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

Go to the source code of this file.

Macros

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

Typedefs

typedef struct RelationDataRelation
 
typedef RelationRelationPtr
 
typedef enum IndexAttrBitmapKind IndexAttrBitmapKind
 

Enumerations

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

Functions

Relation RelationIdGetRelation (Oid relationId)
 
void RelationClose (Relation relation)
 
ListRelationGetFKeyList (Relation relation)
 
ListRelationGetIndexList (Relation relation)
 
ListRelationGetStatExtList (Relation relation)
 
Oid RelationGetPrimaryKeyIndex (Relation relation)
 
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 3341 of file relcache.c.

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

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

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

5937 {
5941 
5942  return 0; /* return value does not matter */
5943 }
int err_generic_string(int field, const char *str)
Definition: elog.c:1514
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3344
#define PG_DIAG_SCHEMA_NAME
Definition: postgres_ext.h:64
#define PG_DIAG_TABLE_NAME
Definition: postgres_ext.h:65
#define RelationGetRelationName(relation)
Definition: rel.h:541
#define RelationGetNamespace(relation)
Definition: rel.h:548

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

5954 {
5955  TupleDesc reldesc = RelationGetDescr(rel);
5956  const char *colname;
5957 
5958  /* Use reldesc if it's a user attribute, else consult the catalogs */
5959  if (attnum > 0 && attnum <= reldesc->natts)
5960  colname = NameStr(TupleDescAttr(reldesc, attnum - 1)->attname);
5961  else
5962  colname = get_attname(RelationGetRelid(rel), attnum, false);
5963 
5964  return errtablecolname(rel, colname);
5965 }
#define NameStr(name)
Definition: c.h:733
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:827
NameData attname
Definition: pg_attribute.h:41
int16 attnum
Definition: pg_attribute.h:74
#define RelationGetRelid(relation)
Definition: rel.h:507
#define RelationGetDescr(relation)
Definition: rel.h:533
int errtablecolname(Relation rel, const char *colname)
Definition: relcache.c:5977
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

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

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

◆ errtablecolname()

int errtablecolname ( Relation  rel,
const char *  colname 
)

Definition at line 5977 of file relcache.c.

5978 {
5979  errtable(rel);
5981 
5982  return 0; /* return value does not matter */
5983 }
#define PG_DIAG_COLUMN_NAME
Definition: postgres_ext.h:66
int errtable(Relation rel)
Definition: relcache.c:5936

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

3921 {
3925 
3926  /* Flag relation as needing eoxact cleanup (to clear these fields) */
3927  EOXactListAdd(relation);
3928 }
#define InvalidSubTransactionId
Definition: c.h:645
#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:781

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

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

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

Referenced by heap_create().

◆ RelationBuildPublicationDesc()

void RelationBuildPublicationDesc ( Relation  relation,
struct PublicationDesc pubdesc 
)

Definition at line 5707 of file relcache.c.

5708 {
5709  List *puboids;
5710  ListCell *lc;
5711  MemoryContext oldcxt;
5712  Oid schemaid;
5713  List *ancestors = NIL;
5714  Oid relid = RelationGetRelid(relation);
5715 
5716  /*
5717  * If not publishable, it publishes no actions. (pgoutput_change() will
5718  * ignore it.)
5719  */
5720  if (!is_publishable_relation(relation))
5721  {
5722  memset(pubdesc, 0, sizeof(PublicationDesc));
5723  pubdesc->rf_valid_for_update = true;
5724  pubdesc->rf_valid_for_delete = true;
5725  pubdesc->cols_valid_for_update = true;
5726  pubdesc->cols_valid_for_delete = true;
5727  return;
5728  }
5729 
5730  if (relation->rd_pubdesc)
5731  {
5732  memcpy(pubdesc, relation->rd_pubdesc, sizeof(PublicationDesc));
5733  return;
5734  }
5735 
5736  memset(pubdesc, 0, sizeof(PublicationDesc));
5737  pubdesc->rf_valid_for_update = true;
5738  pubdesc->rf_valid_for_delete = true;
5739  pubdesc->cols_valid_for_update = true;
5740  pubdesc->cols_valid_for_delete = true;
5741 
5742  /* Fetch the publication membership info. */
5743  puboids = GetRelationPublications(relid);
5744  schemaid = RelationGetNamespace(relation);
5745  puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid));
5746 
5747  if (relation->rd_rel->relispartition)
5748  {
5749  /* Add publications that the ancestors are in too. */
5750  ancestors = get_partition_ancestors(relid);
5751 
5752  foreach(lc, ancestors)
5753  {
5754  Oid ancestor = lfirst_oid(lc);
5755 
5756  puboids = list_concat_unique_oid(puboids,
5757  GetRelationPublications(ancestor));
5758  schemaid = get_rel_namespace(ancestor);
5759  puboids = list_concat_unique_oid(puboids,
5760  GetSchemaPublications(schemaid));
5761  }
5762  }
5763  puboids = list_concat_unique_oid(puboids, GetAllTablesPublications());
5764 
5765  foreach(lc, puboids)
5766  {
5767  Oid pubid = lfirst_oid(lc);
5768  HeapTuple tup;
5769  Form_pg_publication pubform;
5770 
5771  tup = SearchSysCache1(PUBLICATIONOID, ObjectIdGetDatum(pubid));
5772 
5773  if (!HeapTupleIsValid(tup))
5774  elog(ERROR, "cache lookup failed for publication %u", pubid);
5775 
5776  pubform = (Form_pg_publication) GETSTRUCT(tup);
5777 
5778  pubdesc->pubactions.pubinsert |= pubform->pubinsert;
5779  pubdesc->pubactions.pubupdate |= pubform->pubupdate;
5780  pubdesc->pubactions.pubdelete |= pubform->pubdelete;
5781  pubdesc->pubactions.pubtruncate |= pubform->pubtruncate;
5782 
5783  /*
5784  * Check if all columns referenced in the filter expression are part
5785  * of the REPLICA IDENTITY index or not.
5786  *
5787  * If the publication is FOR ALL TABLES then it means the table has no
5788  * row filters and we can skip the validation.
5789  */
5790  if (!pubform->puballtables &&
5791  (pubform->pubupdate || pubform->pubdelete) &&
5792  pub_rf_contains_invalid_column(pubid, relation, ancestors,
5793  pubform->pubviaroot))
5794  {
5795  if (pubform->pubupdate)
5796  pubdesc->rf_valid_for_update = false;
5797  if (pubform->pubdelete)
5798  pubdesc->rf_valid_for_delete = false;
5799  }
5800 
5801  /*
5802  * Check if all columns are part of the REPLICA IDENTITY index or not.
5803  *
5804  * If the publication is FOR ALL TABLES then it means the table has no
5805  * column list and we can skip the validation.
5806  */
5807  if (!pubform->puballtables &&
5808  (pubform->pubupdate || pubform->pubdelete) &&
5809  pub_collist_contains_invalid_column(pubid, relation, ancestors,
5810  pubform->pubviaroot))
5811  {
5812  if (pubform->pubupdate)
5813  pubdesc->cols_valid_for_update = false;
5814  if (pubform->pubdelete)
5815  pubdesc->cols_valid_for_delete = false;
5816  }
5817 
5818  ReleaseSysCache(tup);
5819 
5820  /*
5821  * If we know everything is replicated and the row filter is invalid
5822  * for update and delete, there is no point to check for other
5823  * publications.
5824  */
5825  if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5826  pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5827  !pubdesc->rf_valid_for_update && !pubdesc->rf_valid_for_delete)
5828  break;
5829 
5830  /*
5831  * If we know everything is replicated and the column list is invalid
5832  * for update and delete, there is no point to check for other
5833  * publications.
5834  */
5835  if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5836  pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5837  !pubdesc->cols_valid_for_update && !pubdesc->cols_valid_for_delete)
5838  break;
5839  }
5840 
5841  if (relation->rd_pubdesc)
5842  {
5843  pfree(relation->rd_pubdesc);
5844  relation->rd_pubdesc = NULL;
5845  }
5846 
5847  /* Now save copy of the descriptor in the relcache entry. */
5849  relation->rd_pubdesc = palloc(sizeof(PublicationDesc));
5850  memcpy(relation->rd_pubdesc, pubdesc, sizeof(PublicationDesc));
5851  MemoryContextSwitchTo(oldcxt);
5852 }
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
List * list_concat_unique_oid(List *list1, const List *list2)
Definition: list.c:1469
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1930
void * palloc(Size size)
Definition: mcxt.c:1304
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 * GetSchemaPublications(Oid schemaid)
List * GetRelationPublications(Oid relid)
List * GetAllTablesPublications(void)
bool is_publishable_relation(Relation rel)
FormData_pg_publication * Form_pg_publication
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
unsigned int Oid
Definition: postgres_ext.h:31
bool pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, bool pubviaroot)
bool pub_collist_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, bool pubviaroot)
Definition: pg_list.h:54
PublicationActions pubactions
bool cols_valid_for_delete
bool cols_valid_for_update
PublicationDesc * rd_pubdesc
Definition: rel.h:168
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218

References CacheMemoryContext, PublicationDesc::cols_valid_for_delete, PublicationDesc::cols_valid_for_update, elog, ERROR, 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_collist_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 6762 of file relcache.c.

6763 {
6764  LWLockRelease(RelCacheInitLock);
6765 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1782

References LWLockRelease().

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

◆ RelationCacheInitFilePreInvalidate()

void RelationCacheInitFilePreInvalidate ( void  )

Definition at line 6737 of file relcache.c.

6738 {
6739  char localinitfname[MAXPGPATH];
6740  char sharedinitfname[MAXPGPATH];
6741 
6742  if (DatabasePath)
6743  snprintf(localinitfname, sizeof(localinitfname), "%s/%s",
6745  snprintf(sharedinitfname, sizeof(sharedinitfname), "global/%s",
6747 
6748  LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
6749 
6750  /*
6751  * The files might not be there if no backend has been started since the
6752  * last removal. But complain about failures other than ENOENT with
6753  * ERROR. Fortunately, it's not too late to abort the transaction if we
6754  * can't get rid of the would-be-obsolete init file.
6755  */
6756  if (DatabasePath)
6757  unlink_initfile(localinitfname, ERROR);
6758  unlink_initfile(sharedinitfname, ERROR);
6759 }
char * DatabasePath
Definition: globals.c:101
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1169
@ LW_EXCLUSIVE
Definition: lwlock.h:114
#define MAXPGPATH
#define snprintf
Definition: port.h:238
static void unlink_initfile(const char *initfilename, int elevel)
Definition: relcache.c:6834
#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(), and ProcessCommittedInvalidationMessages().

◆ RelationCacheInitFileRemove()

void RelationCacheInitFileRemove ( void  )

Definition at line 6777 of file relcache.c.

6778 {
6779  const char *tblspcdir = "pg_tblspc";
6780  DIR *dir;
6781  struct dirent *de;
6782  char path[MAXPGPATH + 10 + sizeof(TABLESPACE_VERSION_DIRECTORY)];
6783 
6784  snprintf(path, sizeof(path), "global/%s",
6786  unlink_initfile(path, LOG);
6787 
6788  /* Scan everything in the default tablespace */
6790 
6791  /* Scan the tablespace link directory to find non-default tablespaces */
6792  dir = AllocateDir(tblspcdir);
6793 
6794  while ((de = ReadDirExtended(dir, tblspcdir, LOG)) != NULL)
6795  {
6796  if (strspn(de->d_name, "0123456789") == strlen(de->d_name))
6797  {
6798  /* Scan the tablespace dir for per-database dirs */
6799  snprintf(path, sizeof(path), "%s/%s/%s",
6800  tblspcdir, de->d_name, TABLESPACE_VERSION_DIRECTORY);
6802  }
6803  }
6804 
6805  FreeDir(dir);
6806 }
#define LOG
Definition: elog.h:31
int FreeDir(DIR *dir)
Definition: fd.c:2961
struct dirent * ReadDirExtended(DIR *dir, const char *dirname, int elevel)
Definition: fd.c:2924
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2843
static void RelationCacheInitFileRemoveInDir(const char *tblspcpath)
Definition: relcache.c:6810
#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, ReadDirExtended(), RelationCacheInitFileRemoveInDir(), RELCACHE_INIT_FILENAME, snprintf, TABLESPACE_VERSION_DIRECTORY, and unlink_initfile().

Referenced by StartupXLOG().

◆ RelationCacheInitialize()

void RelationCacheInitialize ( void  )

Definition at line 3946 of file relcache.c.

3947 {
3948  HASHCTL ctl;
3949  int allocsize;
3950 
3951  /*
3952  * make sure cache memory context exists
3953  */
3954  if (!CacheMemoryContext)
3956 
3957  /*
3958  * create hashtable that indexes the relcache
3959  */
3960  ctl.keysize = sizeof(Oid);
3961  ctl.entrysize = sizeof(RelIdCacheEnt);
3962  RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
3963  &ctl, HASH_ELEM | HASH_BLOBS);
3964 
3965  /*
3966  * reserve enough in_progress_list slots for many cases
3967  */
3968  allocsize = 4;
3971  allocsize * sizeof(*in_progress_list));
3972  in_progress_list_maxlen = allocsize;
3973 
3974  /*
3975  * relation mapper needs to be initialized too
3976  */
3978 }
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:1168
tree ctl
Definition: radixtree.h:1807
static int in_progress_list_maxlen
Definition: relcache.c:172
#define INITRELCACHESIZE
Definition: relcache.c:3943
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 3992 of file relcache.c.

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

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

References Assert(), CacheMemoryContext, CLASS_TUPLE_SIZE, criticalRelcachesBuilt, criticalSharedRelcachesBuilt, Desc_pg_attribute, Desc_pg_class, Desc_pg_proc, Desc_pg_type, elog, 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 2968 of file relcache.c.

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

References Assert(), hash_seq_init(), hash_seq_search(), i, in_progress_list, in_progress_list_len, InvalidSubTransactionId, lappend(), lcons(), lfirst, list_free(), NIL, RelationData::rd_createSubid, RelationData::rd_firstRelfilelocatorSubid, RelationData::rd_isnailed, RelationClearRelation(), RelationGetRelid, RelationHasReferenceCountZero, RelationIdCache, RelationInitPhysicalAddr(), RelationIsMapped, RelationMapInvalidateAll(), relcacheInvalsReceived, relidcacheent::reldesc, and smgrreleaseall().

Referenced by InvalidateSystemCachesExtended(), and LocalExecuteInvalidationMessage().

◆ RelationCacheInvalidateEntry()

void RelationCacheInvalidateEntry ( Oid  relationId)

Definition at line 2912 of file relcache.c.

2913 {
2914  Relation relation;
2915 
2916  RelationIdCacheLookup(relationId, relation);
2917 
2918  if (PointerIsValid(relation))
2919  {
2921  RelationFlushRelation(relation);
2922  }
2923  else
2924  {
2925  int i;
2926 
2927  for (i = 0; i < in_progress_list_len; i++)
2928  if (in_progress_list[i].reloid == relationId)
2929  in_progress_list[i].invalidated = true;
2930  }
2931 }
#define PointerIsValid(pointer)
Definition: c.h:750
#define RelationIdCacheLookup(ID, RELATION)
Definition: relcache.c:231
static void RelationFlushRelation(Relation relation)
Definition: relcache.c:2835
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 2193 of file relcache.c.

2194 {
2195  /* Note: no locking manipulations needed */
2197 
2198  RelationCloseCleanup(relation);
2199 }
static void RelationCloseCleanup(Relation relation)
Definition: relcache.c:2202

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

2869 {
2870  Relation relation;
2871 
2872  RelationIdCacheLookup(rid, relation);
2873 
2874  if (!PointerIsValid(relation))
2875  return; /* not in cache, nothing to do */
2876 
2877  if (!RelationHasReferenceCountZero(relation))
2878  elog(ERROR, "relation %u is still open", rid);
2879 
2881  if (relation->rd_createSubid != InvalidSubTransactionId ||
2883  {
2884  /*
2885  * In the event of subtransaction rollback, we must not forget
2886  * rd_*Subid. Mark the entry "dropped" so RelationClearRelation()
2887  * invalidates it in lieu of destroying it. (If we're in a top
2888  * transaction, we could opt to destroy the entry.)
2889  */
2891  }
2892 
2893  RelationClearRelation(relation, false);
2894 }

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

Referenced by heap_drop_with_catalog(), and index_drop().

◆ RelationGetDummyIndexExpressions()

List* RelationGetDummyIndexExpressions ( Relation  relation)

Definition at line 5075 of file relcache.c.

5076 {
5077  List *result;
5078  Datum exprsDatum;
5079  bool isnull;
5080  char *exprsString;
5081  List *rawExprs;
5082  ListCell *lc;
5083 
5084  /* Quick exit if there is nothing to do. */
5085  if (relation->rd_indextuple == NULL ||
5086  heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
5087  return NIL;
5088 
5089  /* Extract raw node tree(s) from index tuple. */
5090  exprsDatum = heap_getattr(relation->rd_indextuple,
5091  Anum_pg_index_indexprs,
5093  &isnull);
5094  Assert(!isnull);
5095  exprsString = TextDatumGetCString(exprsDatum);
5096  rawExprs = (List *) stringToNode(exprsString);
5097  pfree(exprsString);
5098 
5099  /* Construct null Consts; the typlen and typbyval are arbitrary. */
5100  result = NIL;
5101  foreach(lc, rawExprs)
5102  {
5103  Node *rawExpr = (Node *) lfirst(lc);
5104 
5105  result = lappend(result,
5106  makeConst(exprType(rawExpr),
5107  exprTypmod(rawExpr),
5108  exprCollation(rawExpr),
5109  1,
5110  (Datum) 0,
5111  true,
5112  true));
5113  }
5114 
5115  return result;
5116 }
#define TextDatumGetCString(d)
Definition: builtins.h:98
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:455
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:792
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:301
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:298
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:816
uintptr_t Datum
Definition: postgres.h:64
void * stringToNode(const char *str)
Definition: read.c:90
static TupleDesc GetPgIndexDescriptor(void)
Definition: relcache.c:4413
Definition: nodes.h:129
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 5572 of file relcache.c.

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

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

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

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

◆ RelationGetIdentityKeyBitmap()

Bitmapset* RelationGetIdentityKeyBitmap ( Relation  relation)

Definition at line 5495 of file relcache.c.

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

5876 {
5877  MemoryContext oldcxt;
5878  bytea **opts = relation->rd_opcoptions;
5879  Oid relid = RelationGetRelid(relation);
5880  int natts = RelationGetNumberOfAttributes(relation); /* XXX
5881  * IndexRelationGetNumberOfKeyAttributes */
5882  int i;
5883 
5884  /* Try to copy cached options. */
5885  if (opts)
5886  return copy ? CopyIndexAttOptions(opts, natts) : opts;
5887 
5888  /* Get and parse opclass options. */
5889  opts = palloc0(sizeof(*opts) * natts);
5890 
5891  for (i = 0; i < natts; i++)
5892  {
5893  if (criticalRelcachesBuilt && relid != AttributeRelidNumIndexId)
5894  {
5895  Datum attoptions = get_attoptions(relid, i + 1);
5896 
5897  opts[i] = index_opclass_options(relation, i + 1, attoptions, false);
5898 
5899  if (attoptions != (Datum) 0)
5900  pfree(DatumGetPointer(attoptions));
5901  }
5902  }
5903 
5904  /* Copy parsed options to the cache. */
5905  oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
5906  relation->rd_opcoptions = CopyIndexAttOptions(opts, natts);
5907  MemoryContextSwitchTo(oldcxt);
5908 
5909  if (copy)
5910  return opts;
5911 
5912  for (i = 0; i < natts; i++)
5913  {
5914  if (opts[i])
5915  pfree(opts[i]);
5916  }
5917 
5918  pfree(opts);
5919 
5920  return relation->rd_opcoptions;
5921 }
bytea * index_opclass_options(Relation indrel, AttrNumber attnum, Datum attoptions, bool validate)
Definition: indexam.c:999
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:970
static AmcheckOptions opts
Definition: pg_amcheck.c:111
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:513
static bytea ** CopyIndexAttOptions(bytea **srcopts, int natts)
Definition: relcache.c:5855
bytea ** rd_opcoptions
Definition: rel.h:218
Definition: c.h:674

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

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

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 ATExecDropNotNull(), ATInheritAdjustNotNulls(), dropconstraint_internal(), ExecUpdateLockMode(), ExtractReplicaIdentity(), GetParentedForeignKeyRefs(), heap_update(), logicalrep_rel_mark_updatable(), MergeAttributes(), pub_collist_contains_invalid_column(), pub_rf_contains_invalid_column(), and transformTableLikeClause().

◆ RelationGetIndexExpressions()

List* RelationGetIndexExpressions ( Relation  relation)

Definition at line 5016 of file relcache.c.

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

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

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

◆ RelationGetIndexList()

List* RelationGetIndexList ( Relation  relation)

Definition at line 4751 of file relcache.c.

4752 {
4753  Relation indrel;
4754  SysScanDesc indscan;
4755  ScanKeyData skey;
4756  HeapTuple htup;
4757  List *result;
4758  List *oldlist;
4759  char replident = relation->rd_rel->relreplident;
4760  Oid pkeyIndex = InvalidOid;
4761  Oid candidateIndex = InvalidOid;
4762  bool pkdeferrable = false;
4763  MemoryContext oldcxt;
4764 
4765  /* Quick exit if we already computed the list. */
4766  if (relation->rd_indexvalid)
4767  return list_copy(relation->rd_indexlist);
4768 
4769  /*
4770  * We build the list we intend to return (in the caller's context) while
4771  * doing the scan. After successfully completing the scan, we copy that
4772  * list into the relcache entry. This avoids cache-context memory leakage
4773  * if we get some sort of error partway through.
4774  */
4775  result = NIL;
4776 
4777  /* Prepare to scan pg_index for entries having indrelid = this rel. */
4778  ScanKeyInit(&skey,
4779  Anum_pg_index_indrelid,
4780  BTEqualStrategyNumber, F_OIDEQ,
4781  ObjectIdGetDatum(RelationGetRelid(relation)));
4782 
4783  indrel = table_open(IndexRelationId, AccessShareLock);
4784  indscan = systable_beginscan(indrel, IndexIndrelidIndexId, true,
4785  NULL, 1, &skey);
4786 
4787  while (HeapTupleIsValid(htup = systable_getnext(indscan)))
4788  {
4790 
4791  /*
4792  * Ignore any indexes that are currently being dropped. This will
4793  * prevent them from being searched, inserted into, or considered in
4794  * HOT-safety decisions. It's unsafe to touch such an index at all
4795  * since its catalog entries could disappear at any instant.
4796  */
4797  if (!index->indislive)
4798  continue;
4799 
4800  /* add index's OID to result list */
4801  result = lappend_oid(result, index->indexrelid);
4802 
4803  /*
4804  * Non-unique or predicate indexes aren't interesting for either oid
4805  * indexes or replication identity indexes, so don't check them.
4806  * Deferred ones are not useful for replication identity either; but
4807  * we do include them if they are PKs.
4808  */
4809  if (!index->indisunique ||
4810  !heap_attisnull(htup, Anum_pg_index_indpred, NULL))
4811  continue;
4812 
4813  /*
4814  * Remember primary key index, if any. We do this only if the index
4815  * is valid; but if the table is partitioned, then we do it even if
4816  * it's invalid.
4817  *
4818  * The reason for returning invalid primary keys for foreign tables is
4819  * because of pg_dump of NOT NULL constraints, and the fact that PKs
4820  * remain marked invalid until the partitions' PKs are attached to it.
4821  * If we make rd_pkindex invalid, then the attnotnull flag is reset
4822  * after the PK is created, which causes the ALTER INDEX ATTACH
4823  * PARTITION to fail with 'column ... is not marked NOT NULL'. With
4824  * this, dropconstraint_internal() will believe that the columns must
4825  * not have attnotnull reset, so the PKs-on-partitions can be attached
4826  * correctly, until finally the PK-on-parent is marked valid.
4827  *
4828  * Also, this doesn't harm anything, because rd_pkindex is not a
4829  * "real" index anyway, but a RELKIND_PARTITIONED_INDEX.
4830  */
4831  if (index->indisprimary &&
4832  (index->indisvalid ||
4833  relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE))
4834  {
4835  pkeyIndex = index->indexrelid;
4836  pkdeferrable = !index->indimmediate;
4837  }
4838 
4839  if (!index->indimmediate)
4840  continue;
4841 
4842  if (!index->indisvalid)
4843  continue;
4844 
4845  /* remember explicitly chosen replica index */
4846  if (index->indisreplident)
4847  candidateIndex = index->indexrelid;
4848  }
4849 
4850  systable_endscan(indscan);
4851 
4852  table_close(indrel, AccessShareLock);
4853 
4854  /* Sort the result list into OID order, per API spec. */
4855  list_sort(result, list_oid_cmp);
4856 
4857  /* Now save a copy of the completed list in the relcache entry. */
4859  oldlist = relation->rd_indexlist;
4860  relation->rd_indexlist = list_copy(result);
4861  relation->rd_pkindex = pkeyIndex;
4862  relation->rd_ispkdeferrable = pkdeferrable;
4863  if (replident == REPLICA_IDENTITY_DEFAULT && OidIsValid(pkeyIndex) && !pkdeferrable)
4864  relation->rd_replidindex = pkeyIndex;
4865  else if (replident == REPLICA_IDENTITY_INDEX && OidIsValid(candidateIndex))
4866  relation->rd_replidindex = candidateIndex;
4867  else
4868  relation->rd_replidindex = InvalidOid;
4869  relation->rd_indexvalid = true;
4870  MemoryContextSwitchTo(oldcxt);
4871 
4872  /* Don't leak the old list, if there is one */
4873  list_free(oldlist);
4874 
4875  return result;
4876 }
void list_sort(List *list, list_sort_comparator cmp)
Definition: list.c:1674
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
List * list_copy(const List *oldlist)
Definition: list.c:1573
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:95

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(), ATExecChangeOwner(), ATExecSetTableSpace(), AttachPartitionEnsureIndexes(), calculate_indexes_size(), calculate_toast_table_size(), cluster(), DefineIndex(), DefineRelation(), DetachPartitionFinalize(), do_analyze_rel(), ExecInitPartitionInfo(), ExecOpenIndices(), ExecRefreshMatView(), expandTableLikeClause(), FindUsableIndexForReplicaIdentityFull(), get_relation_info(), GetParentedForeignKeyRefs(), index_get_partition(), infer_arbiter_indexes(), mark_index_clustered(), refresh_by_match_merge(), 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 5129 of file relcache.c.

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

◆ RelationGetPrimaryKeyIndex()

Oid RelationGetPrimaryKeyIndex ( Relation  relation)

Definition at line 4970 of file relcache.c.

4971 {
4972  List *ilist;
4973 
4974  if (!relation->rd_indexvalid)
4975  {
4976  /* RelationGetIndexList does the heavy lifting. */
4977  ilist = RelationGetIndexList(relation);
4978  list_free(ilist);
4979  Assert(relation->rd_indexvalid);
4980  }
4981 
4982  return relation->rd_ispkdeferrable ? InvalidOid : relation->rd_pkindex;
4983 }

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

Referenced by GetRelationIdentityOrPK().

◆ RelationGetReplicaIndex()

Oid RelationGetReplicaIndex ( Relation  relation)

Definition at line 4991 of file relcache.c.

4992 {
4993  List *ilist;
4994 
4995  if (!relation->rd_indexvalid)
4996  {
4997  /* RelationGetIndexList does the heavy lifting. */
4998  ilist = RelationGetIndexList(relation);
4999  list_free(ilist);
5000  Assert(relation->rd_indexvalid);
5001  }
5002 
5003  return relation->rd_replidindex;
5004 }

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

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

◆ RelationIdGetRelation()

Relation RelationIdGetRelation ( Oid  relationId)

Definition at line 2062 of file relcache.c.

2063 {
2064  Relation rd;
2065 
2066  /* Make sure we're in an xact, even if this ends up being a cache hit */
2068 
2069  /*
2070  * first try to find reldesc in the cache
2071  */
2072  RelationIdCacheLookup(relationId, rd);
2073 
2074  if (RelationIsValid(rd))
2075  {
2076  /* return NULL for dropped relations */
2078  {
2079  Assert(!rd->rd_isvalid);
2080  return NULL;
2081  }
2082 
2084  /* revalidate cache entry if necessary */
2085  if (!rd->rd_isvalid)
2086  {
2087  /*
2088  * Indexes only have a limited number of possible schema changes,
2089  * and we don't want to use the full-blown procedure because it's
2090  * a headache for indexes that reload itself depends on.
2091  */
2092  if (rd->rd_rel->relkind == RELKIND_INDEX ||
2093  rd->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
2095  else
2096  RelationClearRelation(rd, true);
2097 
2098  /*
2099  * Normally entries need to be valid here, but before the relcache
2100  * has been initialized, not enough infrastructure exists to
2101  * perform pg_class lookups. The structure of such entries doesn't
2102  * change, but we still want to update the rd_rel entry. So
2103  * rd_isvalid = false is left in place for a later lookup.
2104  */
2105  Assert(rd->rd_isvalid ||
2107  }
2108  return rd;
2109  }
2110 
2111  /*
2112  * no reldesc in the cache, so have RelationBuildDesc() build one and add
2113  * it.
2114  */
2115  rd = RelationBuildDesc(relationId, true);
2116  if (RelationIsValid(rd))
2118  return rd;
2119 }
static Relation RelationBuildDesc(Oid targetRelId, bool insertIt)
Definition: relcache.c:1039
static void RelationReloadIndexInfo(Relation relation)
Definition: relcache.c:2256
bool IsTransactionState(void)
Definition: xact.c:379

References Assert(), criticalRelcachesBuilt, InvalidSubTransactionId, IsTransactionState(), RelationData::rd_droppedSubid, RelationData::rd_isnailed, RelationData::rd_isvalid, RelationData::rd_rel, RelationBuildDesc(), RelationClearRelation(), RelationIdCacheLookup, RelationIncrementReferenceCount(), RelationIsValid, and RelationReloadIndexInfo().

Referenced by 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 6697 of file relcache.c.

6698 {
6699  if (relationId == SharedSecLabelRelationId ||
6700  relationId == TriggerRelidNameIndexId ||
6701  relationId == DatabaseNameIndexId ||
6702  relationId == SharedSecLabelObjectIndexId)
6703  {
6704  /*
6705  * If this Assert fails, we don't need the applicable special case
6706  * anymore.
6707  */
6708  Assert(!RelationSupportsSysCache(relationId));
6709  return true;
6710  }
6711  return RelationSupportsSysCache(relationId);
6712 }
bool RelationSupportsSysCache(Oid relid)
Definition: syscache.c:649

References Assert(), and RelationSupportsSysCache().

Referenced by RegisterRelcacheInvalidation(), and write_relcache_init_file().

◆ RelationInitIndexAccessInfo()

void RelationInitIndexAccessInfo ( Relation  relation)

Definition at line 1425 of file relcache.c.

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

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

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

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

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

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, 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, SearchSysCacheCopy1, smgrclose(), smgrdounlinkall(), smgropen(), HeapTupleData::t_self, table_close(), table_open(), and table_relation_set_new_filelocator().

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

Variable Documentation

◆ criticalRelcachesBuilt

◆ criticalSharedRelcachesBuilt