1 /*-------------------------------------------------------------------------
4 * POSTGRES relation descriptor cache code
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/utils/cache/relcache.c,v 1.278 2008/12/03 13:05:22 heikki Exp $
13 *-------------------------------------------------------------------------
17 * RelationCacheInitialize - initialize relcache (to empty)
18 * RelationCacheInitializePhase2 - finish initializing relcache
19 * RelationIdGetRelation - get a reldesc by relation id
20 * RelationClose - close an open relation
23 * The following code contains many undocumented hacks. Please be
32 #include "access/genam.h"
33 #include "access/heapam.h"
34 #include "access/reloptions.h"
35 #include "access/sysattr.h"
36 #include "access/xact.h"
37 #include "catalog/catalog.h"
38 #include "catalog/index.h"
39 #include "catalog/indexing.h"
40 #include "catalog/namespace.h"
41 #include "catalog/pg_amop.h"
42 #include "catalog/pg_amproc.h"
43 #include "catalog/pg_attrdef.h"
44 #include "catalog/pg_authid.h"
45 #include "catalog/pg_constraint.h"
46 #include "catalog/pg_namespace.h"
47 #include "catalog/pg_opclass.h"
48 #include "catalog/pg_proc.h"
49 #include "catalog/pg_rewrite.h"
50 #include "catalog/pg_type.h"
51 #include "commands/trigger.h"
52 #include "miscadmin.h"
53 #include "optimizer/clauses.h"
54 #include "optimizer/planmain.h"
55 #include "optimizer/prep.h"
56 #include "optimizer/var.h"
57 #include "rewrite/rewriteDefine.h"
58 #include "storage/fd.h"
59 #include "storage/lmgr.h"
60 #include "storage/smgr.h"
61 #include "utils/builtins.h"
62 #include "utils/fmgroids.h"
63 #include "utils/inval.h"
64 #include "utils/memutils.h"
65 #include "utils/relcache.h"
66 #include "utils/resowner.h"
67 #include "utils/syscache.h"
68 #include "utils/tqual.h"
69 #include "utils/typcache.h"
73 * name of relcache init file, used to speed up backend startup
75 #define RELCACHE_INIT_FILENAME "pg_internal.init"
77 #define RELCACHE_INIT_FILEMAGIC 0x573264 /* version ID value */
80 * hardcoded tuple descriptors. see include/catalog/pg_attribute.h
82 static FormData_pg_attribute Desc_pg_class[Natts_pg_class] = {Schema_pg_class};
83 static FormData_pg_attribute Desc_pg_attribute[Natts_pg_attribute] = {Schema_pg_attribute};
84 static FormData_pg_attribute Desc_pg_proc[Natts_pg_proc] = {Schema_pg_proc};
85 static FormData_pg_attribute Desc_pg_type[Natts_pg_type] = {Schema_pg_type};
86 static FormData_pg_attribute Desc_pg_index[Natts_pg_index] = {Schema_pg_index};
89 * Hash tables that index the relation cache
91 * We used to index the cache by both name and OID, but now there
92 * is only an index by OID.
94 typedef struct relidcacheent
100 static HTAB *RelationIdCache;
103 * This flag is false until we have prepared the critical relcache entries
104 * that are needed to do indexscans on the tables read by relcache building.
106 bool criticalRelcachesBuilt = false;
109 * This counter counts relcache inval events received since backend startup
110 * (but only for rels that are actually in cache). Presently, we use it only
111 * to detect whether data about to be written by write_relcache_init_file()
112 * might already be obsolete.
114 static long relcacheInvalsReceived = 0L;
117 * This list remembers the OIDs of the relations cached in the relcache
120 static List *initFileRelationIds = NIL;
123 * This flag lets us optimize away work in AtEO(Sub)Xact_RelationCache().
125 static bool need_eoxact_work = false;
129 * macros to manipulate the lookup hashtables
131 #define RelationCacheInsert(RELATION) \
133 RelIdCacheEnt *idhentry; bool found; \
134 idhentry = (RelIdCacheEnt*)hash_search(RelationIdCache, \
135 (void *) &(RELATION->rd_id), \
138 /* used to give notice if found -- now just keep quiet */ \
139 idhentry->reldesc = RELATION; \
142 #define RelationIdCacheLookup(ID, RELATION) \
144 RelIdCacheEnt *hentry; \
145 hentry = (RelIdCacheEnt*)hash_search(RelationIdCache, \
146 (void *) &(ID), HASH_FIND,NULL); \
148 RELATION = hentry->reldesc; \
153 #define RelationCacheDelete(RELATION) \
155 RelIdCacheEnt *idhentry; \
156 idhentry = (RelIdCacheEnt*)hash_search(RelationIdCache, \
157 (void *) &(RELATION->rd_id), \
158 HASH_REMOVE, NULL); \
159 if (idhentry == NULL) \
160 elog(WARNING, "trying to delete a rd_id reldesc that does not exist"); \
165 * Special cache for opclass-related information
167 * Note: only default operators and support procs get cached, ie, those with
168 * lefttype = righttype = opcintype.
170 typedef struct opclasscacheent
172 Oid opclassoid; /* lookup key: OID of opclass */
173 bool valid; /* set TRUE after successful fill-in */
174 StrategyNumber numStrats; /* max # of strategies (from pg_am) */
175 StrategyNumber numSupport; /* max # of support procs (from pg_am) */
176 Oid opcfamily; /* OID of opclass's family */
177 Oid opcintype; /* OID of opclass's declared input type */
178 Oid *operatorOids; /* strategy operators' OIDs */
179 RegProcedure *supportProcs; /* support procs */
182 static HTAB *OpClassCache = NULL;
185 /* non-export function prototypes */
187 static void RelationClearRelation(Relation relation, bool rebuild);
189 static void RelationReloadIndexInfo(Relation relation);
190 static void RelationFlushRelation(Relation relation);
191 static bool load_relcache_init_file(void);
192 static void write_relcache_init_file(void);
193 static void write_item(const void *data, Size len, FILE *fp);
195 static void formrdesc(const char *relationName, Oid relationReltype,
196 bool hasoids, int natts, FormData_pg_attribute *att);
198 static HeapTuple ScanPgRelation(Oid targetRelId, bool indexOK);
199 static Relation AllocateRelationDesc(Relation relation, Form_pg_class relp);
200 static void RelationParseRelOptions(Relation relation, HeapTuple tuple);
201 static void RelationBuildTupleDesc(Relation relation);
202 static Relation RelationBuildDesc(Oid targetRelId, Relation oldrelation);
203 static void RelationInitPhysicalAddr(Relation relation);
204 static TupleDesc GetPgClassDescriptor(void);
205 static TupleDesc GetPgIndexDescriptor(void);
206 static void AttrDefaultFetch(Relation relation);
207 static void CheckConstraintFetch(Relation relation);
208 static List *insert_ordered_oid(List *list, Oid datum);
209 static void IndexSupportInitialize(oidvector *indclass,
211 RegProcedure *indexSupport,
214 StrategyNumber maxStrategyNumber,
215 StrategyNumber maxSupportNumber,
216 AttrNumber maxAttributeNumber);
217 static OpClassCacheEnt *LookupOpclassInfo(Oid operatorClassOid,
218 StrategyNumber numStrats,
219 StrategyNumber numSupport);
225 * This is used by RelationBuildDesc to find a pg_class
226 * tuple matching targetRelId. The caller must hold at least
227 * AccessShareLock on the target relid to prevent concurrent-update
228 * scenarios --- else our SnapshotNow scan might fail to find any
229 * version that it thinks is live.
231 * NB: the returned tuple has been copied into palloc'd storage
232 * and must eventually be freed with heap_freetuple.
235 ScanPgRelation(Oid targetRelId, bool indexOK)
237 HeapTuple pg_class_tuple;
238 Relation pg_class_desc;
239 SysScanDesc pg_class_scan;
246 ObjectIdAttributeNumber,
247 BTEqualStrategyNumber, F_OIDEQ,
248 ObjectIdGetDatum(targetRelId));
251 * Open pg_class and fetch a tuple. Force heap scan if we haven't yet
252 * built the critical relcache entries (this includes initdb and startup
253 * without a pg_internal.init file). The caller can also force a heap
254 * scan by setting indexOK == false.
256 pg_class_desc = heap_open(RelationRelationId, AccessShareLock);
257 pg_class_scan = systable_beginscan(pg_class_desc, ClassOidIndexId,
258 indexOK && criticalRelcachesBuilt,
262 pg_class_tuple = systable_getnext(pg_class_scan);
265 * Must copy tuple before releasing buffer.
267 if (HeapTupleIsValid(pg_class_tuple))
268 pg_class_tuple = heap_copytuple(pg_class_tuple);
271 systable_endscan(pg_class_scan);
272 heap_close(pg_class_desc, AccessShareLock);
274 return pg_class_tuple;
278 * AllocateRelationDesc
280 * This is used to allocate memory for a new relation descriptor
281 * and initialize the rd_rel field.
283 * If 'relation' is NULL, allocate a new RelationData object.
284 * If not, reuse the given object (that path is taken only when
285 * we have to rebuild a relcache entry during RelationClearRelation).
288 AllocateRelationDesc(Relation relation, Form_pg_class relp)
290 MemoryContext oldcxt;
291 Form_pg_class relationForm;
293 /* Relcache entries must live in CacheMemoryContext */
294 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
297 * allocate space for new relation descriptor, if needed
299 if (relation == NULL)
300 relation = (Relation) palloc(sizeof(RelationData));
303 * clear all fields of reldesc
305 MemSet(relation, 0, sizeof(RelationData));
306 relation->rd_targblock = InvalidBlockNumber;
307 relation->rd_fsm_nblocks = InvalidBlockNumber;
308 relation->rd_vm_nblocks = InvalidBlockNumber;
310 /* make sure relation is marked as having no open file yet */
311 relation->rd_smgr = NULL;
314 * Copy the relation tuple form
316 * We only allocate space for the fixed fields, ie, CLASS_TUPLE_SIZE. The
317 * variable-length fields (relacl, reloptions) are NOT stored in the
318 * relcache --- there'd be little point in it, since we don't copy the
319 * tuple's nulls bitmap and hence wouldn't know if the values are valid.
320 * Bottom line is that relacl *cannot* be retrieved from the relcache. Get
321 * it from the syscache if you need it. The same goes for the original
322 * form of reloptions (however, we do store the parsed form of reloptions
325 relationForm = (Form_pg_class) palloc(CLASS_TUPLE_SIZE);
327 memcpy(relationForm, relp, CLASS_TUPLE_SIZE);
329 /* initialize relation tuple form */
330 relation->rd_rel = relationForm;
332 /* and allocate attribute tuple form storage */
333 relation->rd_att = CreateTemplateTupleDesc(relationForm->relnatts,
334 relationForm->relhasoids);
335 /* which we mark as a reference-counted tupdesc */
336 relation->rd_att->tdrefcount = 1;
338 MemoryContextSwitchTo(oldcxt);
344 * RelationParseRelOptions
345 * Convert pg_class.reloptions into pre-parsed rd_options
347 * tuple is the real pg_class tuple (not rd_rel!) for relation
349 * Note: rd_rel and (if an index) rd_am must be valid already
352 RelationParseRelOptions(Relation relation, HeapTuple tuple)
358 relation->rd_options = NULL;
360 /* Fall out if relkind should not have options */
361 switch (relation->rd_rel->relkind)
363 case RELKIND_RELATION:
364 case RELKIND_TOASTVALUE:
365 case RELKIND_UNCATALOGED:
373 * Fetch reloptions from tuple; have to use a hardwired descriptor because
374 * we might not have any other for pg_class yet (consider executing this
375 * code for pg_class itself)
377 datum = fastgetattr(tuple,
378 Anum_pg_class_reloptions,
379 GetPgClassDescriptor(),
384 /* Parse into appropriate format; don't error out here */
385 switch (relation->rd_rel->relkind)
387 case RELKIND_RELATION:
388 case RELKIND_TOASTVALUE:
389 case RELKIND_UNCATALOGED:
390 options = heap_reloptions(relation->rd_rel->relkind, datum,
394 options = index_reloptions(relation->rd_am->amoptions, datum,
398 Assert(false); /* can't get here */
399 options = NULL; /* keep compiler quiet */
403 /* Copy parsed data into CacheMemoryContext */
406 relation->rd_options = MemoryContextAlloc(CacheMemoryContext,
408 memcpy(relation->rd_options, options, VARSIZE(options));
413 * RelationBuildTupleDesc
415 * Form the relation's tuple descriptor from information in
416 * the pg_attribute, pg_attrdef & pg_constraint system catalogs.
419 RelationBuildTupleDesc(Relation relation)
421 HeapTuple pg_attribute_tuple;
422 Relation pg_attribute_desc;
423 SysScanDesc pg_attribute_scan;
427 AttrDefault *attrdef = NULL;
430 /* copy some fields from pg_class row to rd_att */
431 relation->rd_att->tdtypeid = relation->rd_rel->reltype;
432 relation->rd_att->tdtypmod = -1; /* unnecessary, but... */
433 relation->rd_att->tdhasoid = relation->rd_rel->relhasoids;
435 constr = (TupleConstr *) MemoryContextAlloc(CacheMemoryContext,
436 sizeof(TupleConstr));
437 constr->has_not_null = false;
440 * Form a scan key that selects only user attributes (attnum > 0).
441 * (Eliminating system attribute rows at the index level is lots faster
442 * than fetching them.)
444 ScanKeyInit(&skey[0],
445 Anum_pg_attribute_attrelid,
446 BTEqualStrategyNumber, F_OIDEQ,
447 ObjectIdGetDatum(RelationGetRelid(relation)));
448 ScanKeyInit(&skey[1],
449 Anum_pg_attribute_attnum,
450 BTGreaterStrategyNumber, F_INT2GT,
454 * Open pg_attribute and begin a scan. Force heap scan if we haven't yet
455 * built the critical relcache entries (this includes initdb and startup
456 * without a pg_internal.init file).
458 pg_attribute_desc = heap_open(AttributeRelationId, AccessShareLock);
459 pg_attribute_scan = systable_beginscan(pg_attribute_desc,
460 AttributeRelidNumIndexId,
461 criticalRelcachesBuilt,
466 * add attribute data to relation->rd_att
468 need = relation->rd_rel->relnatts;
470 while (HeapTupleIsValid(pg_attribute_tuple = systable_getnext(pg_attribute_scan)))
472 Form_pg_attribute attp;
474 attp = (Form_pg_attribute) GETSTRUCT(pg_attribute_tuple);
476 if (attp->attnum <= 0 ||
477 attp->attnum > relation->rd_rel->relnatts)
478 elog(ERROR, "invalid attribute number %d for %s",
479 attp->attnum, RelationGetRelationName(relation));
481 memcpy(relation->rd_att->attrs[attp->attnum - 1],
483 ATTRIBUTE_TUPLE_SIZE);
485 /* Update constraint/default info */
486 if (attp->attnotnull)
487 constr->has_not_null = true;
492 attrdef = (AttrDefault *)
493 MemoryContextAllocZero(CacheMemoryContext,
494 relation->rd_rel->relnatts *
495 sizeof(AttrDefault));
496 attrdef[ndef].adnum = attp->attnum;
497 attrdef[ndef].adbin = NULL;
506 * end the scan and close the attribute relation
508 systable_endscan(pg_attribute_scan);
509 heap_close(pg_attribute_desc, AccessShareLock);
512 elog(ERROR, "catalog is missing %d attribute(s) for relid %u",
513 need, RelationGetRelid(relation));
516 * The attcacheoff values we read from pg_attribute should all be -1
517 * ("unknown"). Verify this if assert checking is on. They will be
518 * computed when and if needed during tuple access.
520 #ifdef USE_ASSERT_CHECKING
524 for (i = 0; i < relation->rd_rel->relnatts; i++)
525 Assert(relation->rd_att->attrs[i]->attcacheoff == -1);
530 * However, we can easily set the attcacheoff value for the first
531 * attribute: it must be zero. This eliminates the need for special cases
532 * for attnum=1 that used to exist in fastgetattr() and index_getattr().
534 if (relation->rd_rel->relnatts > 0)
535 relation->rd_att->attrs[0]->attcacheoff = 0;
538 * Set up constraint/default info
540 if (constr->has_not_null || ndef > 0 || relation->rd_rel->relchecks)
542 relation->rd_att->constr = constr;
544 if (ndef > 0) /* DEFAULTs */
546 if (ndef < relation->rd_rel->relnatts)
547 constr->defval = (AttrDefault *)
548 repalloc(attrdef, ndef * sizeof(AttrDefault));
550 constr->defval = attrdef;
551 constr->num_defval = ndef;
552 AttrDefaultFetch(relation);
555 constr->num_defval = 0;
557 if (relation->rd_rel->relchecks > 0) /* CHECKs */
559 constr->num_check = relation->rd_rel->relchecks;
560 constr->check = (ConstrCheck *)
561 MemoryContextAllocZero(CacheMemoryContext,
562 constr->num_check * sizeof(ConstrCheck));
563 CheckConstraintFetch(relation);
566 constr->num_check = 0;
571 relation->rd_att->constr = NULL;
576 * RelationBuildRuleLock
578 * Form the relation's rewrite rules from information in
579 * the pg_rewrite system catalog.
581 * Note: The rule parsetrees are potentially very complex node structures.
582 * To allow these trees to be freed when the relcache entry is flushed,
583 * we make a private memory context to hold the RuleLock information for
584 * each relcache entry that has associated rules. The context is used
585 * just for rule info, not for any other subsidiary data of the relcache
586 * entry, because that keeps the update logic in RelationClearRelation()
587 * manageable. The other subsidiary data structures are simple enough
588 * to be easy to free explicitly, anyway.
591 RelationBuildRuleLock(Relation relation)
593 MemoryContext rulescxt;
594 MemoryContext oldcxt;
595 HeapTuple rewrite_tuple;
596 Relation rewrite_desc;
597 TupleDesc rewrite_tupdesc;
598 SysScanDesc rewrite_scan;
606 * Make the private context. Parameters are set on the assumption that
607 * it'll probably not contain much data.
609 rulescxt = AllocSetContextCreate(CacheMemoryContext,
610 RelationGetRelationName(relation),
611 ALLOCSET_SMALL_MINSIZE,
612 ALLOCSET_SMALL_INITSIZE,
613 ALLOCSET_SMALL_MAXSIZE);
614 relation->rd_rulescxt = rulescxt;
617 * allocate an array to hold the rewrite rules (the array is extended if
621 rules = (RewriteRule **)
622 MemoryContextAlloc(rulescxt, sizeof(RewriteRule *) * maxlocks);
629 Anum_pg_rewrite_ev_class,
630 BTEqualStrategyNumber, F_OIDEQ,
631 ObjectIdGetDatum(RelationGetRelid(relation)));
634 * open pg_rewrite and begin a scan
636 * Note: since we scan the rules using RewriteRelRulenameIndexId, we will
637 * be reading the rules in name order, except possibly during
638 * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
639 * ensures that rules will be fired in name order.
641 rewrite_desc = heap_open(RewriteRelationId, AccessShareLock);
642 rewrite_tupdesc = RelationGetDescr(rewrite_desc);
643 rewrite_scan = systable_beginscan(rewrite_desc,
644 RewriteRelRulenameIndexId,
648 while (HeapTupleIsValid(rewrite_tuple = systable_getnext(rewrite_scan)))
650 Form_pg_rewrite rewrite_form = (Form_pg_rewrite) GETSTRUCT(rewrite_tuple);
656 rule = (RewriteRule *) MemoryContextAlloc(rulescxt,
657 sizeof(RewriteRule));
659 rule->ruleId = HeapTupleGetOid(rewrite_tuple);
661 rule->event = rewrite_form->ev_type - '0';
662 rule->attrno = rewrite_form->ev_attr;
663 rule->enabled = rewrite_form->ev_enabled;
664 rule->isInstead = rewrite_form->is_instead;
667 * Must use heap_getattr to fetch ev_action and ev_qual. Also, the
668 * rule strings are often large enough to be toasted. To avoid
669 * leaking memory in the caller's context, do the detoasting here so
670 * we can free the detoasted version.
672 rule_datum = heap_getattr(rewrite_tuple,
673 Anum_pg_rewrite_ev_action,
677 rule_str = TextDatumGetCString(rule_datum);
678 oldcxt = MemoryContextSwitchTo(rulescxt);
679 rule->actions = (List *) stringToNode(rule_str);
680 MemoryContextSwitchTo(oldcxt);
683 rule_datum = heap_getattr(rewrite_tuple,
684 Anum_pg_rewrite_ev_qual,
688 rule_str = TextDatumGetCString(rule_datum);
689 oldcxt = MemoryContextSwitchTo(rulescxt);
690 rule->qual = (Node *) stringToNode(rule_str);
691 MemoryContextSwitchTo(oldcxt);
695 * We want the rule's table references to be checked as though by the
696 * table owner, not the user referencing the rule. Therefore, scan
697 * through the rule's actions and set the checkAsUser field on all
698 * rtable entries. We have to look at the qual as well, in case it
701 * The reason for doing this when the rule is loaded, rather than when
702 * it is stored, is that otherwise ALTER TABLE OWNER would have to
703 * grovel through stored rules to update checkAsUser fields. Scanning
704 * the rule tree during load is relatively cheap (compared to
705 * constructing it in the first place), so we do it here.
707 setRuleCheckAsUser((Node *) rule->actions, relation->rd_rel->relowner);
708 setRuleCheckAsUser(rule->qual, relation->rd_rel->relowner);
710 if (numlocks >= maxlocks)
713 rules = (RewriteRule **)
714 repalloc(rules, sizeof(RewriteRule *) * maxlocks);
716 rules[numlocks++] = rule;
720 * end the scan and close the attribute relation
722 systable_endscan(rewrite_scan);
723 heap_close(rewrite_desc, AccessShareLock);
726 * there might not be any rules (if relhasrules is out-of-date)
730 relation->rd_rules = NULL;
731 relation->rd_rulescxt = NULL;
732 MemoryContextDelete(rulescxt);
737 * form a RuleLock and insert into relation
739 rulelock = (RuleLock *) MemoryContextAlloc(rulescxt, sizeof(RuleLock));
740 rulelock->numLocks = numlocks;
741 rulelock->rules = rules;
743 relation->rd_rules = rulelock;
749 * Determine whether two RuleLocks are equivalent
751 * Probably this should be in the rules code someplace...
754 equalRuleLocks(RuleLock *rlock1, RuleLock *rlock2)
759 * As of 7.3 we assume the rule ordering is repeatable, because
760 * RelationBuildRuleLock should read 'em in a consistent order. So just
761 * compare corresponding slots.
767 if (rlock1->numLocks != rlock2->numLocks)
769 for (i = 0; i < rlock1->numLocks; i++)
771 RewriteRule *rule1 = rlock1->rules[i];
772 RewriteRule *rule2 = rlock2->rules[i];
774 if (rule1->ruleId != rule2->ruleId)
776 if (rule1->event != rule2->event)
778 if (rule1->attrno != rule2->attrno)
780 if (rule1->isInstead != rule2->isInstead)
782 if (!equal(rule1->qual, rule2->qual))
784 if (!equal(rule1->actions, rule2->actions))
788 else if (rlock2 != NULL)
797 * Build a relation descriptor --- either a new one, or by
798 * recycling the given old relation object. The latter case
799 * supports rebuilding a relcache entry without invalidating
800 * pointers to it. The caller must hold at least
801 * AccessShareLock on the target relid.
803 * Returns NULL if no pg_class row could be found for the given relid
804 * (suggesting we are trying to access a just-deleted relation).
805 * Any other error is reported via elog.
808 RelationBuildDesc(Oid targetRelId, Relation oldrelation)
812 HeapTuple pg_class_tuple;
814 MemoryContext oldcxt;
817 * find the tuple in pg_class corresponding to the given relation id
819 pg_class_tuple = ScanPgRelation(targetRelId, true);
822 * if no such tuple exists, return NULL
824 if (!HeapTupleIsValid(pg_class_tuple))
828 * get information from the pg_class_tuple
830 relid = HeapTupleGetOid(pg_class_tuple);
831 relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
834 * allocate storage for the relation descriptor, and copy pg_class_tuple
835 * to relation->rd_rel.
837 relation = AllocateRelationDesc(oldrelation, relp);
840 * initialize the relation's relation id (relation->rd_id)
842 RelationGetRelid(relation) = relid;
845 * normal relations are not nailed into the cache; nor can a pre-existing
846 * relation be new. It could be temp though. (Actually, it could be new
847 * too, but it's okay to forget that fact if forced to flush the entry.)
849 relation->rd_refcnt = 0;
850 relation->rd_isnailed = false;
851 relation->rd_createSubid = InvalidSubTransactionId;
852 relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
853 relation->rd_istemp = isTempOrToastNamespace(relation->rd_rel->relnamespace);
856 * initialize the tuple descriptor (relation->rd_att).
858 RelationBuildTupleDesc(relation);
861 * Fetch rules and triggers that affect this relation
863 if (relation->rd_rel->relhasrules)
864 RelationBuildRuleLock(relation);
867 relation->rd_rules = NULL;
868 relation->rd_rulescxt = NULL;
871 if (relation->rd_rel->relhastriggers)
872 RelationBuildTriggers(relation);
874 relation->trigdesc = NULL;
877 * if it's an index, initialize index-related information
879 if (OidIsValid(relation->rd_rel->relam))
880 RelationInitIndexAccessInfo(relation);
882 /* extract reloptions if any */
883 RelationParseRelOptions(relation, pg_class_tuple);
886 * initialize the relation lock manager information
888 RelationInitLockInfo(relation); /* see lmgr.c */
891 * initialize physical addressing information for the relation
893 RelationInitPhysicalAddr(relation);
895 /* make sure relation is marked as having no open file yet */
896 relation->rd_smgr = NULL;
899 * now we can free the memory allocated for pg_class_tuple
901 heap_freetuple(pg_class_tuple);
904 * Insert newly created relation into relcache hash tables.
906 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
907 RelationCacheInsert(relation);
908 MemoryContextSwitchTo(oldcxt);
910 /* It's fully valid */
911 relation->rd_isvalid = true;
917 * Initialize the physical addressing info (RelFileNode) for a relcache entry
920 RelationInitPhysicalAddr(Relation relation)
922 if (relation->rd_rel->reltablespace)
923 relation->rd_node.spcNode = relation->rd_rel->reltablespace;
925 relation->rd_node.spcNode = MyDatabaseTableSpace;
926 if (relation->rd_rel->relisshared)
927 relation->rd_node.dbNode = InvalidOid;
929 relation->rd_node.dbNode = MyDatabaseId;
930 relation->rd_node.relNode = relation->rd_rel->relfilenode;
934 * Initialize index-access-method support data for an index relation
937 RelationInitIndexAccessInfo(Relation relation)
942 Datum indoptionDatum;
945 int2vector *indoption;
946 MemoryContext indexcxt;
947 MemoryContext oldcontext;
953 * Make a copy of the pg_index entry for the index. Since pg_index
954 * contains variable-length and possibly-null fields, we have to do this
955 * honestly rather than just treating it as a Form_pg_index struct.
957 tuple = SearchSysCache(INDEXRELID,
958 ObjectIdGetDatum(RelationGetRelid(relation)),
960 if (!HeapTupleIsValid(tuple))
961 elog(ERROR, "cache lookup failed for index %u",
962 RelationGetRelid(relation));
963 oldcontext = MemoryContextSwitchTo(CacheMemoryContext);
964 relation->rd_indextuple = heap_copytuple(tuple);
965 relation->rd_index = (Form_pg_index) GETSTRUCT(relation->rd_indextuple);
966 MemoryContextSwitchTo(oldcontext);
967 ReleaseSysCache(tuple);
970 * Make a copy of the pg_am entry for the index's access method
972 tuple = SearchSysCache(AMOID,
973 ObjectIdGetDatum(relation->rd_rel->relam),
975 if (!HeapTupleIsValid(tuple))
976 elog(ERROR, "cache lookup failed for access method %u",
977 relation->rd_rel->relam);
978 aform = (Form_pg_am) MemoryContextAlloc(CacheMemoryContext, sizeof *aform);
979 memcpy(aform, GETSTRUCT(tuple), sizeof *aform);
980 ReleaseSysCache(tuple);
981 relation->rd_am = aform;
983 natts = relation->rd_rel->relnatts;
984 if (natts != relation->rd_index->indnatts)
985 elog(ERROR, "relnatts disagrees with indnatts for index %u",
986 RelationGetRelid(relation));
987 amstrategies = aform->amstrategies;
988 amsupport = aform->amsupport;
991 * Make the private context to hold index access info. The reason we need
992 * a context, and not just a couple of pallocs, is so that we won't leak
993 * any subsidiary info attached to fmgr lookup records.
995 * Context parameters are set on the assumption that it'll probably not
998 indexcxt = AllocSetContextCreate(CacheMemoryContext,
999 RelationGetRelationName(relation),
1000 ALLOCSET_SMALL_MINSIZE,
1001 ALLOCSET_SMALL_INITSIZE,
1002 ALLOCSET_SMALL_MAXSIZE);
1003 relation->rd_indexcxt = indexcxt;
1006 * Allocate arrays to hold data
1008 relation->rd_aminfo = (RelationAmInfo *)
1009 MemoryContextAllocZero(indexcxt, sizeof(RelationAmInfo));
1011 relation->rd_opfamily = (Oid *)
1012 MemoryContextAllocZero(indexcxt, natts * sizeof(Oid));
1013 relation->rd_opcintype = (Oid *)
1014 MemoryContextAllocZero(indexcxt, natts * sizeof(Oid));
1016 if (amstrategies > 0)
1017 relation->rd_operator = (Oid *)
1018 MemoryContextAllocZero(indexcxt,
1019 natts * amstrategies * sizeof(Oid));
1021 relation->rd_operator = NULL;
1025 int nsupport = natts * amsupport;
1027 relation->rd_support = (RegProcedure *)
1028 MemoryContextAllocZero(indexcxt, nsupport * sizeof(RegProcedure));
1029 relation->rd_supportinfo = (FmgrInfo *)
1030 MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
1034 relation->rd_support = NULL;
1035 relation->rd_supportinfo = NULL;
1038 relation->rd_indoption = (int16 *)
1039 MemoryContextAllocZero(indexcxt, natts * sizeof(int16));
1042 * indclass cannot be referenced directly through the C struct, because it
1043 * comes after the variable-width indkey field. Must extract the datum
1046 indclassDatum = fastgetattr(relation->rd_indextuple,
1047 Anum_pg_index_indclass,
1048 GetPgIndexDescriptor(),
1051 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1054 * Fill the operator and support procedure OID arrays, as well as the info
1055 * about opfamilies and opclass input types. (aminfo and supportinfo are
1056 * left as zeroes, and are filled on-the-fly when used)
1058 IndexSupportInitialize(indclass,
1059 relation->rd_operator, relation->rd_support,
1060 relation->rd_opfamily, relation->rd_opcintype,
1061 amstrategies, amsupport, natts);
1064 * Similarly extract indoption and copy it to the cache entry
1066 indoptionDatum = fastgetattr(relation->rd_indextuple,
1067 Anum_pg_index_indoption,
1068 GetPgIndexDescriptor(),
1071 indoption = (int2vector *) DatumGetPointer(indoptionDatum);
1072 memcpy(relation->rd_indoption, indoption->values, natts * sizeof(int16));
1075 * expressions and predicate cache will be filled later
1077 relation->rd_indexprs = NIL;
1078 relation->rd_indpred = NIL;
1079 relation->rd_amcache = NULL;
1083 * IndexSupportInitialize
1084 * Initializes an index's cached opclass information,
1085 * given the index's pg_index.indclass entry.
1087 * Data is returned into *indexOperator, *indexSupport, *opFamily, and
1088 * *opcInType, which are arrays allocated by the caller.
1090 * The caller also passes maxStrategyNumber, maxSupportNumber, and
1091 * maxAttributeNumber, since these indicate the size of the arrays
1092 * it has allocated --- but in practice these numbers must always match
1093 * those obtainable from the system catalog entries for the index and
1097 IndexSupportInitialize(oidvector *indclass,
1099 RegProcedure *indexSupport,
1102 StrategyNumber maxStrategyNumber,
1103 StrategyNumber maxSupportNumber,
1104 AttrNumber maxAttributeNumber)
1108 for (attIndex = 0; attIndex < maxAttributeNumber; attIndex++)
1110 OpClassCacheEnt *opcentry;
1112 if (!OidIsValid(indclass->values[attIndex]))
1113 elog(ERROR, "bogus pg_index tuple");
1115 /* look up the info for this opclass, using a cache */
1116 opcentry = LookupOpclassInfo(indclass->values[attIndex],
1120 /* copy cached data into relcache entry */
1121 opFamily[attIndex] = opcentry->opcfamily;
1122 opcInType[attIndex] = opcentry->opcintype;
1123 if (maxStrategyNumber > 0)
1124 memcpy(&indexOperator[attIndex * maxStrategyNumber],
1125 opcentry->operatorOids,
1126 maxStrategyNumber * sizeof(Oid));
1127 if (maxSupportNumber > 0)
1128 memcpy(&indexSupport[attIndex * maxSupportNumber],
1129 opcentry->supportProcs,
1130 maxSupportNumber * sizeof(RegProcedure));
1137 * This routine maintains a per-opclass cache of the information needed
1138 * by IndexSupportInitialize(). This is more efficient than relying on
1139 * the catalog cache, because we can load all the info about a particular
1140 * opclass in a single indexscan of pg_amproc or pg_amop.
1142 * The information from pg_am about expected range of strategy and support
1143 * numbers is passed in, rather than being looked up, mainly because the
1144 * caller will have it already.
1146 * Note there is no provision for flushing the cache. This is OK at the
1147 * moment because there is no way to ALTER any interesting properties of an
1148 * existing opclass --- all you can do is drop it, which will result in
1149 * a useless but harmless dead entry in the cache. To support altering
1150 * opclass membership (not the same as opfamily membership!), we'd need to
1151 * be able to flush this cache as well as the contents of relcache entries
1154 static OpClassCacheEnt *
1155 LookupOpclassInfo(Oid operatorClassOid,
1156 StrategyNumber numStrats,
1157 StrategyNumber numSupport)
1159 OpClassCacheEnt *opcentry;
1163 ScanKeyData skey[3];
1167 if (OpClassCache == NULL)
1169 /* First time through: initialize the opclass cache */
1172 if (!CacheMemoryContext)
1173 CreateCacheMemoryContext();
1175 MemSet(&ctl, 0, sizeof(ctl));
1176 ctl.keysize = sizeof(Oid);
1177 ctl.entrysize = sizeof(OpClassCacheEnt);
1178 ctl.hash = oid_hash;
1179 OpClassCache = hash_create("Operator class cache", 64,
1180 &ctl, HASH_ELEM | HASH_FUNCTION);
1183 opcentry = (OpClassCacheEnt *) hash_search(OpClassCache,
1184 (void *) &operatorClassOid,
1185 HASH_ENTER, &found);
1189 /* Need to allocate memory for new entry */
1190 opcentry->valid = false; /* until known OK */
1191 opcentry->numStrats = numStrats;
1192 opcentry->numSupport = numSupport;
1195 opcentry->operatorOids = (Oid *)
1196 MemoryContextAllocZero(CacheMemoryContext,
1197 numStrats * sizeof(Oid));
1199 opcentry->operatorOids = NULL;
1202 opcentry->supportProcs = (RegProcedure *)
1203 MemoryContextAllocZero(CacheMemoryContext,
1204 numSupport * sizeof(RegProcedure));
1206 opcentry->supportProcs = NULL;
1210 Assert(numStrats == opcentry->numStrats);
1211 Assert(numSupport == opcentry->numSupport);
1215 * When testing for cache-flush hazards, we intentionally disable the
1216 * operator class cache and force reloading of the info on each call.
1217 * This is helpful because we want to test the case where a cache flush
1218 * occurs while we are loading the info, and it's very hard to provoke
1219 * that if this happens only once per opclass per backend.
1221 #if defined(CLOBBER_CACHE_ALWAYS)
1222 opcentry->valid = false;
1225 if (opcentry->valid)
1229 * Need to fill in new entry.
1231 * To avoid infinite recursion during startup, force heap scans if we're
1232 * looking up info for the opclasses used by the indexes we would like to
1235 indexOK = criticalRelcachesBuilt ||
1236 (operatorClassOid != OID_BTREE_OPS_OID &&
1237 operatorClassOid != INT2_BTREE_OPS_OID);
1240 * We have to fetch the pg_opclass row to determine its opfamily and
1241 * opcintype, which are needed to look up the operators and functions.
1242 * It'd be convenient to use the syscache here, but that probably doesn't
1243 * work while bootstrapping.
1245 ScanKeyInit(&skey[0],
1246 ObjectIdAttributeNumber,
1247 BTEqualStrategyNumber, F_OIDEQ,
1248 ObjectIdGetDatum(operatorClassOid));
1249 rel = heap_open(OperatorClassRelationId, AccessShareLock);
1250 scan = systable_beginscan(rel, OpclassOidIndexId, indexOK,
1251 SnapshotNow, 1, skey);
1253 if (HeapTupleIsValid(htup = systable_getnext(scan)))
1255 Form_pg_opclass opclassform = (Form_pg_opclass) GETSTRUCT(htup);
1257 opcentry->opcfamily = opclassform->opcfamily;
1258 opcentry->opcintype = opclassform->opcintype;
1261 elog(ERROR, "could not find tuple for opclass %u", operatorClassOid);
1263 systable_endscan(scan);
1264 heap_close(rel, AccessShareLock);
1268 * Scan pg_amop to obtain operators for the opclass. We only fetch the
1269 * default ones (those with lefttype = righttype = opcintype).
1273 ScanKeyInit(&skey[0],
1274 Anum_pg_amop_amopfamily,
1275 BTEqualStrategyNumber, F_OIDEQ,
1276 ObjectIdGetDatum(opcentry->opcfamily));
1277 ScanKeyInit(&skey[1],
1278 Anum_pg_amop_amoplefttype,
1279 BTEqualStrategyNumber, F_OIDEQ,
1280 ObjectIdGetDatum(opcentry->opcintype));
1281 ScanKeyInit(&skey[2],
1282 Anum_pg_amop_amoprighttype,
1283 BTEqualStrategyNumber, F_OIDEQ,
1284 ObjectIdGetDatum(opcentry->opcintype));
1285 rel = heap_open(AccessMethodOperatorRelationId, AccessShareLock);
1286 scan = systable_beginscan(rel, AccessMethodStrategyIndexId, indexOK,
1287 SnapshotNow, 3, skey);
1289 while (HeapTupleIsValid(htup = systable_getnext(scan)))
1291 Form_pg_amop amopform = (Form_pg_amop) GETSTRUCT(htup);
1293 if (amopform->amopstrategy <= 0 ||
1294 (StrategyNumber) amopform->amopstrategy > numStrats)
1295 elog(ERROR, "invalid amopstrategy number %d for opclass %u",
1296 amopform->amopstrategy, operatorClassOid);
1297 opcentry->operatorOids[amopform->amopstrategy - 1] =
1301 systable_endscan(scan);
1302 heap_close(rel, AccessShareLock);
1306 * Scan pg_amproc to obtain support procs for the opclass. We only fetch
1307 * the default ones (those with lefttype = righttype = opcintype).
1311 ScanKeyInit(&skey[0],
1312 Anum_pg_amproc_amprocfamily,
1313 BTEqualStrategyNumber, F_OIDEQ,
1314 ObjectIdGetDatum(opcentry->opcfamily));
1315 ScanKeyInit(&skey[1],
1316 Anum_pg_amproc_amproclefttype,
1317 BTEqualStrategyNumber, F_OIDEQ,
1318 ObjectIdGetDatum(opcentry->opcintype));
1319 ScanKeyInit(&skey[2],
1320 Anum_pg_amproc_amprocrighttype,
1321 BTEqualStrategyNumber, F_OIDEQ,
1322 ObjectIdGetDatum(opcentry->opcintype));
1323 rel = heap_open(AccessMethodProcedureRelationId, AccessShareLock);
1324 scan = systable_beginscan(rel, AccessMethodProcedureIndexId, indexOK,
1325 SnapshotNow, 3, skey);
1327 while (HeapTupleIsValid(htup = systable_getnext(scan)))
1329 Form_pg_amproc amprocform = (Form_pg_amproc) GETSTRUCT(htup);
1331 if (amprocform->amprocnum <= 0 ||
1332 (StrategyNumber) amprocform->amprocnum > numSupport)
1333 elog(ERROR, "invalid amproc number %d for opclass %u",
1334 amprocform->amprocnum, operatorClassOid);
1336 opcentry->supportProcs[amprocform->amprocnum - 1] =
1340 systable_endscan(scan);
1341 heap_close(rel, AccessShareLock);
1344 opcentry->valid = true;
1352 * This is a special cut-down version of RelationBuildDesc()
1353 * used by RelationCacheInitializePhase2() in initializing the relcache.
1354 * The relation descriptor is built just from the supplied parameters,
1355 * without actually looking at any system table entries. We cheat
1356 * quite a lot since we only need to work for a few basic system
1359 * formrdesc is currently used for: pg_class, pg_attribute, pg_proc,
1360 * and pg_type (see RelationCacheInitializePhase2).
1362 * Note that these catalogs can't have constraints (except attnotnull),
1363 * default values, rules, or triggers, since we don't cope with any of that.
1365 * NOTE: we assume we are already switched into CacheMemoryContext.
1368 formrdesc(const char *relationName, Oid relationReltype,
1369 bool hasoids, int natts, FormData_pg_attribute *att)
1376 * allocate new relation desc, clear all fields of reldesc
1378 relation = (Relation) palloc0(sizeof(RelationData));
1379 relation->rd_targblock = InvalidBlockNumber;
1380 relation->rd_fsm_nblocks = InvalidBlockNumber;
1381 relation->rd_vm_nblocks = InvalidBlockNumber;
1383 /* make sure relation is marked as having no open file yet */
1384 relation->rd_smgr = NULL;
1387 * initialize reference count: 1 because it is nailed in cache
1389 relation->rd_refcnt = 1;
1392 * all entries built with this routine are nailed-in-cache; none are for
1393 * new or temp relations.
1395 relation->rd_isnailed = true;
1396 relation->rd_createSubid = InvalidSubTransactionId;
1397 relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
1398 relation->rd_istemp = false;
1401 * initialize relation tuple form
1403 * The data we insert here is pretty incomplete/bogus, but it'll serve to
1404 * get us launched. RelationCacheInitializePhase2() will read the real
1405 * data from pg_class and replace what we've done here.
1407 relation->rd_rel = (Form_pg_class) palloc0(CLASS_TUPLE_SIZE);
1409 namestrcpy(&relation->rd_rel->relname, relationName);
1410 relation->rd_rel->relnamespace = PG_CATALOG_NAMESPACE;
1411 relation->rd_rel->reltype = relationReltype;
1414 * It's important to distinguish between shared and non-shared relations,
1415 * even at bootstrap time, to make sure we know where they are stored. At
1416 * present, all relations that formrdesc is used for are not shared.
1418 relation->rd_rel->relisshared = false;
1420 relation->rd_rel->relpages = 1;
1421 relation->rd_rel->reltuples = 1;
1422 relation->rd_rel->relkind = RELKIND_RELATION;
1423 relation->rd_rel->relhasoids = hasoids;
1424 relation->rd_rel->relnatts = (int16) natts;
1427 * initialize attribute tuple form
1429 * Unlike the case with the relation tuple, this data had better be right
1430 * because it will never be replaced. The input values must be correctly
1431 * defined by macros in src/include/catalog/ headers.
1433 relation->rd_att = CreateTemplateTupleDesc(natts, hasoids);
1434 relation->rd_att->tdrefcount = 1; /* mark as refcounted */
1436 relation->rd_att->tdtypeid = relationReltype;
1437 relation->rd_att->tdtypmod = -1; /* unnecessary, but... */
1440 * initialize tuple desc info
1442 has_not_null = false;
1443 for (i = 0; i < natts; i++)
1445 memcpy(relation->rd_att->attrs[i],
1447 ATTRIBUTE_TUPLE_SIZE);
1448 has_not_null |= att[i].attnotnull;
1449 /* make sure attcacheoff is valid */
1450 relation->rd_att->attrs[i]->attcacheoff = -1;
1453 /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
1454 relation->rd_att->attrs[0]->attcacheoff = 0;
1456 /* mark not-null status */
1459 TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
1461 constr->has_not_null = true;
1462 relation->rd_att->constr = constr;
1466 * initialize relation id from info in att array (my, this is ugly)
1468 RelationGetRelid(relation) = relation->rd_att->attrs[0]->attrelid;
1469 relation->rd_rel->relfilenode = RelationGetRelid(relation);
1472 * initialize the relation lock manager information
1474 RelationInitLockInfo(relation); /* see lmgr.c */
1477 * initialize physical addressing information for the relation
1479 RelationInitPhysicalAddr(relation);
1482 * initialize the rel-has-index flag, using hardwired knowledge
1484 if (IsBootstrapProcessingMode())
1486 /* In bootstrap mode, we have no indexes */
1487 relation->rd_rel->relhasindex = false;
1491 /* Otherwise, all the rels formrdesc is used for have indexes */
1492 relation->rd_rel->relhasindex = true;
1496 * add new reldesc to relcache
1498 RelationCacheInsert(relation);
1500 /* It's fully valid */
1501 relation->rd_isvalid = true;
1505 /* ----------------------------------------------------------------
1506 * Relation Descriptor Lookup Interface
1507 * ----------------------------------------------------------------
1511 * RelationIdGetRelation
1513 * Lookup a reldesc by OID; make one if not already in cache.
1515 * Returns NULL if no pg_class row could be found for the given relid
1516 * (suggesting we are trying to access a just-deleted relation).
1517 * Any other error is reported via elog.
1519 * NB: caller should already have at least AccessShareLock on the
1520 * relation ID, else there are nasty race conditions.
1522 * NB: relation ref count is incremented, or set to 1 if new entry.
1523 * Caller should eventually decrement count. (Usually,
1524 * that happens by calling RelationClose().)
1527 RelationIdGetRelation(Oid relationId)
1532 * first try to find reldesc in the cache
1534 RelationIdCacheLookup(relationId, rd);
1536 if (RelationIsValid(rd))
1538 RelationIncrementReferenceCount(rd);
1539 /* revalidate nailed index if necessary */
1540 if (!rd->rd_isvalid)
1541 RelationReloadIndexInfo(rd);
1546 * no reldesc in the cache, so have RelationBuildDesc() build one and add
1549 rd = RelationBuildDesc(relationId, NULL);
1550 if (RelationIsValid(rd))
1551 RelationIncrementReferenceCount(rd);
1555 /* ----------------------------------------------------------------
1556 * cache invalidation support routines
1557 * ----------------------------------------------------------------
1561 * RelationIncrementReferenceCount
1562 * Increments relation reference count.
1564 * Note: bootstrap mode has its own weird ideas about relation refcount
1565 * behavior; we ought to fix it someday, but for now, just disable
1566 * reference count ownership tracking in bootstrap mode.
1569 RelationIncrementReferenceCount(Relation rel)
1571 ResourceOwnerEnlargeRelationRefs(CurrentResourceOwner);
1572 rel->rd_refcnt += 1;
1573 if (!IsBootstrapProcessingMode())
1574 ResourceOwnerRememberRelationRef(CurrentResourceOwner, rel);
1578 * RelationDecrementReferenceCount
1579 * Decrements relation reference count.
1582 RelationDecrementReferenceCount(Relation rel)
1584 Assert(rel->rd_refcnt > 0);
1585 rel->rd_refcnt -= 1;
1586 if (!IsBootstrapProcessingMode())
1587 ResourceOwnerForgetRelationRef(CurrentResourceOwner, rel);
1591 * RelationClose - close an open relation
1593 * Actually, we just decrement the refcount.
1595 * NOTE: if compiled with -DRELCACHE_FORCE_RELEASE then relcache entries
1596 * will be freed as soon as their refcount goes to zero. In combination
1597 * with aset.c's CLOBBER_FREED_MEMORY option, this provides a good test
1598 * to catch references to already-released relcache entries. It slows
1599 * things down quite a bit, however.
1602 RelationClose(Relation relation)
1604 /* Note: no locking manipulations needed */
1605 RelationDecrementReferenceCount(relation);
1607 #ifdef RELCACHE_FORCE_RELEASE
1608 if (RelationHasReferenceCountZero(relation) &&
1609 relation->rd_createSubid == InvalidSubTransactionId &&
1610 relation->rd_newRelfilenodeSubid == InvalidSubTransactionId)
1611 RelationClearRelation(relation, false);
1616 * RelationReloadIndexInfo - reload minimal information for an open index
1618 * This function is used only for indexes. A relcache inval on an index
1619 * can mean that its pg_class or pg_index row changed. There are only
1620 * very limited changes that are allowed to an existing index's schema,
1621 * so we can update the relcache entry without a complete rebuild; which
1622 * is fortunate because we can't rebuild an index entry that is "nailed"
1623 * and/or in active use. We support full replacement of the pg_class row,
1624 * as well as updates of a few simple fields of the pg_index row.
1626 * We can't necessarily reread the catalog rows right away; we might be
1627 * in a failed transaction when we receive the SI notification. If so,
1628 * RelationClearRelation just marks the entry as invalid by setting
1629 * rd_isvalid to false. This routine is called to fix the entry when it
1632 * We assume that at the time we are called, we have at least AccessShareLock
1633 * on the target index. (Note: in the calls from RelationClearRelation,
1634 * this is legitimate because we know the rel has positive refcount.)
1637 RelationReloadIndexInfo(Relation relation)
1640 HeapTuple pg_class_tuple;
1643 /* Should be called only for invalidated indexes */
1644 Assert(relation->rd_rel->relkind == RELKIND_INDEX &&
1645 !relation->rd_isvalid);
1646 /* Should be closed at smgr level */
1647 Assert(relation->rd_smgr == NULL);
1650 * Read the pg_class row
1652 * Don't try to use an indexscan of pg_class_oid_index to reload the info
1653 * for pg_class_oid_index ...
1655 indexOK = (RelationGetRelid(relation) != ClassOidIndexId);
1656 pg_class_tuple = ScanPgRelation(RelationGetRelid(relation), indexOK);
1657 if (!HeapTupleIsValid(pg_class_tuple))
1658 elog(ERROR, "could not find pg_class tuple for index %u",
1659 RelationGetRelid(relation));
1660 relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
1661 memcpy(relation->rd_rel, relp, CLASS_TUPLE_SIZE);
1662 /* Reload reloptions in case they changed */
1663 if (relation->rd_options)
1664 pfree(relation->rd_options);
1665 RelationParseRelOptions(relation, pg_class_tuple);
1666 /* done with pg_class tuple */
1667 heap_freetuple(pg_class_tuple);
1668 /* We must recalculate physical address in case it changed */
1669 RelationInitPhysicalAddr(relation);
1671 * Must reset targblock, fsm_nblocks and vm_nblocks in case rel was
1674 relation->rd_targblock = InvalidBlockNumber;
1675 relation->rd_fsm_nblocks = InvalidBlockNumber;
1676 relation->rd_vm_nblocks = InvalidBlockNumber;
1677 /* Must free any AM cached data, too */
1678 if (relation->rd_amcache)
1679 pfree(relation->rd_amcache);
1680 relation->rd_amcache = NULL;
1683 * For a non-system index, there are fields of the pg_index row that are
1684 * allowed to change, so re-read that row and update the relcache entry.
1685 * Most of the info derived from pg_index (such as support function lookup
1686 * info) cannot change, and indeed the whole point of this routine is to
1687 * update the relcache entry without clobbering that data; so wholesale
1688 * replacement is not appropriate.
1690 if (!IsSystemRelation(relation))
1693 Form_pg_index index;
1695 tuple = SearchSysCache(INDEXRELID,
1696 ObjectIdGetDatum(RelationGetRelid(relation)),
1698 if (!HeapTupleIsValid(tuple))
1699 elog(ERROR, "cache lookup failed for index %u",
1700 RelationGetRelid(relation));
1701 index = (Form_pg_index) GETSTRUCT(tuple);
1703 relation->rd_index->indisvalid = index->indisvalid;
1704 relation->rd_index->indcheckxmin = index->indcheckxmin;
1705 relation->rd_index->indisready = index->indisready;
1706 HeapTupleHeaderSetXmin(relation->rd_indextuple->t_data,
1707 HeapTupleHeaderGetXmin(tuple->t_data));
1709 ReleaseSysCache(tuple);
1712 /* Okay, now it's valid again */
1713 relation->rd_isvalid = true;
1717 * RelationClearRelation
1719 * Physically blow away a relation cache entry, or reset it and rebuild
1720 * it from scratch (that is, from catalog entries). The latter path is
1721 * usually used when we are notified of a change to an open relation
1722 * (one with refcount > 0). However, this routine just does whichever
1723 * it's told to do; callers must determine which they want.
1725 * NB: when rebuilding, we'd better hold some lock on the relation.
1726 * In current usages this is presumed true because it has refcnt > 0.
1729 RelationClearRelation(Relation relation, bool rebuild)
1731 Oid old_reltype = relation->rd_rel->reltype;
1732 MemoryContext oldcxt;
1735 * Make sure smgr and lower levels close the relation's files, if they
1736 * weren't closed already. If the relation is not getting deleted, the
1737 * next smgr access should reopen the files automatically. This ensures
1738 * that the low-level file access state is updated after, say, a vacuum
1741 RelationCloseSmgr(relation);
1744 * Never, never ever blow away a nailed-in system relation, because we'd
1745 * be unable to recover. However, we must reset rd_targblock, in case we
1746 * got called because of a relation cache flush that was triggered by
1749 * If it's a nailed index, then we need to re-read the pg_class row to see
1750 * if its relfilenode changed. We can't necessarily do that here, because
1751 * we might be in a failed transaction. We assume it's okay to do it if
1752 * there are open references to the relcache entry (cf notes for
1753 * AtEOXact_RelationCache). Otherwise just mark the entry as possibly
1754 * invalid, and it'll be fixed when next opened.
1756 if (relation->rd_isnailed)
1758 relation->rd_targblock = InvalidBlockNumber;
1759 relation->rd_fsm_nblocks = InvalidBlockNumber;
1760 relation->rd_vm_nblocks = InvalidBlockNumber;
1761 if (relation->rd_rel->relkind == RELKIND_INDEX)
1763 relation->rd_isvalid = false; /* needs to be revalidated */
1764 if (relation->rd_refcnt > 1)
1765 RelationReloadIndexInfo(relation);
1771 * Even non-system indexes should not be blown away if they are open and
1772 * have valid index support information. This avoids problems with active
1773 * use of the index support information. As with nailed indexes, we
1774 * re-read the pg_class row to handle possible physical relocation of the
1775 * index, and we check for pg_index updates too.
1777 if (relation->rd_rel->relkind == RELKIND_INDEX &&
1778 relation->rd_refcnt > 0 &&
1779 relation->rd_indexcxt != NULL)
1781 relation->rd_isvalid = false; /* needs to be revalidated */
1782 RelationReloadIndexInfo(relation);
1787 * Remove relation from hash tables
1789 * Note: we might be reinserting it momentarily, but we must not have it
1790 * visible in the hash tables until it's valid again, so don't try to
1791 * optimize this away...
1793 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
1794 RelationCacheDelete(relation);
1795 MemoryContextSwitchTo(oldcxt);
1797 /* Clear out catcache's entries for this relation */
1798 CatalogCacheFlushRelation(RelationGetRelid(relation));
1801 * Free all the subsidiary data structures of the relcache entry. We
1802 * cannot free rd_att if we are trying to rebuild the entry, however,
1803 * because pointers to it may be cached in various places. The rule
1804 * manager might also have pointers into the rewrite rules. So to begin
1805 * with, we can only get rid of these fields:
1807 FreeTriggerDesc(relation->trigdesc);
1808 if (relation->rd_indextuple)
1809 pfree(relation->rd_indextuple);
1810 if (relation->rd_am)
1811 pfree(relation->rd_am);
1812 if (relation->rd_rel)
1813 pfree(relation->rd_rel);
1814 if (relation->rd_options)
1815 pfree(relation->rd_options);
1816 list_free(relation->rd_indexlist);
1817 bms_free(relation->rd_indexattr);
1818 if (relation->rd_indexcxt)
1819 MemoryContextDelete(relation->rd_indexcxt);
1822 * If we're really done with the relcache entry, blow it away. But if
1823 * someone is still using it, reconstruct the whole deal without moving
1824 * the physical RelationData record (so that the someone's pointer is
1829 /* ok to zap remaining substructure */
1830 flush_rowtype_cache(old_reltype);
1831 /* can't use DecrTupleDescRefCount here */
1832 Assert(relation->rd_att->tdrefcount > 0);
1833 if (--relation->rd_att->tdrefcount == 0)
1834 FreeTupleDesc(relation->rd_att);
1835 if (relation->rd_rulescxt)
1836 MemoryContextDelete(relation->rd_rulescxt);
1842 * When rebuilding an open relcache entry, must preserve ref count and
1843 * rd_createSubid/rd_newRelfilenodeSubid state. Also attempt to
1844 * preserve the tupledesc and rewrite-rule substructures in place.
1845 * (Note: the refcount mechanism for tupledescs may eventually ensure
1846 * that we don't really need to preserve the tupledesc in-place, but
1847 * for now there are still a lot of places that assume an open rel's
1848 * tupledesc won't move.)
1850 * Note that this process does not touch CurrentResourceOwner; which
1851 * is good because whatever ref counts the entry may have do not
1852 * necessarily belong to that resource owner.
1854 Oid save_relid = RelationGetRelid(relation);
1855 int old_refcnt = relation->rd_refcnt;
1856 SubTransactionId old_createSubid = relation->rd_createSubid;
1857 SubTransactionId old_newRelfilenodeSubid = relation->rd_newRelfilenodeSubid;
1858 struct PgStat_TableStatus *old_pgstat_info = relation->pgstat_info;
1859 TupleDesc old_att = relation->rd_att;
1860 RuleLock *old_rules = relation->rd_rules;
1861 MemoryContext old_rulescxt = relation->rd_rulescxt;
1863 if (RelationBuildDesc(save_relid, relation) != relation)
1865 /* Should only get here if relation was deleted */
1866 flush_rowtype_cache(old_reltype);
1867 Assert(old_att->tdrefcount > 0);
1868 if (--old_att->tdrefcount == 0)
1869 FreeTupleDesc(old_att);
1871 MemoryContextDelete(old_rulescxt);
1873 elog(ERROR, "relation %u deleted while still in use", save_relid);
1875 relation->rd_refcnt = old_refcnt;
1876 relation->rd_createSubid = old_createSubid;
1877 relation->rd_newRelfilenodeSubid = old_newRelfilenodeSubid;
1878 relation->pgstat_info = old_pgstat_info;
1880 if (equalTupleDescs(old_att, relation->rd_att))
1882 /* needn't flush typcache here */
1883 Assert(relation->rd_att->tdrefcount == 1);
1884 if (--relation->rd_att->tdrefcount == 0)
1885 FreeTupleDesc(relation->rd_att);
1886 relation->rd_att = old_att;
1890 flush_rowtype_cache(old_reltype);
1891 Assert(old_att->tdrefcount > 0);
1892 if (--old_att->tdrefcount == 0)
1893 FreeTupleDesc(old_att);
1895 if (equalRuleLocks(old_rules, relation->rd_rules))
1897 if (relation->rd_rulescxt)
1898 MemoryContextDelete(relation->rd_rulescxt);
1899 relation->rd_rules = old_rules;
1900 relation->rd_rulescxt = old_rulescxt;
1905 MemoryContextDelete(old_rulescxt);
1911 * RelationFlushRelation
1913 * Rebuild the relation if it is open (refcount > 0), else blow it away.
1916 RelationFlushRelation(Relation relation)
1920 if (relation->rd_createSubid != InvalidSubTransactionId ||
1921 relation->rd_newRelfilenodeSubid != InvalidSubTransactionId)
1924 * New relcache entries are always rebuilt, not flushed; else we'd
1925 * forget the "new" status of the relation, which is a useful
1926 * optimization to have. Ditto for the new-relfilenode status.
1933 * Pre-existing rels can be dropped from the relcache if not open.
1935 rebuild = !RelationHasReferenceCountZero(relation);
1938 RelationClearRelation(relation, rebuild);
1942 * RelationForgetRelation - unconditionally remove a relcache entry
1944 * External interface for destroying a relcache entry when we
1945 * drop the relation.
1948 RelationForgetRelation(Oid rid)
1952 RelationIdCacheLookup(rid, relation);
1954 if (!PointerIsValid(relation))
1955 return; /* not in cache, nothing to do */
1957 if (!RelationHasReferenceCountZero(relation))
1958 elog(ERROR, "relation %u is still open", rid);
1960 /* Unconditionally destroy the relcache entry */
1961 RelationClearRelation(relation, false);
1965 * RelationCacheInvalidateEntry
1967 * This routine is invoked for SI cache flush messages.
1969 * Any relcache entry matching the relid must be flushed. (Note: caller has
1970 * already determined that the relid belongs to our database or is a shared
1973 * We used to skip local relations, on the grounds that they could
1974 * not be targets of cross-backend SI update messages; but it seems
1975 * safer to process them, so that our *own* SI update messages will
1976 * have the same effects during CommandCounterIncrement for both
1977 * local and nonlocal relations.
1980 RelationCacheInvalidateEntry(Oid relationId)
1984 RelationIdCacheLookup(relationId, relation);
1986 if (PointerIsValid(relation))
1988 relcacheInvalsReceived++;
1989 RelationFlushRelation(relation);
1994 * RelationCacheInvalidate
1995 * Blow away cached relation descriptors that have zero reference counts,
1996 * and rebuild those with positive reference counts. Also reset the smgr
1999 * This is currently used only to recover from SI message buffer overflow,
2000 * so we do not touch new-in-transaction relations; they cannot be targets
2001 * of cross-backend SI updates (and our own updates now go through a
2002 * separate linked list that isn't limited by the SI message buffer size).
2003 * Likewise, we need not discard new-relfilenode-in-transaction hints,
2004 * since any invalidation of those would be a local event.
2006 * We do this in two phases: the first pass deletes deletable items, and
2007 * the second one rebuilds the rebuildable items. This is essential for
2008 * safety, because hash_seq_search only copes with concurrent deletion of
2009 * the element it is currently visiting. If a second SI overflow were to
2010 * occur while we are walking the table, resulting in recursive entry to
2011 * this routine, we could crash because the inner invocation blows away
2012 * the entry next to be visited by the outer scan. But this way is OK,
2013 * because (a) during the first pass we won't process any more SI messages,
2014 * so hash_seq_search will complete safely; (b) during the second pass we
2015 * only hold onto pointers to nondeletable entries.
2017 * The two-phase approach also makes it easy to ensure that we process
2018 * nailed-in-cache indexes before other nondeletable items, and that we
2019 * process pg_class_oid_index first of all. In scenarios where a nailed
2020 * index has been given a new relfilenode, we have to detect that update
2021 * before the nailed index is used in reloading any other relcache entry.
2024 RelationCacheInvalidate(void)
2026 HASH_SEQ_STATUS status;
2027 RelIdCacheEnt *idhentry;
2029 List *rebuildFirstList = NIL;
2030 List *rebuildList = NIL;
2034 hash_seq_init(&status, RelationIdCache);
2036 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
2038 relation = idhentry->reldesc;
2040 /* Must close all smgr references to avoid leaving dangling ptrs */
2041 RelationCloseSmgr(relation);
2043 /* Ignore new relations, since they are never SI targets */
2044 if (relation->rd_createSubid != InvalidSubTransactionId)
2047 relcacheInvalsReceived++;
2049 if (RelationHasReferenceCountZero(relation))
2051 /* Delete this entry immediately */
2052 Assert(!relation->rd_isnailed);
2053 RelationClearRelation(relation, false);
2058 * Add this entry to list of stuff to rebuild in second pass.
2059 * pg_class_oid_index goes on the front of rebuildFirstList, other
2060 * nailed indexes on the back, and everything else into
2061 * rebuildList (in no particular order).
2063 if (relation->rd_isnailed &&
2064 relation->rd_rel->relkind == RELKIND_INDEX)
2066 if (RelationGetRelid(relation) == ClassOidIndexId)
2067 rebuildFirstList = lcons(relation, rebuildFirstList);
2069 rebuildFirstList = lappend(rebuildFirstList, relation);
2072 rebuildList = lcons(relation, rebuildList);
2077 * Now zap any remaining smgr cache entries. This must happen before we
2078 * start to rebuild entries, since that may involve catalog fetches which
2079 * will re-open catalog files.
2083 /* Phase 2: rebuild the items found to need rebuild in phase 1 */
2084 foreach(l, rebuildFirstList)
2086 relation = (Relation) lfirst(l);
2087 RelationClearRelation(relation, true);
2089 list_free(rebuildFirstList);
2090 foreach(l, rebuildList)
2092 relation = (Relation) lfirst(l);
2093 RelationClearRelation(relation, true);
2095 list_free(rebuildList);
2099 * AtEOXact_RelationCache
2101 * Clean up the relcache at main-transaction commit or abort.
2103 * Note: this must be called *before* processing invalidation messages.
2104 * In the case of abort, we don't want to try to rebuild any invalidated
2105 * cache entries (since we can't safely do database accesses). Therefore
2106 * we must reset refcnts before handling pending invalidations.
2108 * As of PostgreSQL 8.1, relcache refcnts should get released by the
2109 * ResourceOwner mechanism. This routine just does a debugging
2110 * cross-check that no pins remain. However, we also need to do special
2111 * cleanup when the current transaction created any relations or made use
2112 * of forced index lists.
2115 AtEOXact_RelationCache(bool isCommit)
2117 HASH_SEQ_STATUS status;
2118 RelIdCacheEnt *idhentry;
2121 * To speed up transaction exit, we want to avoid scanning the relcache
2122 * unless there is actually something for this routine to do. Other than
2123 * the debug-only Assert checks, most transactions don't create any work
2124 * for us to do here, so we keep a static flag that gets set if there is
2125 * anything to do. (Currently, this means either a relation is created in
2126 * the current xact, or one is given a new relfilenode, or an index list
2127 * is forced.) For simplicity, the flag remains set till end of top-level
2128 * transaction, even though we could clear it at subtransaction end in
2131 if (!need_eoxact_work
2132 #ifdef USE_ASSERT_CHECKING
2138 hash_seq_init(&status, RelationIdCache);
2140 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
2142 Relation relation = idhentry->reldesc;
2145 * The relcache entry's ref count should be back to its normal
2146 * not-in-a-transaction state: 0 unless it's nailed in cache.
2148 * In bootstrap mode, this is NOT true, so don't check it --- the
2149 * bootstrap code expects relations to stay open across start/commit
2150 * transaction calls. (That seems bogus, but it's not worth fixing.)
2152 #ifdef USE_ASSERT_CHECKING
2153 if (!IsBootstrapProcessingMode())
2155 int expected_refcnt;
2157 expected_refcnt = relation->rd_isnailed ? 1 : 0;
2158 Assert(relation->rd_refcnt == expected_refcnt);
2163 * Is it a relation created in the current transaction?
2165 * During commit, reset the flag to zero, since we are now out of the
2166 * creating transaction. During abort, simply delete the relcache
2167 * entry --- it isn't interesting any longer. (NOTE: if we have
2168 * forgotten the new-ness of a new relation due to a forced cache
2169 * flush, the entry will get deleted anyway by shared-cache-inval
2170 * processing of the aborted pg_class insertion.)
2172 if (relation->rd_createSubid != InvalidSubTransactionId)
2175 relation->rd_createSubid = InvalidSubTransactionId;
2178 RelationClearRelation(relation, false);
2184 * Likewise, reset the hint about the relfilenode being new.
2186 relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
2189 * Flush any temporary index list.
2191 if (relation->rd_indexvalid == 2)
2193 list_free(relation->rd_indexlist);
2194 relation->rd_indexlist = NIL;
2195 relation->rd_oidindex = InvalidOid;
2196 relation->rd_indexvalid = 0;
2200 /* Once done with the transaction, we can reset need_eoxact_work */
2201 need_eoxact_work = false;
2205 * AtEOSubXact_RelationCache
2207 * Clean up the relcache at sub-transaction commit or abort.
2209 * Note: this must be called *before* processing invalidation messages.
2212 AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid,
2213 SubTransactionId parentSubid)
2215 HASH_SEQ_STATUS status;
2216 RelIdCacheEnt *idhentry;
2219 * Skip the relcache scan if nothing to do --- see notes for
2220 * AtEOXact_RelationCache.
2222 if (!need_eoxact_work)
2225 hash_seq_init(&status, RelationIdCache);
2227 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
2229 Relation relation = idhentry->reldesc;
2232 * Is it a relation created in the current subtransaction?
2234 * During subcommit, mark it as belonging to the parent, instead.
2235 * During subabort, simply delete the relcache entry.
2237 if (relation->rd_createSubid == mySubid)
2240 relation->rd_createSubid = parentSubid;
2243 Assert(RelationHasReferenceCountZero(relation));
2244 RelationClearRelation(relation, false);
2250 * Likewise, update or drop any new-relfilenode-in-subtransaction
2253 if (relation->rd_newRelfilenodeSubid == mySubid)
2256 relation->rd_newRelfilenodeSubid = parentSubid;
2258 relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
2262 * Flush any temporary index list.
2264 if (relation->rd_indexvalid == 2)
2266 list_free(relation->rd_indexlist);
2267 relation->rd_indexlist = NIL;
2268 relation->rd_oidindex = InvalidOid;
2269 relation->rd_indexvalid = 0;
2275 * RelationCacheMarkNewRelfilenode
2277 * Mark the rel as having been given a new relfilenode in the current
2278 * (sub) transaction. This is a hint that can be used to optimize
2279 * later operations on the rel in the same transaction.
2282 RelationCacheMarkNewRelfilenode(Relation rel)
2285 rel->rd_newRelfilenodeSubid = GetCurrentSubTransactionId();
2286 /* ... and now we have eoxact cleanup work to do */
2287 need_eoxact_work = true;
2292 * RelationBuildLocalRelation
2293 * Build a relcache entry for an about-to-be-created relation,
2294 * and enter it into the relcache.
2297 RelationBuildLocalRelation(const char *relname,
2302 bool shared_relation)
2305 MemoryContext oldcxt;
2306 int natts = tupDesc->natts;
2311 AssertArg(natts >= 0);
2314 * check for creation of a rel that must be nailed in cache.
2316 * XXX this list had better match RelationCacheInitializePhase2's list.
2320 case RelationRelationId:
2321 case AttributeRelationId:
2322 case ProcedureRelationId:
2323 case TypeRelationId:
2332 * check that hardwired list of shared rels matches what's in the
2333 * bootstrap .bki file. If you get a failure here during initdb, you
2334 * probably need to fix IsSharedRelation() to match whatever you've done
2335 * to the set of shared relations.
2337 if (shared_relation != IsSharedRelation(relid))
2338 elog(ERROR, "shared_relation flag for \"%s\" does not match IsSharedRelation(%u)",
2342 * switch to the cache context to create the relcache entry.
2344 if (!CacheMemoryContext)
2345 CreateCacheMemoryContext();
2347 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2350 * allocate a new relation descriptor and fill in basic state fields.
2352 rel = (Relation) palloc0(sizeof(RelationData));
2354 rel->rd_targblock = InvalidBlockNumber;
2355 rel->rd_fsm_nblocks = InvalidBlockNumber;
2356 rel->rd_vm_nblocks = InvalidBlockNumber;
2358 /* make sure relation is marked as having no open file yet */
2359 rel->rd_smgr = NULL;
2361 /* mark it nailed if appropriate */
2362 rel->rd_isnailed = nailit;
2364 rel->rd_refcnt = nailit ? 1 : 0;
2366 /* it's being created in this transaction */
2367 rel->rd_createSubid = GetCurrentSubTransactionId();
2368 rel->rd_newRelfilenodeSubid = InvalidSubTransactionId;
2370 /* must flag that we have rels created in this transaction */
2371 need_eoxact_work = true;
2373 /* is it a temporary relation? */
2374 rel->rd_istemp = isTempOrToastNamespace(relnamespace);
2377 * create a new tuple descriptor from the one passed in. We do this
2378 * partly to copy it into the cache context, and partly because the new
2379 * relation can't have any defaults or constraints yet; they have to be
2380 * added in later steps, because they require additions to multiple system
2381 * catalogs. We can copy attnotnull constraints here, however.
2383 rel->rd_att = CreateTupleDescCopy(tupDesc);
2384 rel->rd_att->tdrefcount = 1; /* mark as refcounted */
2385 has_not_null = false;
2386 for (i = 0; i < natts; i++)
2388 rel->rd_att->attrs[i]->attnotnull = tupDesc->attrs[i]->attnotnull;
2389 has_not_null |= tupDesc->attrs[i]->attnotnull;
2394 TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
2396 constr->has_not_null = true;
2397 rel->rd_att->constr = constr;
2401 * initialize relation tuple form (caller may add/override data later)
2403 rel->rd_rel = (Form_pg_class) palloc0(CLASS_TUPLE_SIZE);
2405 namestrcpy(&rel->rd_rel->relname, relname);
2406 rel->rd_rel->relnamespace = relnamespace;
2408 rel->rd_rel->relkind = RELKIND_UNCATALOGED;
2409 rel->rd_rel->relhasoids = rel->rd_att->tdhasoid;
2410 rel->rd_rel->relnatts = natts;
2411 rel->rd_rel->reltype = InvalidOid;
2412 /* needed when bootstrapping: */
2413 rel->rd_rel->relowner = BOOTSTRAP_SUPERUSERID;
2416 * Insert relation physical and logical identifiers (OIDs) into the right
2417 * places. Note that the physical ID (relfilenode) is initially the same
2418 * as the logical ID (OID).
2420 rel->rd_rel->relisshared = shared_relation;
2422 RelationGetRelid(rel) = relid;
2424 for (i = 0; i < natts; i++)
2425 rel->rd_att->attrs[i]->attrelid = relid;
2427 rel->rd_rel->relfilenode = relid;
2428 rel->rd_rel->reltablespace = reltablespace;
2430 RelationInitLockInfo(rel); /* see lmgr.c */
2432 RelationInitPhysicalAddr(rel);
2435 * Okay to insert into the relcache hash tables.
2437 RelationCacheInsert(rel);
2440 * done building relcache entry.
2442 MemoryContextSwitchTo(oldcxt);
2444 /* It's fully valid */
2445 rel->rd_isvalid = true;
2448 * Caller expects us to pin the returned entry.
2450 RelationIncrementReferenceCount(rel);
2456 * RelationCacheInitialize
2458 * This initializes the relation descriptor cache. At the time
2459 * that this is invoked, we can't do database access yet (mainly
2460 * because the transaction subsystem is not up); all we are doing
2461 * is making an empty cache hashtable. This must be done before
2462 * starting the initialization transaction, because otherwise
2463 * AtEOXact_RelationCache would crash if that transaction aborts
2464 * before we can get the relcache set up.
2467 #define INITRELCACHESIZE 400
2470 RelationCacheInitialize(void)
2472 MemoryContext oldcxt;
2476 * switch to cache memory context
2478 if (!CacheMemoryContext)
2479 CreateCacheMemoryContext();
2481 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2484 * create hashtable that indexes the relcache
2486 MemSet(&ctl, 0, sizeof(ctl));
2487 ctl.keysize = sizeof(Oid);
2488 ctl.entrysize = sizeof(RelIdCacheEnt);
2489 ctl.hash = oid_hash;
2490 RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
2491 &ctl, HASH_ELEM | HASH_FUNCTION);
2493 MemoryContextSwitchTo(oldcxt);
2497 * RelationCacheInitializePhase2
2499 * This is called as soon as the catcache and transaction system
2500 * are functional. At this point we can actually read data from
2501 * the system catalogs. We first try to read pre-computed relcache
2502 * entries from the pg_internal.init file. If that's missing or
2503 * broken, make phony entries for the minimum set of nailed-in-cache
2504 * relations. Then (unless bootstrapping) make sure we have entries
2505 * for the critical system indexes. Once we've done all this, we
2506 * have enough infrastructure to open any system catalog or use any
2507 * catcache. The last step is to rewrite pg_internal.init if needed.
2510 RelationCacheInitializePhase2(void)
2512 HASH_SEQ_STATUS status;
2513 RelIdCacheEnt *idhentry;
2514 MemoryContext oldcxt;
2515 bool needNewCacheFile = false;
2518 * switch to cache memory context
2520 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2523 * Try to load the relcache cache file. If unsuccessful, bootstrap the
2524 * cache with pre-made descriptors for the critical "nailed-in" system
2527 if (IsBootstrapProcessingMode() ||
2528 !load_relcache_init_file())
2530 needNewCacheFile = true;
2532 formrdesc("pg_class", PG_CLASS_RELTYPE_OID,
2533 true, Natts_pg_class, Desc_pg_class);
2534 formrdesc("pg_attribute", PG_ATTRIBUTE_RELTYPE_OID,
2535 false, Natts_pg_attribute, Desc_pg_attribute);
2536 formrdesc("pg_proc", PG_PROC_RELTYPE_OID,
2537 true, Natts_pg_proc, Desc_pg_proc);
2538 formrdesc("pg_type", PG_TYPE_RELTYPE_OID,
2539 true, Natts_pg_type, Desc_pg_type);
2541 #define NUM_CRITICAL_RELS 4 /* fix if you change list above */
2544 MemoryContextSwitchTo(oldcxt);
2546 /* In bootstrap mode, the faked-up formrdesc info is all we'll have */
2547 if (IsBootstrapProcessingMode())
2551 * If we didn't get the critical system indexes loaded into relcache, do
2552 * so now. These are critical because the catcache and/or opclass cache
2553 * depend on them for fetches done during relcache load. Thus, we have an
2554 * infinite-recursion problem. We can break the recursion by doing
2555 * heapscans instead of indexscans at certain key spots. To avoid hobbling
2556 * performance, we only want to do that until we have the critical indexes
2557 * loaded into relcache. Thus, the flag criticalRelcachesBuilt is used to
2558 * decide whether to do heapscan or indexscan at the key spots, and we set
2559 * it true after we've loaded the critical indexes.
2561 * The critical indexes are marked as "nailed in cache", partly to make it
2562 * easy for load_relcache_init_file to count them, but mainly because we
2563 * cannot flush and rebuild them once we've set criticalRelcachesBuilt to
2564 * true. (NOTE: perhaps it would be possible to reload them by
2565 * temporarily setting criticalRelcachesBuilt to false again. For now,
2566 * though, we just nail 'em in.)
2568 * RewriteRelRulenameIndexId and TriggerRelidNameIndexId are not critical
2569 * in the same way as the others, because the critical catalogs don't
2570 * (currently) have any rules or triggers, and so these indexes can be
2571 * rebuilt without inducing recursion. However they are used during
2572 * relcache load when a rel does have rules or triggers, so we choose to
2573 * nail them for performance reasons.
2575 if (!criticalRelcachesBuilt)
2579 #define LOAD_CRIT_INDEX(indexoid) \
2581 LockRelationOid(indexoid, AccessShareLock); \
2582 ird = RelationBuildDesc(indexoid, NULL); \
2584 elog(PANIC, "could not open critical system index %u", \
2586 ird->rd_isnailed = true; \
2587 ird->rd_refcnt = 1; \
2588 UnlockRelationOid(indexoid, AccessShareLock); \
2591 LOAD_CRIT_INDEX(ClassOidIndexId);
2592 LOAD_CRIT_INDEX(AttributeRelidNumIndexId);
2593 LOAD_CRIT_INDEX(IndexRelidIndexId);
2594 LOAD_CRIT_INDEX(OpclassOidIndexId);
2595 LOAD_CRIT_INDEX(AccessMethodStrategyIndexId);
2596 LOAD_CRIT_INDEX(AccessMethodProcedureIndexId);
2597 LOAD_CRIT_INDEX(OperatorOidIndexId);
2598 LOAD_CRIT_INDEX(RewriteRelRulenameIndexId);
2599 LOAD_CRIT_INDEX(TriggerRelidNameIndexId);
2601 #define NUM_CRITICAL_INDEXES 9 /* fix if you change list above */
2603 criticalRelcachesBuilt = true;
2607 * Now, scan all the relcache entries and update anything that might be
2608 * wrong in the results from formrdesc or the relcache cache file. If we
2609 * faked up relcache entries using formrdesc, then read the real pg_class
2610 * rows and replace the fake entries with them. Also, if any of the
2611 * relcache entries have rules or triggers, load that info the hard way
2612 * since it isn't recorded in the cache file.
2614 hash_seq_init(&status, RelationIdCache);
2616 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
2618 Relation relation = idhentry->reldesc;
2621 * If it's a faked-up entry, read the real pg_class tuple.
2623 if (needNewCacheFile && relation->rd_isnailed)
2628 htup = SearchSysCache(RELOID,
2629 ObjectIdGetDatum(RelationGetRelid(relation)),
2631 if (!HeapTupleIsValid(htup))
2632 elog(FATAL, "cache lookup failed for relation %u",
2633 RelationGetRelid(relation));
2634 relp = (Form_pg_class) GETSTRUCT(htup);
2637 * Copy tuple to relation->rd_rel. (See notes in
2638 * AllocateRelationDesc())
2640 Assert(relation->rd_rel != NULL);
2641 memcpy((char *) relation->rd_rel, (char *) relp, CLASS_TUPLE_SIZE);
2643 /* Update rd_options while we have the tuple */
2644 if (relation->rd_options)
2645 pfree(relation->rd_options);
2646 RelationParseRelOptions(relation, htup);
2649 * Also update the derived fields in rd_att.
2651 relation->rd_att->tdtypeid = relp->reltype;
2652 relation->rd_att->tdtypmod = -1; /* unnecessary, but... */
2653 relation->rd_att->tdhasoid = relp->relhasoids;
2655 ReleaseSysCache(htup);
2659 * Fix data that isn't saved in relcache cache file.
2661 if (relation->rd_rel->relhasrules && relation->rd_rules == NULL)
2662 RelationBuildRuleLock(relation);
2663 if (relation->rd_rel->relhastriggers && relation->trigdesc == NULL)
2664 RelationBuildTriggers(relation);
2668 * Lastly, write out a new relcache cache file if one is needed.
2670 if (needNewCacheFile)
2673 * Force all the catcaches to finish initializing and thereby open the
2674 * catalogs and indexes they use. This will preload the relcache with
2675 * entries for all the most important system catalogs and indexes, so
2676 * that the init file will be most useful for future backends.
2678 InitCatalogCachePhase2();
2680 /* now write the file */
2681 write_relcache_init_file();
2686 * GetPgClassDescriptor -- get a predefined tuple descriptor for pg_class
2687 * GetPgIndexDescriptor -- get a predefined tuple descriptor for pg_index
2689 * We need this kluge because we have to be able to access non-fixed-width
2690 * fields of pg_class and pg_index before we have the standard catalog caches
2691 * available. We use predefined data that's set up in just the same way as
2692 * the bootstrapped reldescs used by formrdesc(). The resulting tupdesc is
2693 * not 100% kosher: it does not have the correct rowtype OID in tdtypeid, nor
2694 * does it have a TupleConstr field. But it's good enough for the purpose of
2695 * extracting fields.
2698 BuildHardcodedDescriptor(int natts, Form_pg_attribute attrs, bool hasoids)
2701 MemoryContext oldcxt;
2704 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2706 result = CreateTemplateTupleDesc(natts, hasoids);
2707 result->tdtypeid = RECORDOID; /* not right, but we don't care */
2708 result->tdtypmod = -1;
2710 for (i = 0; i < natts; i++)
2712 memcpy(result->attrs[i], &attrs[i], ATTRIBUTE_TUPLE_SIZE);
2713 /* make sure attcacheoff is valid */
2714 result->attrs[i]->attcacheoff = -1;
2717 /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
2718 result->attrs[0]->attcacheoff = 0;
2720 /* Note: we don't bother to set up a TupleConstr entry */
2722 MemoryContextSwitchTo(oldcxt);
2728 GetPgClassDescriptor(void)
2730 static TupleDesc pgclassdesc = NULL;
2733 if (pgclassdesc == NULL)
2734 pgclassdesc = BuildHardcodedDescriptor(Natts_pg_class,
2742 GetPgIndexDescriptor(void)
2744 static TupleDesc pgindexdesc = NULL;
2747 if (pgindexdesc == NULL)
2748 pgindexdesc = BuildHardcodedDescriptor(Natts_pg_index,
2756 AttrDefaultFetch(Relation relation)
2758 AttrDefault *attrdef = relation->rd_att->constr->defval;
2759 int ndef = relation->rd_att->constr->num_defval;
2770 Anum_pg_attrdef_adrelid,
2771 BTEqualStrategyNumber, F_OIDEQ,
2772 ObjectIdGetDatum(RelationGetRelid(relation)));
2774 adrel = heap_open(AttrDefaultRelationId, AccessShareLock);
2775 adscan = systable_beginscan(adrel, AttrDefaultIndexId, true,
2776 SnapshotNow, 1, &skey);
2779 while (HeapTupleIsValid(htup = systable_getnext(adscan)))
2781 Form_pg_attrdef adform = (Form_pg_attrdef) GETSTRUCT(htup);
2783 for (i = 0; i < ndef; i++)
2785 if (adform->adnum != attrdef[i].adnum)
2787 if (attrdef[i].adbin != NULL)
2788 elog(WARNING, "multiple attrdef records found for attr %s of rel %s",
2789 NameStr(relation->rd_att->attrs[adform->adnum - 1]->attname),
2790 RelationGetRelationName(relation));
2794 val = fastgetattr(htup,
2795 Anum_pg_attrdef_adbin,
2796 adrel->rd_att, &isnull);
2798 elog(WARNING, "null adbin for attr %s of rel %s",
2799 NameStr(relation->rd_att->attrs[adform->adnum - 1]->attname),
2800 RelationGetRelationName(relation));
2802 attrdef[i].adbin = MemoryContextStrdup(CacheMemoryContext,
2803 TextDatumGetCString(val));
2808 elog(WARNING, "unexpected attrdef record found for attr %d of rel %s",
2809 adform->adnum, RelationGetRelationName(relation));
2812 systable_endscan(adscan);
2813 heap_close(adrel, AccessShareLock);
2816 elog(WARNING, "%d attrdef record(s) missing for rel %s",
2817 ndef - found, RelationGetRelationName(relation));
2821 CheckConstraintFetch(Relation relation)
2823 ConstrCheck *check = relation->rd_att->constr->check;
2824 int ncheck = relation->rd_att->constr->num_check;
2826 SysScanDesc conscan;
2827 ScanKeyData skey[1];
2833 ScanKeyInit(&skey[0],
2834 Anum_pg_constraint_conrelid,
2835 BTEqualStrategyNumber, F_OIDEQ,
2836 ObjectIdGetDatum(RelationGetRelid(relation)));
2838 conrel = heap_open(ConstraintRelationId, AccessShareLock);
2839 conscan = systable_beginscan(conrel, ConstraintRelidIndexId, true,
2840 SnapshotNow, 1, skey);
2842 while (HeapTupleIsValid(htup = systable_getnext(conscan)))
2844 Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(htup);
2846 /* We want check constraints only */
2847 if (conform->contype != CONSTRAINT_CHECK)
2850 if (found >= ncheck)
2851 elog(ERROR, "unexpected constraint record found for rel %s",
2852 RelationGetRelationName(relation));
2854 check[found].ccname = MemoryContextStrdup(CacheMemoryContext,
2855 NameStr(conform->conname));
2857 /* Grab and test conbin is actually set */
2858 val = fastgetattr(htup,
2859 Anum_pg_constraint_conbin,
2860 conrel->rd_att, &isnull);
2862 elog(ERROR, "null conbin for rel %s",
2863 RelationGetRelationName(relation));
2865 check[found].ccbin = MemoryContextStrdup(CacheMemoryContext,
2866 TextDatumGetCString(val));
2870 systable_endscan(conscan);
2871 heap_close(conrel, AccessShareLock);
2873 if (found != ncheck)
2874 elog(ERROR, "%d constraint record(s) missing for rel %s",
2875 ncheck - found, RelationGetRelationName(relation));
2879 * RelationGetIndexList -- get a list of OIDs of indexes on this relation
2881 * The index list is created only if someone requests it. We scan pg_index
2882 * to find relevant indexes, and add the list to the relcache entry so that
2883 * we won't have to compute it again. Note that shared cache inval of a
2884 * relcache entry will delete the old list and set rd_indexvalid to 0,
2885 * so that we must recompute the index list on next request. This handles
2886 * creation or deletion of an index.
2888 * The returned list is guaranteed to be sorted in order by OID. This is
2889 * needed by the executor, since for index types that we obtain exclusive
2890 * locks on when updating the index, all backends must lock the indexes in
2891 * the same order or we will get deadlocks (see ExecOpenIndices()). Any
2892 * consistent ordering would do, but ordering by OID is easy.
2894 * Since shared cache inval causes the relcache's copy of the list to go away,
2895 * we return a copy of the list palloc'd in the caller's context. The caller
2896 * may list_free() the returned list after scanning it. This is necessary
2897 * since the caller will typically be doing syscache lookups on the relevant
2898 * indexes, and syscache lookup could cause SI messages to be processed!
2900 * We also update rd_oidindex, which this module treats as effectively part
2901 * of the index list. rd_oidindex is valid when rd_indexvalid isn't zero;
2902 * it is the pg_class OID of a unique index on OID when the relation has one,
2903 * and InvalidOid if there is no such index.
2906 RelationGetIndexList(Relation relation)
2909 SysScanDesc indscan;
2914 MemoryContext oldcxt;
2916 /* Quick exit if we already computed the list. */
2917 if (relation->rd_indexvalid != 0)
2918 return list_copy(relation->rd_indexlist);
2921 * We build the list we intend to return (in the caller's context) while
2922 * doing the scan. After successfully completing the scan, we copy that
2923 * list into the relcache entry. This avoids cache-context memory leakage
2924 * if we get some sort of error partway through.
2927 oidIndex = InvalidOid;
2929 /* Prepare to scan pg_index for entries having indrelid = this rel. */
2931 Anum_pg_index_indrelid,
2932 BTEqualStrategyNumber, F_OIDEQ,
2933 ObjectIdGetDatum(RelationGetRelid(relation)));
2935 indrel = heap_open(IndexRelationId, AccessShareLock);
2936 indscan = systable_beginscan(indrel, IndexIndrelidIndexId, true,
2937 SnapshotNow, 1, &skey);
2939 while (HeapTupleIsValid(htup = systable_getnext(indscan)))
2941 Form_pg_index index = (Form_pg_index) GETSTRUCT(htup);
2943 /* Add index's OID to result list in the proper order */
2944 result = insert_ordered_oid(result, index->indexrelid);
2946 /* Check to see if it is a unique, non-partial btree index on OID */
2947 if (index->indnatts == 1 &&
2948 index->indisunique &&
2949 index->indkey.values[0] == ObjectIdAttributeNumber &&
2950 index->indclass.values[0] == OID_BTREE_OPS_OID &&
2951 heap_attisnull(htup, Anum_pg_index_indpred))
2952 oidIndex = index->indexrelid;
2955 systable_endscan(indscan);
2956 heap_close(indrel, AccessShareLock);
2958 /* Now save a copy of the completed list in the relcache entry. */
2959 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2960 relation->rd_indexlist = list_copy(result);
2961 relation->rd_oidindex = oidIndex;
2962 relation->rd_indexvalid = 1;
2963 MemoryContextSwitchTo(oldcxt);
2969 * insert_ordered_oid
2970 * Insert a new Oid into a sorted list of Oids, preserving ordering
2972 * Building the ordered list this way is O(N^2), but with a pretty small
2973 * constant, so for the number of entries we expect it will probably be
2974 * faster than trying to apply qsort(). Most tables don't have very many
2978 insert_ordered_oid(List *list, Oid datum)
2982 /* Does the datum belong at the front? */
2983 if (list == NIL || datum < linitial_oid(list))
2984 return lcons_oid(datum, list);
2985 /* No, so find the entry it belongs after */
2986 prev = list_head(list);
2989 ListCell *curr = lnext(prev);
2991 if (curr == NULL || datum < lfirst_oid(curr))
2992 break; /* it belongs after 'prev', before 'curr' */
2996 /* Insert datum into list after 'prev' */
2997 lappend_cell_oid(list, prev, datum);
3002 * RelationSetIndexList -- externally force the index list contents
3004 * This is used to temporarily override what we think the set of valid
3005 * indexes is (including the presence or absence of an OID index).
3006 * The forcing will be valid only until transaction commit or abort.
3008 * This should only be applied to nailed relations, because in a non-nailed
3009 * relation the hacked index list could be lost at any time due to SI
3010 * messages. In practice it is only used on pg_class (see REINDEX).
3012 * It is up to the caller to make sure the given list is correctly ordered.
3014 * We deliberately do not change rd_indexattr here: even when operating
3015 * with a temporary partial index list, HOT-update decisions must be made
3016 * correctly with respect to the full index set. It is up to the caller
3017 * to ensure that a correct rd_indexattr set has been cached before first
3018 * calling RelationSetIndexList; else a subsequent inquiry might cause a
3019 * wrong rd_indexattr set to get computed and cached.
3022 RelationSetIndexList(Relation relation, List *indexIds, Oid oidIndex)
3024 MemoryContext oldcxt;
3026 Assert(relation->rd_isnailed);
3027 /* Copy the list into the cache context (could fail for lack of mem) */
3028 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3029 indexIds = list_copy(indexIds);
3030 MemoryContextSwitchTo(oldcxt);
3031 /* Okay to replace old list */
3032 list_free(relation->rd_indexlist);
3033 relation->rd_indexlist = indexIds;
3034 relation->rd_oidindex = oidIndex;
3035 relation->rd_indexvalid = 2; /* mark list as forced */
3036 /* must flag that we have a forced index list */
3037 need_eoxact_work = true;
3041 * RelationGetOidIndex -- get the pg_class OID of the relation's OID index
3043 * Returns InvalidOid if there is no such index.
3046 RelationGetOidIndex(Relation relation)
3051 * If relation doesn't have OIDs at all, caller is probably confused. (We
3052 * could just silently return InvalidOid, but it seems better to throw an
3055 Assert(relation->rd_rel->relhasoids);
3057 if (relation->rd_indexvalid == 0)
3059 /* RelationGetIndexList does the heavy lifting. */
3060 ilist = RelationGetIndexList(relation);
3062 Assert(relation->rd_indexvalid != 0);
3065 return relation->rd_oidindex;
3069 * RelationGetIndexExpressions -- get the index expressions for an index
3071 * We cache the result of transforming pg_index.indexprs into a node tree.
3072 * If the rel is not an index or has no expressional columns, we return NIL.
3073 * Otherwise, the returned tree is copied into the caller's memory context.
3074 * (We don't want to return a pointer to the relcache copy, since it could
3075 * disappear due to relcache invalidation.)
3078 RelationGetIndexExpressions(Relation relation)
3084 MemoryContext oldcxt;
3086 /* Quick exit if we already computed the result. */
3087 if (relation->rd_indexprs)
3088 return (List *) copyObject(relation->rd_indexprs);
3090 /* Quick exit if there is nothing to do. */
3091 if (relation->rd_indextuple == NULL ||
3092 heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs))
3096 * We build the tree we intend to return in the caller's context. After
3097 * successfully completing the work, we copy it into the relcache entry.
3098 * This avoids problems if we get some sort of error partway through.
3100 exprsDatum = heap_getattr(relation->rd_indextuple,
3101 Anum_pg_index_indexprs,
3102 GetPgIndexDescriptor(),
3105 exprsString = TextDatumGetCString(exprsDatum);
3106 result = (List *) stringToNode(exprsString);
3110 * Run the expressions through eval_const_expressions. This is not just an
3111 * optimization, but is necessary, because the planner will be comparing
3112 * them to similarly-processed qual clauses, and may fail to detect valid
3113 * matches without this. We don't bother with canonicalize_qual, however.
3115 result = (List *) eval_const_expressions(NULL, (Node *) result);
3118 * Also mark any coercion format fields as "don't care", so that the
3119 * planner can match to both explicit and implicit coercions.
3121 set_coercionform_dontcare((Node *) result);
3123 /* May as well fix opfuncids too */
3124 fix_opfuncids((Node *) result);
3126 /* Now save a copy of the completed tree in the relcache entry. */
3127 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3128 relation->rd_indexprs = (List *) copyObject(result);
3129 MemoryContextSwitchTo(oldcxt);
3135 * RelationGetIndexPredicate -- get the index predicate for an index
3137 * We cache the result of transforming pg_index.indpred into an implicit-AND
3138 * node tree (suitable for ExecQual).
3139 * If the rel is not an index or has no predicate, we return NIL.
3140 * Otherwise, the returned tree is copied into the caller's memory context.
3141 * (We don't want to return a pointer to the relcache copy, since it could
3142 * disappear due to relcache invalidation.)
3145 RelationGetIndexPredicate(Relation relation)
3151 MemoryContext oldcxt;
3153 /* Quick exit if we already computed the result. */
3154 if (relation->rd_indpred)
3155 return (List *) copyObject(relation->rd_indpred);
3157 /* Quick exit if there is nothing to do. */
3158 if (relation->rd_indextuple == NULL ||
3159 heap_attisnull(relation->rd_indextuple, Anum_pg_index_indpred))
3163 * We build the tree we intend to return in the caller's context. After
3164 * successfully completing the work, we copy it into the relcache entry.
3165 * This avoids problems if we get some sort of error partway through.
3167 predDatum = heap_getattr(relation->rd_indextuple,
3168 Anum_pg_index_indpred,
3169 GetPgIndexDescriptor(),
3172 predString = TextDatumGetCString(predDatum);
3173 result = (List *) stringToNode(predString);
3177 * Run the expression through const-simplification and canonicalization.
3178 * This is not just an optimization, but is necessary, because the planner
3179 * will be comparing it to similarly-processed qual clauses, and may fail
3180 * to detect valid matches without this. This must match the processing
3181 * done to qual clauses in preprocess_expression()! (We can skip the
3182 * stuff involving subqueries, however, since we don't allow any in index
3185 result = (List *) eval_const_expressions(NULL, (Node *) result);
3187 result = (List *) canonicalize_qual((Expr *) result);
3190 * Also mark any coercion format fields as "don't care", so that the
3191 * planner can match to both explicit and implicit coercions.
3193 set_coercionform_dontcare((Node *) result);
3195 /* Also convert to implicit-AND format */
3196 result = make_ands_implicit((Expr *) result);
3198 /* May as well fix opfuncids too */
3199 fix_opfuncids((Node *) result);
3201 /* Now save a copy of the completed tree in the relcache entry. */
3202 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3203 relation->rd_indpred = (List *) copyObject(result);
3204 MemoryContextSwitchTo(oldcxt);
3210 * RelationGetIndexAttrBitmap -- get a bitmap of index attribute numbers
3212 * The result has a bit set for each attribute used anywhere in the index
3213 * definitions of all the indexes on this relation. (This includes not only
3214 * simple index keys, but attributes used in expressions and partial-index
3217 * Attribute numbers are offset by FirstLowInvalidHeapAttributeNumber so that
3218 * we can include system attributes (e.g., OID) in the bitmap representation.
3220 * The returned result is palloc'd in the caller's memory context and should
3221 * be bms_free'd when not needed anymore.
3224 RelationGetIndexAttrBitmap(Relation relation)
3226 Bitmapset *indexattrs;
3229 MemoryContext oldcxt;
3231 /* Quick exit if we already computed the result. */
3232 if (relation->rd_indexattr != NULL)
3233 return bms_copy(relation->rd_indexattr);
3235 /* Fast path if definitely no indexes */
3236 if (!RelationGetForm(relation)->relhasindex)
3240 * Get cached list of index OIDs
3242 indexoidlist = RelationGetIndexList(relation);
3244 /* Fall out if no indexes (but relhasindex was set) */
3245 if (indexoidlist == NIL)
3249 * For each index, add referenced attributes to indexattrs.
3252 foreach(l, indexoidlist)
3254 Oid indexOid = lfirst_oid(l);
3256 IndexInfo *indexInfo;
3259 indexDesc = index_open(indexOid, AccessShareLock);
3261 /* Extract index key information from the index's pg_index row */
3262 indexInfo = BuildIndexInfo(indexDesc);
3264 /* Collect simple attribute references */
3265 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
3267 int attrnum = indexInfo->ii_KeyAttrNumbers[i];
3270 indexattrs = bms_add_member(indexattrs,
3271 attrnum - FirstLowInvalidHeapAttributeNumber);
3274 /* Collect all attributes used in expressions, too */
3275 pull_varattnos((Node *) indexInfo->ii_Expressions, &indexattrs);
3277 /* Collect all attributes in the index predicate, too */
3278 pull_varattnos((Node *) indexInfo->ii_Predicate, &indexattrs);
3280 index_close(indexDesc, AccessShareLock);
3283 list_free(indexoidlist);
3285 /* Now save a copy of the bitmap in the relcache entry. */
3286 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3287 relation->rd_indexattr = bms_copy(indexattrs);
3288 MemoryContextSwitchTo(oldcxt);
3290 /* We return our original working copy for caller to play with */
3296 * load_relcache_init_file, write_relcache_init_file
3298 * In late 1992, we started regularly having databases with more than
3299 * a thousand classes in them. With this number of classes, it became
3300 * critical to do indexed lookups on the system catalogs.
3302 * Bootstrapping these lookups is very hard. We want to be able to
3303 * use an index on pg_attribute, for example, but in order to do so,
3304 * we must have read pg_attribute for the attributes in the index,
3305 * which implies that we need to use the index.
3307 * In order to get around the problem, we do the following:
3309 * + When the database system is initialized (at initdb time), we
3310 * don't use indexes. We do sequential scans.
3312 * + When the backend is started up in normal mode, we load an image
3313 * of the appropriate relation descriptors, in internal format,
3314 * from an initialization file in the data/base/... directory.
3316 * + If the initialization file isn't there, then we create the
3317 * relation descriptors using sequential scans and write 'em to
3318 * the initialization file for use by subsequent backends.
3320 * We could dispense with the initialization file and just build the
3321 * critical reldescs the hard way on every backend startup, but that
3322 * slows down backend startup noticeably.
3324 * We can in fact go further, and save more relcache entries than
3325 * just the ones that are absolutely critical; this allows us to speed
3326 * up backend startup by not having to build such entries the hard way.
3327 * Presently, all the catalog and index entries that are referred to
3328 * by catcaches are stored in the initialization file.
3330 * The same mechanism that detects when catcache and relcache entries
3331 * need to be invalidated (due to catalog updates) also arranges to
3332 * unlink the initialization file when its contents may be out of date.
3333 * The file will then be rebuilt during the next backend startup.
3337 * load_relcache_init_file -- attempt to load cache from the init file
3339 * If successful, return TRUE and set criticalRelcachesBuilt to true.
3340 * If not successful, return FALSE.
3342 * NOTE: we assume we are already switched into CacheMemoryContext.
3345 load_relcache_init_file(void)
3348 char initfilename[MAXPGPATH];
3358 snprintf(initfilename, sizeof(initfilename), "%s/%s",
3359 DatabasePath, RELCACHE_INIT_FILENAME);
3361 fp = AllocateFile(initfilename, PG_BINARY_R);
3366 * Read the index relcache entries from the file. Note we will not enter
3367 * any of them into the cache if the read fails partway through; this
3368 * helps to guard against broken init files.
3371 rels = (Relation *) palloc(max_rels * sizeof(Relation));
3373 nailed_rels = nailed_indexes = 0;
3374 initFileRelationIds = NIL;
3376 /* check for correct magic number (compatible version) */
3377 if (fread(&magic, 1, sizeof(magic), fp) != sizeof(magic))
3379 if (magic != RELCACHE_INIT_FILEMAGIC)
3382 for (relno = 0;; relno++)
3387 Form_pg_class relform;
3390 /* first read the relation descriptor length */
3391 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3394 break; /* end of file */
3398 /* safety check for incompatible relcache layout */
3399 if (len != sizeof(RelationData))
3402 /* allocate another relcache header */
3403 if (num_rels >= max_rels)
3406 rels = (Relation *) repalloc(rels, max_rels * sizeof(Relation));
3409 rel = rels[num_rels++] = (Relation) palloc(len);
3411 /* then, read the Relation structure */
3412 if ((nread = fread(rel, 1, len, fp)) != len)
3415 /* next read the relation tuple form */
3416 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3419 relform = (Form_pg_class) palloc(len);
3420 if ((nread = fread(relform, 1, len, fp)) != len)
3423 rel->rd_rel = relform;
3425 /* initialize attribute tuple forms */
3426 rel->rd_att = CreateTemplateTupleDesc(relform->relnatts,
3427 relform->relhasoids);
3428 rel->rd_att->tdrefcount = 1; /* mark as refcounted */
3430 rel->rd_att->tdtypeid = relform->reltype;
3431 rel->rd_att->tdtypmod = -1; /* unnecessary, but... */
3433 /* next read all the attribute tuple form data entries */
3434 has_not_null = false;
3435 for (i = 0; i < relform->relnatts; i++)
3437 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3439 if (len != ATTRIBUTE_TUPLE_SIZE)
3441 if ((nread = fread(rel->rd_att->attrs[i], 1, len, fp)) != len)
3444 has_not_null |= rel->rd_att->attrs[i]->attnotnull;
3447 /* next read the access method specific field */
3448 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3452 rel->rd_options = palloc(len);
3453 if ((nread = fread(rel->rd_options, 1, len, fp)) != len)
3455 if (len != VARSIZE(rel->rd_options))
3456 goto read_failed; /* sanity check */
3460 rel->rd_options = NULL;
3463 /* mark not-null status */
3466 TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
3468 constr->has_not_null = true;
3469 rel->rd_att->constr = constr;
3472 /* If it's an index, there's more to do */
3473 if (rel->rd_rel->relkind == RELKIND_INDEX)
3476 MemoryContext indexcxt;
3480 RegProcedure *support;
3484 /* Count nailed indexes to ensure we have 'em all */
3485 if (rel->rd_isnailed)
3488 /* next, read the pg_index tuple */
3489 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3492 rel->rd_indextuple = (HeapTuple) palloc(len);
3493 if ((nread = fread(rel->rd_indextuple, 1, len, fp)) != len)
3496 /* Fix up internal pointers in the tuple -- see heap_copytuple */
3497 rel->rd_indextuple->t_data = (HeapTupleHeader) ((char *) rel->rd_indextuple + HEAPTUPLESIZE);
3498 rel->rd_index = (Form_pg_index) GETSTRUCT(rel->rd_indextuple);
3500 /* next, read the access method tuple form */
3501 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3504 am = (Form_pg_am) palloc(len);
3505 if ((nread = fread(am, 1, len, fp)) != len)
3510 * prepare index info context --- parameters should match
3511 * RelationInitIndexAccessInfo
3513 indexcxt = AllocSetContextCreate(CacheMemoryContext,
3514 RelationGetRelationName(rel),
3515 ALLOCSET_SMALL_MINSIZE,
3516 ALLOCSET_SMALL_INITSIZE,
3517 ALLOCSET_SMALL_MAXSIZE);
3518 rel->rd_indexcxt = indexcxt;
3520 /* next, read the vector of opfamily OIDs */
3521 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3524 opfamily = (Oid *) MemoryContextAlloc(indexcxt, len);
3525 if ((nread = fread(opfamily, 1, len, fp)) != len)
3528 rel->rd_opfamily = opfamily;
3530 /* next, read the vector of opcintype OIDs */
3531 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3534 opcintype = (Oid *) MemoryContextAlloc(indexcxt, len);
3535 if ((nread = fread(opcintype, 1, len, fp)) != len)
3538 rel->rd_opcintype = opcintype;
3540 /* next, read the vector of operator OIDs */
3541 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3544 operator = (Oid *) MemoryContextAlloc(indexcxt, len);
3545 if ((nread = fread(operator, 1, len, fp)) != len)
3548 rel->rd_operator = operator;
3550 /* next, read the vector of support procedures */
3551 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3553 support = (RegProcedure *) MemoryContextAlloc(indexcxt, len);
3554 if ((nread = fread(support, 1, len, fp)) != len)
3557 rel->rd_support = support;
3559 /* finally, read the vector of indoption values */
3560 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3563 indoption = (int16 *) MemoryContextAlloc(indexcxt, len);
3564 if ((nread = fread(indoption, 1, len, fp)) != len)
3567 rel->rd_indoption = indoption;
3569 /* set up zeroed fmgr-info vectors */
3570 rel->rd_aminfo = (RelationAmInfo *)
3571 MemoryContextAllocZero(indexcxt, sizeof(RelationAmInfo));
3572 nsupport = relform->relnatts * am->amsupport;
3573 rel->rd_supportinfo = (FmgrInfo *)
3574 MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
3578 /* Count nailed rels to ensure we have 'em all */
3579 if (rel->rd_isnailed)
3582 Assert(rel->rd_index == NULL);
3583 Assert(rel->rd_indextuple == NULL);
3584 Assert(rel->rd_am == NULL);
3585 Assert(rel->rd_indexcxt == NULL);
3586 Assert(rel->rd_aminfo == NULL);
3587 Assert(rel->rd_opfamily == NULL);
3588 Assert(rel->rd_opcintype == NULL);
3589 Assert(rel->rd_operator == NULL);
3590 Assert(rel->rd_support == NULL);
3591 Assert(rel->rd_supportinfo == NULL);
3592 Assert(rel->rd_indoption == NULL);
3596 * Rules and triggers are not saved (mainly because the internal
3597 * format is complex and subject to change). They must be rebuilt if
3598 * needed by RelationCacheInitializePhase2. This is not expected to
3599 * be a big performance hit since few system catalogs have such. Ditto
3600 * for index expressions and predicates.
3602 rel->rd_rules = NULL;
3603 rel->rd_rulescxt = NULL;
3604 rel->trigdesc = NULL;
3605 rel->rd_indexprs = NIL;
3606 rel->rd_indpred = NIL;
3609 * Reset transient-state fields in the relcache entry
3611 rel->rd_smgr = NULL;
3612 rel->rd_targblock = InvalidBlockNumber;
3613 rel->rd_fsm_nblocks = InvalidBlockNumber;
3614 rel->rd_vm_nblocks = InvalidBlockNumber;
3615 if (rel->rd_isnailed)
3619 rel->rd_indexvalid = 0;
3620 rel->rd_indexlist = NIL;
3621 rel->rd_indexattr = NULL;
3622 rel->rd_oidindex = InvalidOid;
3623 rel->rd_createSubid = InvalidSubTransactionId;
3624 rel->rd_newRelfilenodeSubid = InvalidSubTransactionId;
3625 rel->rd_amcache = NULL;
3626 MemSet(&rel->pgstat_info, 0, sizeof(rel->pgstat_info));
3629 * Recompute lock and physical addressing info. This is needed in
3630 * case the pg_internal.init file was copied from some other database
3631 * by CREATE DATABASE.
3633 RelationInitLockInfo(rel);
3634 RelationInitPhysicalAddr(rel);
3638 * We reached the end of the init file without apparent problem. Did we
3639 * get the right number of nailed items? (This is a useful crosscheck in
3640 * case the set of critical rels or indexes changes.)
3642 if (nailed_rels != NUM_CRITICAL_RELS ||
3643 nailed_indexes != NUM_CRITICAL_INDEXES)
3647 * OK, all appears well.
3649 * Now insert all the new relcache entries into the cache.
3651 for (relno = 0; relno < num_rels; relno++)
3653 RelationCacheInsert(rels[relno]);
3654 /* also make a list of their OIDs, for RelationIdIsInInitFile */
3655 initFileRelationIds = lcons_oid(RelationGetRelid(rels[relno]),
3656 initFileRelationIds);
3662 criticalRelcachesBuilt = true;
3666 * init file is broken, so do it the hard way. We don't bother trying to
3667 * free the clutter we just allocated; it's not in the relcache so it
3678 * Write out a new initialization file with the current contents
3682 write_relcache_init_file(void)
3685 char tempfilename[MAXPGPATH];
3686 char finalfilename[MAXPGPATH];
3688 HASH_SEQ_STATUS status;
3689 RelIdCacheEnt *idhentry;
3690 MemoryContext oldcxt;
3694 * We must write a temporary file and rename it into place. Otherwise,
3695 * another backend starting at about the same time might crash trying to
3696 * read the partially-complete file.
3698 snprintf(tempfilename, sizeof(tempfilename), "%s/%s.%d",
3699 DatabasePath, RELCACHE_INIT_FILENAME, MyProcPid);
3700 snprintf(finalfilename, sizeof(finalfilename), "%s/%s",
3701 DatabasePath, RELCACHE_INIT_FILENAME);
3703 unlink(tempfilename); /* in case it exists w/wrong permissions */
3705 fp = AllocateFile(tempfilename, PG_BINARY_W);
3709 * We used to consider this a fatal error, but we might as well
3710 * continue with backend startup ...
3713 (errcode_for_file_access(),
3714 errmsg("could not create relation-cache initialization file \"%s\": %m",
3716 errdetail("Continuing anyway, but there's something wrong.")));
3721 * Write a magic number to serve as a file version identifier. We can
3722 * change the magic number whenever the relcache layout changes.
3724 magic = RELCACHE_INIT_FILEMAGIC;
3725 if (fwrite(&magic, 1, sizeof(magic), fp) != sizeof(magic))
3726 elog(FATAL, "could not write init file");
3729 * Write all the reldescs (in no particular order).
3731 hash_seq_init(&status, RelationIdCache);
3733 initFileRelationIds = NIL;
3735 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3737 Relation rel = idhentry->reldesc;
3738 Form_pg_class relform = rel->rd_rel;
3740 /* first write the relcache entry proper */
3741 write_item(rel, sizeof(RelationData), fp);
3743 /* next write the relation tuple form */
3744 write_item(relform, CLASS_TUPLE_SIZE, fp);
3746 /* next, do all the attribute tuple form data entries */
3747 for (i = 0; i < relform->relnatts; i++)
3749 write_item(rel->rd_att->attrs[i], ATTRIBUTE_TUPLE_SIZE, fp);
3752 /* next, do the access method specific field */
3753 write_item(rel->rd_options,
3754 (rel->rd_options ? VARSIZE(rel->rd_options) : 0),
3757 /* If it's an index, there's more to do */
3758 if (rel->rd_rel->relkind == RELKIND_INDEX)
3760 Form_pg_am am = rel->rd_am;
3762 /* write the pg_index tuple */
3763 /* we assume this was created by heap_copytuple! */
3764 write_item(rel->rd_indextuple,
3765 HEAPTUPLESIZE + rel->rd_indextuple->t_len,
3768 /* next, write the access method tuple form */
3769 write_item(am, sizeof(FormData_pg_am), fp);
3771 /* next, write the vector of opfamily OIDs */
3772 write_item(rel->rd_opfamily,
3773 relform->relnatts * sizeof(Oid),
3776 /* next, write the vector of opcintype OIDs */
3777 write_item(rel->rd_opcintype,
3778 relform->relnatts * sizeof(Oid),
3781 /* next, write the vector of operator OIDs */
3782 write_item(rel->rd_operator,
3783 relform->relnatts * (am->amstrategies * sizeof(Oid)),
3786 /* next, write the vector of support procedures */
3787 write_item(rel->rd_support,
3788 relform->relnatts * (am->amsupport * sizeof(RegProcedure)),
3791 /* finally, write the vector of indoption values */
3792 write_item(rel->rd_indoption,
3793 relform->relnatts * sizeof(int16),
3797 /* also make a list of their OIDs, for RelationIdIsInInitFile */
3798 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3799 initFileRelationIds = lcons_oid(RelationGetRelid(rel),
3800 initFileRelationIds);
3801 MemoryContextSwitchTo(oldcxt);
3805 elog(FATAL, "could not write init file");
3808 * Now we have to check whether the data we've so painstakingly
3809 * accumulated is already obsolete due to someone else's just-committed
3810 * catalog changes. If so, we just delete the temp file and leave it to
3811 * the next backend to try again. (Our own relcache entries will be
3812 * updated by SI message processing, but we can't be sure whether what we
3813 * wrote out was up-to-date.)
3815 * This mustn't run concurrently with RelationCacheInitFileInvalidate, so
3816 * grab a serialization lock for the duration.
3818 LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
3820 /* Make sure we have seen all incoming SI messages */
3821 AcceptInvalidationMessages();
3824 * If we have received any SI relcache invals since backend start, assume
3825 * we may have written out-of-date data.
3827 if (relcacheInvalsReceived == 0L)
3830 * OK, rename the temp file to its final name, deleting any
3831 * previously-existing init file.
3833 * Note: a failure here is possible under Cygwin, if some other
3834 * backend is holding open an unlinked-but-not-yet-gone init file. So
3835 * treat this as a noncritical failure; just remove the useless temp
3838 if (rename(tempfilename, finalfilename) < 0)
3839 unlink(tempfilename);
3843 /* Delete the already-obsolete temp file */
3844 unlink(tempfilename);
3847 LWLockRelease(RelCacheInitLock);
3850 /* write a chunk of data preceded by its length */
3852 write_item(const void *data, Size len, FILE *fp)
3854 if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len))
3855 elog(FATAL, "could not write init file");
3856 if (fwrite(data, 1, len, fp) != len)
3857 elog(FATAL, "could not write init file");
3861 * Detect whether a given relation (identified by OID) is one of the ones
3862 * we store in the init file.
3864 * Note that we effectively assume that all backends running in a database
3865 * would choose to store the same set of relations in the init file;
3866 * otherwise there are cases where we'd fail to detect the need for an init
3867 * file invalidation. This does not seem likely to be a problem in practice.
3870 RelationIdIsInInitFile(Oid relationId)
3872 return list_member_oid(initFileRelationIds, relationId);
3876 * Invalidate (remove) the init file during commit of a transaction that
3877 * changed one or more of the relation cache entries that are kept in the
3880 * We actually need to remove the init file twice: once just before sending
3881 * the SI messages that include relcache inval for such relations, and once
3882 * just after sending them. The unlink before ensures that a backend that's
3883 * currently starting cannot read the now-obsolete init file and then miss
3884 * the SI messages that will force it to update its relcache entries. (This
3885 * works because the backend startup sequence gets into the PGPROC array before
3886 * trying to load the init file.) The unlink after is to synchronize with a
3887 * backend that may currently be trying to write an init file based on data
3888 * that we've just rendered invalid. Such a backend will see the SI messages,
3889 * but we can't leave the init file sitting around to fool later backends.
3891 * Ignore any failure to unlink the file, since it might not be there if
3892 * no backend has been started since the last removal.
3895 RelationCacheInitFileInvalidate(bool beforeSend)
3897 char initfilename[MAXPGPATH];
3899 snprintf(initfilename, sizeof(initfilename), "%s/%s",
3900 DatabasePath, RELCACHE_INIT_FILENAME);
3904 /* no interlock needed here */
3905 unlink(initfilename);
3910 * We need to interlock this against write_relcache_init_file, to
3911 * guard against possibility that someone renames a new-but-
3912 * already-obsolete init file into place just after we unlink. With
3913 * the interlock, it's certain that write_relcache_init_file will
3914 * notice our SI inval message before renaming into place, or else
3915 * that we will execute second and successfully unlink the file.
3917 LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
3918 unlink(initfilename);
3919 LWLockRelease(RelCacheInitLock);
3924 * Remove the init file for a given database during postmaster startup.
3926 * We used to keep the init file across restarts, but that is unsafe in PITR
3927 * scenarios, and even in simple crash-recovery cases there are windows for
3928 * the init file to become out-of-sync with the database. So now we just
3929 * remove it during startup and expect the first backend launch to rebuild it.
3930 * Of course, this has to happen in each database of the cluster. For
3931 * simplicity this is driven by flatfiles.c, which has to scan pg_database
3935 RelationCacheInitFileRemove(const char *dbPath)
3937 char initfilename[MAXPGPATH];
3939 snprintf(initfilename, sizeof(initfilename), "%s/%s",
3940 dbPath, RELCACHE_INIT_FILENAME);
3941 unlink(initfilename);
3942 /* ignore any error, since it might not be there at all */