Fix oversight in previous error-reporting patch; mustn't pfree path string
[PostgreSQL.git] / src / backend / utils / cache / relcache.c
blobbc1c11a09f017d49dcf5fa3c50c73f71059ba8a2
1 /*-------------------------------------------------------------------------
3 * relcache.c
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
10 * IDENTIFICATION
11 * $PostgreSQL$
13 *-------------------------------------------------------------------------
16 * INTERFACE ROUTINES
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
22 * NOTES
23 * The following code contains many undocumented hacks. Please be
24 * careful....
26 #include "postgres.h"
28 #include <sys/file.h>
29 #include <fcntl.h>
30 #include <unistd.h>
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
96 Oid reloid;
97 Relation reldesc;
98 } 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
118 * init file.
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) \
132 do { \
133 RelIdCacheEnt *idhentry; bool found; \
134 idhentry = (RelIdCacheEnt*)hash_search(RelationIdCache, \
135 (void *) &(RELATION->rd_id), \
136 HASH_ENTER, \
137 &found); \
138 /* used to give notice if found -- now just keep quiet */ \
139 idhentry->reldesc = RELATION; \
140 } while(0)
142 #define RelationIdCacheLookup(ID, RELATION) \
143 do { \
144 RelIdCacheEnt *hentry; \
145 hentry = (RelIdCacheEnt*)hash_search(RelationIdCache, \
146 (void *) &(ID), HASH_FIND,NULL); \
147 if (hentry) \
148 RELATION = hentry->reldesc; \
149 else \
150 RELATION = NULL; \
151 } while(0)
153 #define RelationCacheDelete(RELATION) \
154 do { \
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"); \
161 } while(0)
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 */
180 } OpClassCacheEnt;
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,
210 Oid *indexOperator,
211 RegProcedure *indexSupport,
212 Oid *opFamily,
213 Oid *opcInType,
214 StrategyNumber maxStrategyNumber,
215 StrategyNumber maxSupportNumber,
216 AttrNumber maxAttributeNumber);
217 static OpClassCacheEnt *LookupOpclassInfo(Oid operatorClassOid,
218 StrategyNumber numStrats,
219 StrategyNumber numSupport);
223 * ScanPgRelation
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.
234 static HeapTuple
235 ScanPgRelation(Oid targetRelId, bool indexOK)
237 HeapTuple pg_class_tuple;
238 Relation pg_class_desc;
239 SysScanDesc pg_class_scan;
240 ScanKeyData key[1];
243 * form a scan key
245 ScanKeyInit(&key[0],
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,
259 SnapshotNow,
260 1, key);
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);
270 /* all done */
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).
287 static Relation
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_cache = InvalidBlockNumber;
309 /* make sure relation is marked as having no open file yet */
310 relation->rd_smgr = NULL;
313 * Copy the relation tuple form
315 * We only allocate space for the fixed fields, ie, CLASS_TUPLE_SIZE. The
316 * variable-length fields (relacl, reloptions) are NOT stored in the
317 * relcache --- there'd be little point in it, since we don't copy the
318 * tuple's nulls bitmap and hence wouldn't know if the values are valid.
319 * Bottom line is that relacl *cannot* be retrieved from the relcache. Get
320 * it from the syscache if you need it. The same goes for the original
321 * form of reloptions (however, we do store the parsed form of reloptions
322 * in rd_options).
324 relationForm = (Form_pg_class) palloc(CLASS_TUPLE_SIZE);
326 memcpy(relationForm, relp, CLASS_TUPLE_SIZE);
328 /* initialize relation tuple form */
329 relation->rd_rel = relationForm;
331 /* and allocate attribute tuple form storage */
332 relation->rd_att = CreateTemplateTupleDesc(relationForm->relnatts,
333 relationForm->relhasoids);
334 /* which we mark as a reference-counted tupdesc */
335 relation->rd_att->tdrefcount = 1;
337 MemoryContextSwitchTo(oldcxt);
339 return relation;
343 * RelationParseRelOptions
344 * Convert pg_class.reloptions into pre-parsed rd_options
346 * tuple is the real pg_class tuple (not rd_rel!) for relation
348 * Note: rd_rel and (if an index) rd_am must be valid already
350 static void
351 RelationParseRelOptions(Relation relation, HeapTuple tuple)
353 Datum datum;
354 bool isnull;
355 bytea *options;
357 relation->rd_options = NULL;
359 /* Fall out if relkind should not have options */
360 switch (relation->rd_rel->relkind)
362 case RELKIND_RELATION:
363 case RELKIND_TOASTVALUE:
364 case RELKIND_UNCATALOGED:
365 case RELKIND_INDEX:
366 break;
367 default:
368 return;
372 * Fetch reloptions from tuple; have to use a hardwired descriptor because
373 * we might not have any other for pg_class yet (consider executing this
374 * code for pg_class itself)
376 datum = fastgetattr(tuple,
377 Anum_pg_class_reloptions,
378 GetPgClassDescriptor(),
379 &isnull);
380 if (isnull)
381 return;
383 /* Parse into appropriate format; don't error out here */
384 switch (relation->rd_rel->relkind)
386 case RELKIND_RELATION:
387 case RELKIND_TOASTVALUE:
388 case RELKIND_UNCATALOGED:
389 options = heap_reloptions(relation->rd_rel->relkind, datum,
390 false);
391 break;
392 case RELKIND_INDEX:
393 options = index_reloptions(relation->rd_am->amoptions, datum,
394 false);
395 break;
396 default:
397 Assert(false); /* can't get here */
398 options = NULL; /* keep compiler quiet */
399 break;
402 /* Copy parsed data into CacheMemoryContext */
403 if (options)
405 relation->rd_options = MemoryContextAlloc(CacheMemoryContext,
406 VARSIZE(options));
407 memcpy(relation->rd_options, options, VARSIZE(options));
412 * RelationBuildTupleDesc
414 * Form the relation's tuple descriptor from information in
415 * the pg_attribute, pg_attrdef & pg_constraint system catalogs.
417 static void
418 RelationBuildTupleDesc(Relation relation)
420 HeapTuple pg_attribute_tuple;
421 Relation pg_attribute_desc;
422 SysScanDesc pg_attribute_scan;
423 ScanKeyData skey[2];
424 int need;
425 TupleConstr *constr;
426 AttrDefault *attrdef = NULL;
427 int ndef = 0;
429 /* copy some fields from pg_class row to rd_att */
430 relation->rd_att->tdtypeid = relation->rd_rel->reltype;
431 relation->rd_att->tdtypmod = -1; /* unnecessary, but... */
432 relation->rd_att->tdhasoid = relation->rd_rel->relhasoids;
434 constr = (TupleConstr *) MemoryContextAlloc(CacheMemoryContext,
435 sizeof(TupleConstr));
436 constr->has_not_null = false;
439 * Form a scan key that selects only user attributes (attnum > 0).
440 * (Eliminating system attribute rows at the index level is lots faster
441 * than fetching them.)
443 ScanKeyInit(&skey[0],
444 Anum_pg_attribute_attrelid,
445 BTEqualStrategyNumber, F_OIDEQ,
446 ObjectIdGetDatum(RelationGetRelid(relation)));
447 ScanKeyInit(&skey[1],
448 Anum_pg_attribute_attnum,
449 BTGreaterStrategyNumber, F_INT2GT,
450 Int16GetDatum(0));
453 * Open pg_attribute and begin a scan. Force heap scan if we haven't yet
454 * built the critical relcache entries (this includes initdb and startup
455 * without a pg_internal.init file).
457 pg_attribute_desc = heap_open(AttributeRelationId, AccessShareLock);
458 pg_attribute_scan = systable_beginscan(pg_attribute_desc,
459 AttributeRelidNumIndexId,
460 criticalRelcachesBuilt,
461 SnapshotNow,
462 2, skey);
465 * add attribute data to relation->rd_att
467 need = relation->rd_rel->relnatts;
469 while (HeapTupleIsValid(pg_attribute_tuple = systable_getnext(pg_attribute_scan)))
471 Form_pg_attribute attp;
473 attp = (Form_pg_attribute) GETSTRUCT(pg_attribute_tuple);
475 if (attp->attnum <= 0 ||
476 attp->attnum > relation->rd_rel->relnatts)
477 elog(ERROR, "invalid attribute number %d for %s",
478 attp->attnum, RelationGetRelationName(relation));
480 memcpy(relation->rd_att->attrs[attp->attnum - 1],
481 attp,
482 ATTRIBUTE_TUPLE_SIZE);
484 /* Update constraint/default info */
485 if (attp->attnotnull)
486 constr->has_not_null = true;
488 if (attp->atthasdef)
490 if (attrdef == NULL)
491 attrdef = (AttrDefault *)
492 MemoryContextAllocZero(CacheMemoryContext,
493 relation->rd_rel->relnatts *
494 sizeof(AttrDefault));
495 attrdef[ndef].adnum = attp->attnum;
496 attrdef[ndef].adbin = NULL;
497 ndef++;
499 need--;
500 if (need == 0)
501 break;
505 * end the scan and close the attribute relation
507 systable_endscan(pg_attribute_scan);
508 heap_close(pg_attribute_desc, AccessShareLock);
510 if (need != 0)
511 elog(ERROR, "catalog is missing %d attribute(s) for relid %u",
512 need, RelationGetRelid(relation));
515 * The attcacheoff values we read from pg_attribute should all be -1
516 * ("unknown"). Verify this if assert checking is on. They will be
517 * computed when and if needed during tuple access.
519 #ifdef USE_ASSERT_CHECKING
521 int i;
523 for (i = 0; i < relation->rd_rel->relnatts; i++)
524 Assert(relation->rd_att->attrs[i]->attcacheoff == -1);
526 #endif
529 * However, we can easily set the attcacheoff value for the first
530 * attribute: it must be zero. This eliminates the need for special cases
531 * for attnum=1 that used to exist in fastgetattr() and index_getattr().
533 if (relation->rd_rel->relnatts > 0)
534 relation->rd_att->attrs[0]->attcacheoff = 0;
537 * Set up constraint/default info
539 if (constr->has_not_null || ndef > 0 || relation->rd_rel->relchecks)
541 relation->rd_att->constr = constr;
543 if (ndef > 0) /* DEFAULTs */
545 if (ndef < relation->rd_rel->relnatts)
546 constr->defval = (AttrDefault *)
547 repalloc(attrdef, ndef * sizeof(AttrDefault));
548 else
549 constr->defval = attrdef;
550 constr->num_defval = ndef;
551 AttrDefaultFetch(relation);
553 else
554 constr->num_defval = 0;
556 if (relation->rd_rel->relchecks > 0) /* CHECKs */
558 constr->num_check = relation->rd_rel->relchecks;
559 constr->check = (ConstrCheck *)
560 MemoryContextAllocZero(CacheMemoryContext,
561 constr->num_check * sizeof(ConstrCheck));
562 CheckConstraintFetch(relation);
564 else
565 constr->num_check = 0;
567 else
569 pfree(constr);
570 relation->rd_att->constr = NULL;
575 * RelationBuildRuleLock
577 * Form the relation's rewrite rules from information in
578 * the pg_rewrite system catalog.
580 * Note: The rule parsetrees are potentially very complex node structures.
581 * To allow these trees to be freed when the relcache entry is flushed,
582 * we make a private memory context to hold the RuleLock information for
583 * each relcache entry that has associated rules. The context is used
584 * just for rule info, not for any other subsidiary data of the relcache
585 * entry, because that keeps the update logic in RelationClearRelation()
586 * manageable. The other subsidiary data structures are simple enough
587 * to be easy to free explicitly, anyway.
589 static void
590 RelationBuildRuleLock(Relation relation)
592 MemoryContext rulescxt;
593 MemoryContext oldcxt;
594 HeapTuple rewrite_tuple;
595 Relation rewrite_desc;
596 TupleDesc rewrite_tupdesc;
597 SysScanDesc rewrite_scan;
598 ScanKeyData key;
599 RuleLock *rulelock;
600 int numlocks;
601 RewriteRule **rules;
602 int maxlocks;
605 * Make the private context. Parameters are set on the assumption that
606 * it'll probably not contain much data.
608 rulescxt = AllocSetContextCreate(CacheMemoryContext,
609 RelationGetRelationName(relation),
610 ALLOCSET_SMALL_MINSIZE,
611 ALLOCSET_SMALL_INITSIZE,
612 ALLOCSET_SMALL_MAXSIZE);
613 relation->rd_rulescxt = rulescxt;
616 * allocate an array to hold the rewrite rules (the array is extended if
617 * necessary)
619 maxlocks = 4;
620 rules = (RewriteRule **)
621 MemoryContextAlloc(rulescxt, sizeof(RewriteRule *) * maxlocks);
622 numlocks = 0;
625 * form a scan key
627 ScanKeyInit(&key,
628 Anum_pg_rewrite_ev_class,
629 BTEqualStrategyNumber, F_OIDEQ,
630 ObjectIdGetDatum(RelationGetRelid(relation)));
633 * open pg_rewrite and begin a scan
635 * Note: since we scan the rules using RewriteRelRulenameIndexId, we will
636 * be reading the rules in name order, except possibly during
637 * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
638 * ensures that rules will be fired in name order.
640 rewrite_desc = heap_open(RewriteRelationId, AccessShareLock);
641 rewrite_tupdesc = RelationGetDescr(rewrite_desc);
642 rewrite_scan = systable_beginscan(rewrite_desc,
643 RewriteRelRulenameIndexId,
644 true, SnapshotNow,
645 1, &key);
647 while (HeapTupleIsValid(rewrite_tuple = systable_getnext(rewrite_scan)))
649 Form_pg_rewrite rewrite_form = (Form_pg_rewrite) GETSTRUCT(rewrite_tuple);
650 bool isnull;
651 Datum rule_datum;
652 char *rule_str;
653 RewriteRule *rule;
655 rule = (RewriteRule *) MemoryContextAlloc(rulescxt,
656 sizeof(RewriteRule));
658 rule->ruleId = HeapTupleGetOid(rewrite_tuple);
660 rule->event = rewrite_form->ev_type - '0';
661 rule->attrno = rewrite_form->ev_attr;
662 rule->enabled = rewrite_form->ev_enabled;
663 rule->isInstead = rewrite_form->is_instead;
666 * Must use heap_getattr to fetch ev_action and ev_qual. Also, the
667 * rule strings are often large enough to be toasted. To avoid
668 * leaking memory in the caller's context, do the detoasting here so
669 * we can free the detoasted version.
671 rule_datum = heap_getattr(rewrite_tuple,
672 Anum_pg_rewrite_ev_action,
673 rewrite_tupdesc,
674 &isnull);
675 Assert(!isnull);
676 rule_str = TextDatumGetCString(rule_datum);
677 oldcxt = MemoryContextSwitchTo(rulescxt);
678 rule->actions = (List *) stringToNode(rule_str);
679 MemoryContextSwitchTo(oldcxt);
680 pfree(rule_str);
682 rule_datum = heap_getattr(rewrite_tuple,
683 Anum_pg_rewrite_ev_qual,
684 rewrite_tupdesc,
685 &isnull);
686 Assert(!isnull);
687 rule_str = TextDatumGetCString(rule_datum);
688 oldcxt = MemoryContextSwitchTo(rulescxt);
689 rule->qual = (Node *) stringToNode(rule_str);
690 MemoryContextSwitchTo(oldcxt);
691 pfree(rule_str);
694 * We want the rule's table references to be checked as though by the
695 * table owner, not the user referencing the rule. Therefore, scan
696 * through the rule's actions and set the checkAsUser field on all
697 * rtable entries. We have to look at the qual as well, in case it
698 * contains sublinks.
700 * The reason for doing this when the rule is loaded, rather than when
701 * it is stored, is that otherwise ALTER TABLE OWNER would have to
702 * grovel through stored rules to update checkAsUser fields. Scanning
703 * the rule tree during load is relatively cheap (compared to
704 * constructing it in the first place), so we do it here.
706 setRuleCheckAsUser((Node *) rule->actions, relation->rd_rel->relowner);
707 setRuleCheckAsUser(rule->qual, relation->rd_rel->relowner);
709 if (numlocks >= maxlocks)
711 maxlocks *= 2;
712 rules = (RewriteRule **)
713 repalloc(rules, sizeof(RewriteRule *) * maxlocks);
715 rules[numlocks++] = rule;
719 * end the scan and close the attribute relation
721 systable_endscan(rewrite_scan);
722 heap_close(rewrite_desc, AccessShareLock);
725 * there might not be any rules (if relhasrules is out-of-date)
727 if (numlocks == 0)
729 relation->rd_rules = NULL;
730 relation->rd_rulescxt = NULL;
731 MemoryContextDelete(rulescxt);
732 return;
736 * form a RuleLock and insert into relation
738 rulelock = (RuleLock *) MemoryContextAlloc(rulescxt, sizeof(RuleLock));
739 rulelock->numLocks = numlocks;
740 rulelock->rules = rules;
742 relation->rd_rules = rulelock;
746 * equalRuleLocks
748 * Determine whether two RuleLocks are equivalent
750 * Probably this should be in the rules code someplace...
752 static bool
753 equalRuleLocks(RuleLock *rlock1, RuleLock *rlock2)
755 int i;
758 * As of 7.3 we assume the rule ordering is repeatable, because
759 * RelationBuildRuleLock should read 'em in a consistent order. So just
760 * compare corresponding slots.
762 if (rlock1 != NULL)
764 if (rlock2 == NULL)
765 return false;
766 if (rlock1->numLocks != rlock2->numLocks)
767 return false;
768 for (i = 0; i < rlock1->numLocks; i++)
770 RewriteRule *rule1 = rlock1->rules[i];
771 RewriteRule *rule2 = rlock2->rules[i];
773 if (rule1->ruleId != rule2->ruleId)
774 return false;
775 if (rule1->event != rule2->event)
776 return false;
777 if (rule1->attrno != rule2->attrno)
778 return false;
779 if (rule1->isInstead != rule2->isInstead)
780 return false;
781 if (!equal(rule1->qual, rule2->qual))
782 return false;
783 if (!equal(rule1->actions, rule2->actions))
784 return false;
787 else if (rlock2 != NULL)
788 return false;
789 return true;
794 * RelationBuildDesc
796 * Build a relation descriptor --- either a new one, or by
797 * recycling the given old relation object. The latter case
798 * supports rebuilding a relcache entry without invalidating
799 * pointers to it. The caller must hold at least
800 * AccessShareLock on the target relid.
802 * Returns NULL if no pg_class row could be found for the given relid
803 * (suggesting we are trying to access a just-deleted relation).
804 * Any other error is reported via elog.
806 static Relation
807 RelationBuildDesc(Oid targetRelId, Relation oldrelation)
809 Relation relation;
810 Oid relid;
811 HeapTuple pg_class_tuple;
812 Form_pg_class relp;
813 MemoryContext oldcxt;
816 * find the tuple in pg_class corresponding to the given relation id
818 pg_class_tuple = ScanPgRelation(targetRelId, true);
821 * if no such tuple exists, return NULL
823 if (!HeapTupleIsValid(pg_class_tuple))
824 return NULL;
827 * get information from the pg_class_tuple
829 relid = HeapTupleGetOid(pg_class_tuple);
830 relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
833 * allocate storage for the relation descriptor, and copy pg_class_tuple
834 * to relation->rd_rel.
836 relation = AllocateRelationDesc(oldrelation, relp);
839 * initialize the relation's relation id (relation->rd_id)
841 RelationGetRelid(relation) = relid;
844 * normal relations are not nailed into the cache; nor can a pre-existing
845 * relation be new. It could be temp though. (Actually, it could be new
846 * too, but it's okay to forget that fact if forced to flush the entry.)
848 relation->rd_refcnt = 0;
849 relation->rd_isnailed = false;
850 relation->rd_createSubid = InvalidSubTransactionId;
851 relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
852 relation->rd_istemp = isTempOrToastNamespace(relation->rd_rel->relnamespace);
855 * initialize the tuple descriptor (relation->rd_att).
857 RelationBuildTupleDesc(relation);
860 * Fetch rules and triggers that affect this relation
862 if (relation->rd_rel->relhasrules)
863 RelationBuildRuleLock(relation);
864 else
866 relation->rd_rules = NULL;
867 relation->rd_rulescxt = NULL;
870 if (relation->rd_rel->relhastriggers)
871 RelationBuildTriggers(relation);
872 else
873 relation->trigdesc = NULL;
876 * if it's an index, initialize index-related information
878 if (OidIsValid(relation->rd_rel->relam))
879 RelationInitIndexAccessInfo(relation);
881 /* extract reloptions if any */
882 RelationParseRelOptions(relation, pg_class_tuple);
885 * initialize the relation lock manager information
887 RelationInitLockInfo(relation); /* see lmgr.c */
890 * initialize physical addressing information for the relation
892 RelationInitPhysicalAddr(relation);
894 /* make sure relation is marked as having no open file yet */
895 relation->rd_smgr = NULL;
898 * now we can free the memory allocated for pg_class_tuple
900 heap_freetuple(pg_class_tuple);
903 * Insert newly created relation into relcache hash tables.
905 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
906 RelationCacheInsert(relation);
907 MemoryContextSwitchTo(oldcxt);
909 /* It's fully valid */
910 relation->rd_isvalid = true;
912 return relation;
916 * Initialize the physical addressing info (RelFileNode) for a relcache entry
918 static void
919 RelationInitPhysicalAddr(Relation relation)
921 if (relation->rd_rel->reltablespace)
922 relation->rd_node.spcNode = relation->rd_rel->reltablespace;
923 else
924 relation->rd_node.spcNode = MyDatabaseTableSpace;
925 if (relation->rd_rel->relisshared)
926 relation->rd_node.dbNode = InvalidOid;
927 else
928 relation->rd_node.dbNode = MyDatabaseId;
929 relation->rd_node.relNode = relation->rd_rel->relfilenode;
933 * Initialize index-access-method support data for an index relation
935 void
936 RelationInitIndexAccessInfo(Relation relation)
938 HeapTuple tuple;
939 Form_pg_am aform;
940 Datum indclassDatum;
941 Datum indoptionDatum;
942 bool isnull;
943 oidvector *indclass;
944 int2vector *indoption;
945 MemoryContext indexcxt;
946 MemoryContext oldcontext;
947 int natts;
948 uint16 amstrategies;
949 uint16 amsupport;
952 * Make a copy of the pg_index entry for the index. Since pg_index
953 * contains variable-length and possibly-null fields, we have to do this
954 * honestly rather than just treating it as a Form_pg_index struct.
956 tuple = SearchSysCache(INDEXRELID,
957 ObjectIdGetDatum(RelationGetRelid(relation)),
958 0, 0, 0);
959 if (!HeapTupleIsValid(tuple))
960 elog(ERROR, "cache lookup failed for index %u",
961 RelationGetRelid(relation));
962 oldcontext = MemoryContextSwitchTo(CacheMemoryContext);
963 relation->rd_indextuple = heap_copytuple(tuple);
964 relation->rd_index = (Form_pg_index) GETSTRUCT(relation->rd_indextuple);
965 MemoryContextSwitchTo(oldcontext);
966 ReleaseSysCache(tuple);
969 * Make a copy of the pg_am entry for the index's access method
971 tuple = SearchSysCache(AMOID,
972 ObjectIdGetDatum(relation->rd_rel->relam),
973 0, 0, 0);
974 if (!HeapTupleIsValid(tuple))
975 elog(ERROR, "cache lookup failed for access method %u",
976 relation->rd_rel->relam);
977 aform = (Form_pg_am) MemoryContextAlloc(CacheMemoryContext, sizeof *aform);
978 memcpy(aform, GETSTRUCT(tuple), sizeof *aform);
979 ReleaseSysCache(tuple);
980 relation->rd_am = aform;
982 natts = relation->rd_rel->relnatts;
983 if (natts != relation->rd_index->indnatts)
984 elog(ERROR, "relnatts disagrees with indnatts for index %u",
985 RelationGetRelid(relation));
986 amstrategies = aform->amstrategies;
987 amsupport = aform->amsupport;
990 * Make the private context to hold index access info. The reason we need
991 * a context, and not just a couple of pallocs, is so that we won't leak
992 * any subsidiary info attached to fmgr lookup records.
994 * Context parameters are set on the assumption that it'll probably not
995 * contain much data.
997 indexcxt = AllocSetContextCreate(CacheMemoryContext,
998 RelationGetRelationName(relation),
999 ALLOCSET_SMALL_MINSIZE,
1000 ALLOCSET_SMALL_INITSIZE,
1001 ALLOCSET_SMALL_MAXSIZE);
1002 relation->rd_indexcxt = indexcxt;
1005 * Allocate arrays to hold data
1007 relation->rd_aminfo = (RelationAmInfo *)
1008 MemoryContextAllocZero(indexcxt, sizeof(RelationAmInfo));
1010 relation->rd_opfamily = (Oid *)
1011 MemoryContextAllocZero(indexcxt, natts * sizeof(Oid));
1012 relation->rd_opcintype = (Oid *)
1013 MemoryContextAllocZero(indexcxt, natts * sizeof(Oid));
1015 if (amstrategies > 0)
1016 relation->rd_operator = (Oid *)
1017 MemoryContextAllocZero(indexcxt,
1018 natts * amstrategies * sizeof(Oid));
1019 else
1020 relation->rd_operator = NULL;
1022 if (amsupport > 0)
1024 int nsupport = natts * amsupport;
1026 relation->rd_support = (RegProcedure *)
1027 MemoryContextAllocZero(indexcxt, nsupport * sizeof(RegProcedure));
1028 relation->rd_supportinfo = (FmgrInfo *)
1029 MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
1031 else
1033 relation->rd_support = NULL;
1034 relation->rd_supportinfo = NULL;
1037 relation->rd_indoption = (int16 *)
1038 MemoryContextAllocZero(indexcxt, natts * sizeof(int16));
1041 * indclass cannot be referenced directly through the C struct, because it
1042 * comes after the variable-width indkey field. Must extract the datum
1043 * the hard way...
1045 indclassDatum = fastgetattr(relation->rd_indextuple,
1046 Anum_pg_index_indclass,
1047 GetPgIndexDescriptor(),
1048 &isnull);
1049 Assert(!isnull);
1050 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1053 * Fill the operator and support procedure OID arrays, as well as the info
1054 * about opfamilies and opclass input types. (aminfo and supportinfo are
1055 * left as zeroes, and are filled on-the-fly when used)
1057 IndexSupportInitialize(indclass,
1058 relation->rd_operator, relation->rd_support,
1059 relation->rd_opfamily, relation->rd_opcintype,
1060 amstrategies, amsupport, natts);
1063 * Similarly extract indoption and copy it to the cache entry
1065 indoptionDatum = fastgetattr(relation->rd_indextuple,
1066 Anum_pg_index_indoption,
1067 GetPgIndexDescriptor(),
1068 &isnull);
1069 Assert(!isnull);
1070 indoption = (int2vector *) DatumGetPointer(indoptionDatum);
1071 memcpy(relation->rd_indoption, indoption->values, natts * sizeof(int16));
1074 * expressions and predicate cache will be filled later
1076 relation->rd_indexprs = NIL;
1077 relation->rd_indpred = NIL;
1078 relation->rd_amcache = NULL;
1082 * IndexSupportInitialize
1083 * Initializes an index's cached opclass information,
1084 * given the index's pg_index.indclass entry.
1086 * Data is returned into *indexOperator, *indexSupport, *opFamily, and
1087 * *opcInType, which are arrays allocated by the caller.
1089 * The caller also passes maxStrategyNumber, maxSupportNumber, and
1090 * maxAttributeNumber, since these indicate the size of the arrays
1091 * it has allocated --- but in practice these numbers must always match
1092 * those obtainable from the system catalog entries for the index and
1093 * access method.
1095 static void
1096 IndexSupportInitialize(oidvector *indclass,
1097 Oid *indexOperator,
1098 RegProcedure *indexSupport,
1099 Oid *opFamily,
1100 Oid *opcInType,
1101 StrategyNumber maxStrategyNumber,
1102 StrategyNumber maxSupportNumber,
1103 AttrNumber maxAttributeNumber)
1105 int attIndex;
1107 for (attIndex = 0; attIndex < maxAttributeNumber; attIndex++)
1109 OpClassCacheEnt *opcentry;
1111 if (!OidIsValid(indclass->values[attIndex]))
1112 elog(ERROR, "bogus pg_index tuple");
1114 /* look up the info for this opclass, using a cache */
1115 opcentry = LookupOpclassInfo(indclass->values[attIndex],
1116 maxStrategyNumber,
1117 maxSupportNumber);
1119 /* copy cached data into relcache entry */
1120 opFamily[attIndex] = opcentry->opcfamily;
1121 opcInType[attIndex] = opcentry->opcintype;
1122 if (maxStrategyNumber > 0)
1123 memcpy(&indexOperator[attIndex * maxStrategyNumber],
1124 opcentry->operatorOids,
1125 maxStrategyNumber * sizeof(Oid));
1126 if (maxSupportNumber > 0)
1127 memcpy(&indexSupport[attIndex * maxSupportNumber],
1128 opcentry->supportProcs,
1129 maxSupportNumber * sizeof(RegProcedure));
1134 * LookupOpclassInfo
1136 * This routine maintains a per-opclass cache of the information needed
1137 * by IndexSupportInitialize(). This is more efficient than relying on
1138 * the catalog cache, because we can load all the info about a particular
1139 * opclass in a single indexscan of pg_amproc or pg_amop.
1141 * The information from pg_am about expected range of strategy and support
1142 * numbers is passed in, rather than being looked up, mainly because the
1143 * caller will have it already.
1145 * Note there is no provision for flushing the cache. This is OK at the
1146 * moment because there is no way to ALTER any interesting properties of an
1147 * existing opclass --- all you can do is drop it, which will result in
1148 * a useless but harmless dead entry in the cache. To support altering
1149 * opclass membership (not the same as opfamily membership!), we'd need to
1150 * be able to flush this cache as well as the contents of relcache entries
1151 * for indexes.
1153 static OpClassCacheEnt *
1154 LookupOpclassInfo(Oid operatorClassOid,
1155 StrategyNumber numStrats,
1156 StrategyNumber numSupport)
1158 OpClassCacheEnt *opcentry;
1159 bool found;
1160 Relation rel;
1161 SysScanDesc scan;
1162 ScanKeyData skey[3];
1163 HeapTuple htup;
1164 bool indexOK;
1166 if (OpClassCache == NULL)
1168 /* First time through: initialize the opclass cache */
1169 HASHCTL ctl;
1171 if (!CacheMemoryContext)
1172 CreateCacheMemoryContext();
1174 MemSet(&ctl, 0, sizeof(ctl));
1175 ctl.keysize = sizeof(Oid);
1176 ctl.entrysize = sizeof(OpClassCacheEnt);
1177 ctl.hash = oid_hash;
1178 OpClassCache = hash_create("Operator class cache", 64,
1179 &ctl, HASH_ELEM | HASH_FUNCTION);
1182 opcentry = (OpClassCacheEnt *) hash_search(OpClassCache,
1183 (void *) &operatorClassOid,
1184 HASH_ENTER, &found);
1186 if (!found)
1188 /* Need to allocate memory for new entry */
1189 opcentry->valid = false; /* until known OK */
1190 opcentry->numStrats = numStrats;
1191 opcentry->numSupport = numSupport;
1193 if (numStrats > 0)
1194 opcentry->operatorOids = (Oid *)
1195 MemoryContextAllocZero(CacheMemoryContext,
1196 numStrats * sizeof(Oid));
1197 else
1198 opcentry->operatorOids = NULL;
1200 if (numSupport > 0)
1201 opcentry->supportProcs = (RegProcedure *)
1202 MemoryContextAllocZero(CacheMemoryContext,
1203 numSupport * sizeof(RegProcedure));
1204 else
1205 opcentry->supportProcs = NULL;
1207 else
1209 Assert(numStrats == opcentry->numStrats);
1210 Assert(numSupport == opcentry->numSupport);
1214 * When testing for cache-flush hazards, we intentionally disable the
1215 * operator class cache and force reloading of the info on each call.
1216 * This is helpful because we want to test the case where a cache flush
1217 * occurs while we are loading the info, and it's very hard to provoke
1218 * that if this happens only once per opclass per backend.
1220 #if defined(CLOBBER_CACHE_ALWAYS)
1221 opcentry->valid = false;
1222 #endif
1224 if (opcentry->valid)
1225 return opcentry;
1228 * Need to fill in new entry.
1230 * To avoid infinite recursion during startup, force heap scans if we're
1231 * looking up info for the opclasses used by the indexes we would like to
1232 * reference here.
1234 indexOK = criticalRelcachesBuilt ||
1235 (operatorClassOid != OID_BTREE_OPS_OID &&
1236 operatorClassOid != INT2_BTREE_OPS_OID);
1239 * We have to fetch the pg_opclass row to determine its opfamily and
1240 * opcintype, which are needed to look up the operators and functions.
1241 * It'd be convenient to use the syscache here, but that probably doesn't
1242 * work while bootstrapping.
1244 ScanKeyInit(&skey[0],
1245 ObjectIdAttributeNumber,
1246 BTEqualStrategyNumber, F_OIDEQ,
1247 ObjectIdGetDatum(operatorClassOid));
1248 rel = heap_open(OperatorClassRelationId, AccessShareLock);
1249 scan = systable_beginscan(rel, OpclassOidIndexId, indexOK,
1250 SnapshotNow, 1, skey);
1252 if (HeapTupleIsValid(htup = systable_getnext(scan)))
1254 Form_pg_opclass opclassform = (Form_pg_opclass) GETSTRUCT(htup);
1256 opcentry->opcfamily = opclassform->opcfamily;
1257 opcentry->opcintype = opclassform->opcintype;
1259 else
1260 elog(ERROR, "could not find tuple for opclass %u", operatorClassOid);
1262 systable_endscan(scan);
1263 heap_close(rel, AccessShareLock);
1267 * Scan pg_amop to obtain operators for the opclass. We only fetch the
1268 * default ones (those with lefttype = righttype = opcintype).
1270 if (numStrats > 0)
1272 ScanKeyInit(&skey[0],
1273 Anum_pg_amop_amopfamily,
1274 BTEqualStrategyNumber, F_OIDEQ,
1275 ObjectIdGetDatum(opcentry->opcfamily));
1276 ScanKeyInit(&skey[1],
1277 Anum_pg_amop_amoplefttype,
1278 BTEqualStrategyNumber, F_OIDEQ,
1279 ObjectIdGetDatum(opcentry->opcintype));
1280 ScanKeyInit(&skey[2],
1281 Anum_pg_amop_amoprighttype,
1282 BTEqualStrategyNumber, F_OIDEQ,
1283 ObjectIdGetDatum(opcentry->opcintype));
1284 rel = heap_open(AccessMethodOperatorRelationId, AccessShareLock);
1285 scan = systable_beginscan(rel, AccessMethodStrategyIndexId, indexOK,
1286 SnapshotNow, 3, skey);
1288 while (HeapTupleIsValid(htup = systable_getnext(scan)))
1290 Form_pg_amop amopform = (Form_pg_amop) GETSTRUCT(htup);
1292 if (amopform->amopstrategy <= 0 ||
1293 (StrategyNumber) amopform->amopstrategy > numStrats)
1294 elog(ERROR, "invalid amopstrategy number %d for opclass %u",
1295 amopform->amopstrategy, operatorClassOid);
1296 opcentry->operatorOids[amopform->amopstrategy - 1] =
1297 amopform->amopopr;
1300 systable_endscan(scan);
1301 heap_close(rel, AccessShareLock);
1305 * Scan pg_amproc to obtain support procs for the opclass. We only fetch
1306 * the default ones (those with lefttype = righttype = opcintype).
1308 if (numSupport > 0)
1310 ScanKeyInit(&skey[0],
1311 Anum_pg_amproc_amprocfamily,
1312 BTEqualStrategyNumber, F_OIDEQ,
1313 ObjectIdGetDatum(opcentry->opcfamily));
1314 ScanKeyInit(&skey[1],
1315 Anum_pg_amproc_amproclefttype,
1316 BTEqualStrategyNumber, F_OIDEQ,
1317 ObjectIdGetDatum(opcentry->opcintype));
1318 ScanKeyInit(&skey[2],
1319 Anum_pg_amproc_amprocrighttype,
1320 BTEqualStrategyNumber, F_OIDEQ,
1321 ObjectIdGetDatum(opcentry->opcintype));
1322 rel = heap_open(AccessMethodProcedureRelationId, AccessShareLock);
1323 scan = systable_beginscan(rel, AccessMethodProcedureIndexId, indexOK,
1324 SnapshotNow, 3, skey);
1326 while (HeapTupleIsValid(htup = systable_getnext(scan)))
1328 Form_pg_amproc amprocform = (Form_pg_amproc) GETSTRUCT(htup);
1330 if (amprocform->amprocnum <= 0 ||
1331 (StrategyNumber) amprocform->amprocnum > numSupport)
1332 elog(ERROR, "invalid amproc number %d for opclass %u",
1333 amprocform->amprocnum, operatorClassOid);
1335 opcentry->supportProcs[amprocform->amprocnum - 1] =
1336 amprocform->amproc;
1339 systable_endscan(scan);
1340 heap_close(rel, AccessShareLock);
1343 opcentry->valid = true;
1344 return opcentry;
1349 * formrdesc
1351 * This is a special cut-down version of RelationBuildDesc()
1352 * used by RelationCacheInitializePhase2() in initializing the relcache.
1353 * The relation descriptor is built just from the supplied parameters,
1354 * without actually looking at any system table entries. We cheat
1355 * quite a lot since we only need to work for a few basic system
1356 * catalogs.
1358 * formrdesc is currently used for: pg_class, pg_attribute, pg_proc,
1359 * and pg_type (see RelationCacheInitializePhase2).
1361 * Note that these catalogs can't have constraints (except attnotnull),
1362 * default values, rules, or triggers, since we don't cope with any of that.
1364 * NOTE: we assume we are already switched into CacheMemoryContext.
1366 static void
1367 formrdesc(const char *relationName, Oid relationReltype,
1368 bool hasoids, int natts, FormData_pg_attribute *att)
1370 Relation relation;
1371 int i;
1372 bool has_not_null;
1375 * allocate new relation desc, clear all fields of reldesc
1377 relation = (Relation) palloc0(sizeof(RelationData));
1378 relation->rd_targblock = InvalidBlockNumber;
1379 relation->rd_fsm_nblocks_cache = InvalidBlockNumber;
1381 /* make sure relation is marked as having no open file yet */
1382 relation->rd_smgr = NULL;
1385 * initialize reference count: 1 because it is nailed in cache
1387 relation->rd_refcnt = 1;
1390 * all entries built with this routine are nailed-in-cache; none are for
1391 * new or temp relations.
1393 relation->rd_isnailed = true;
1394 relation->rd_createSubid = InvalidSubTransactionId;
1395 relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
1396 relation->rd_istemp = false;
1399 * initialize relation tuple form
1401 * The data we insert here is pretty incomplete/bogus, but it'll serve to
1402 * get us launched. RelationCacheInitializePhase2() will read the real
1403 * data from pg_class and replace what we've done here.
1405 relation->rd_rel = (Form_pg_class) palloc0(CLASS_TUPLE_SIZE);
1407 namestrcpy(&relation->rd_rel->relname, relationName);
1408 relation->rd_rel->relnamespace = PG_CATALOG_NAMESPACE;
1409 relation->rd_rel->reltype = relationReltype;
1412 * It's important to distinguish between shared and non-shared relations,
1413 * even at bootstrap time, to make sure we know where they are stored. At
1414 * present, all relations that formrdesc is used for are not shared.
1416 relation->rd_rel->relisshared = false;
1418 relation->rd_rel->relpages = 1;
1419 relation->rd_rel->reltuples = 1;
1420 relation->rd_rel->relkind = RELKIND_RELATION;
1421 relation->rd_rel->relhasoids = hasoids;
1422 relation->rd_rel->relnatts = (int16) natts;
1425 * initialize attribute tuple form
1427 * Unlike the case with the relation tuple, this data had better be right
1428 * because it will never be replaced. The input values must be correctly
1429 * defined by macros in src/include/catalog/ headers.
1431 relation->rd_att = CreateTemplateTupleDesc(natts, hasoids);
1432 relation->rd_att->tdrefcount = 1; /* mark as refcounted */
1434 relation->rd_att->tdtypeid = relationReltype;
1435 relation->rd_att->tdtypmod = -1; /* unnecessary, but... */
1438 * initialize tuple desc info
1440 has_not_null = false;
1441 for (i = 0; i < natts; i++)
1443 memcpy(relation->rd_att->attrs[i],
1444 &att[i],
1445 ATTRIBUTE_TUPLE_SIZE);
1446 has_not_null |= att[i].attnotnull;
1447 /* make sure attcacheoff is valid */
1448 relation->rd_att->attrs[i]->attcacheoff = -1;
1451 /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
1452 relation->rd_att->attrs[0]->attcacheoff = 0;
1454 /* mark not-null status */
1455 if (has_not_null)
1457 TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
1459 constr->has_not_null = true;
1460 relation->rd_att->constr = constr;
1464 * initialize relation id from info in att array (my, this is ugly)
1466 RelationGetRelid(relation) = relation->rd_att->attrs[0]->attrelid;
1467 relation->rd_rel->relfilenode = RelationGetRelid(relation);
1470 * initialize the relation lock manager information
1472 RelationInitLockInfo(relation); /* see lmgr.c */
1475 * initialize physical addressing information for the relation
1477 RelationInitPhysicalAddr(relation);
1480 * initialize the rel-has-index flag, using hardwired knowledge
1482 if (IsBootstrapProcessingMode())
1484 /* In bootstrap mode, we have no indexes */
1485 relation->rd_rel->relhasindex = false;
1487 else
1489 /* Otherwise, all the rels formrdesc is used for have indexes */
1490 relation->rd_rel->relhasindex = true;
1494 * add new reldesc to relcache
1496 RelationCacheInsert(relation);
1498 /* It's fully valid */
1499 relation->rd_isvalid = true;
1503 /* ----------------------------------------------------------------
1504 * Relation Descriptor Lookup Interface
1505 * ----------------------------------------------------------------
1509 * RelationIdGetRelation
1511 * Lookup a reldesc by OID; make one if not already in cache.
1513 * Returns NULL if no pg_class row could be found for the given relid
1514 * (suggesting we are trying to access a just-deleted relation).
1515 * Any other error is reported via elog.
1517 * NB: caller should already have at least AccessShareLock on the
1518 * relation ID, else there are nasty race conditions.
1520 * NB: relation ref count is incremented, or set to 1 if new entry.
1521 * Caller should eventually decrement count. (Usually,
1522 * that happens by calling RelationClose().)
1524 Relation
1525 RelationIdGetRelation(Oid relationId)
1527 Relation rd;
1530 * first try to find reldesc in the cache
1532 RelationIdCacheLookup(relationId, rd);
1534 if (RelationIsValid(rd))
1536 RelationIncrementReferenceCount(rd);
1537 /* revalidate nailed index if necessary */
1538 if (!rd->rd_isvalid)
1539 RelationReloadIndexInfo(rd);
1540 return rd;
1544 * no reldesc in the cache, so have RelationBuildDesc() build one and add
1545 * it.
1547 rd = RelationBuildDesc(relationId, NULL);
1548 if (RelationIsValid(rd))
1549 RelationIncrementReferenceCount(rd);
1550 return rd;
1553 /* ----------------------------------------------------------------
1554 * cache invalidation support routines
1555 * ----------------------------------------------------------------
1559 * RelationIncrementReferenceCount
1560 * Increments relation reference count.
1562 * Note: bootstrap mode has its own weird ideas about relation refcount
1563 * behavior; we ought to fix it someday, but for now, just disable
1564 * reference count ownership tracking in bootstrap mode.
1566 void
1567 RelationIncrementReferenceCount(Relation rel)
1569 ResourceOwnerEnlargeRelationRefs(CurrentResourceOwner);
1570 rel->rd_refcnt += 1;
1571 if (!IsBootstrapProcessingMode())
1572 ResourceOwnerRememberRelationRef(CurrentResourceOwner, rel);
1576 * RelationDecrementReferenceCount
1577 * Decrements relation reference count.
1579 void
1580 RelationDecrementReferenceCount(Relation rel)
1582 Assert(rel->rd_refcnt > 0);
1583 rel->rd_refcnt -= 1;
1584 if (!IsBootstrapProcessingMode())
1585 ResourceOwnerForgetRelationRef(CurrentResourceOwner, rel);
1589 * RelationClose - close an open relation
1591 * Actually, we just decrement the refcount.
1593 * NOTE: if compiled with -DRELCACHE_FORCE_RELEASE then relcache entries
1594 * will be freed as soon as their refcount goes to zero. In combination
1595 * with aset.c's CLOBBER_FREED_MEMORY option, this provides a good test
1596 * to catch references to already-released relcache entries. It slows
1597 * things down quite a bit, however.
1599 void
1600 RelationClose(Relation relation)
1602 /* Note: no locking manipulations needed */
1603 RelationDecrementReferenceCount(relation);
1605 #ifdef RELCACHE_FORCE_RELEASE
1606 if (RelationHasReferenceCountZero(relation) &&
1607 relation->rd_createSubid == InvalidSubTransactionId &&
1608 relation->rd_newRelfilenodeSubid == InvalidSubTransactionId)
1609 RelationClearRelation(relation, false);
1610 #endif
1614 * RelationReloadIndexInfo - reload minimal information for an open index
1616 * This function is used only for indexes. A relcache inval on an index
1617 * can mean that its pg_class or pg_index row changed. There are only
1618 * very limited changes that are allowed to an existing index's schema,
1619 * so we can update the relcache entry without a complete rebuild; which
1620 * is fortunate because we can't rebuild an index entry that is "nailed"
1621 * and/or in active use. We support full replacement of the pg_class row,
1622 * as well as updates of a few simple fields of the pg_index row.
1624 * We can't necessarily reread the catalog rows right away; we might be
1625 * in a failed transaction when we receive the SI notification. If so,
1626 * RelationClearRelation just marks the entry as invalid by setting
1627 * rd_isvalid to false. This routine is called to fix the entry when it
1628 * is next needed.
1630 * We assume that at the time we are called, we have at least AccessShareLock
1631 * on the target index. (Note: in the calls from RelationClearRelation,
1632 * this is legitimate because we know the rel has positive refcount.)
1634 static void
1635 RelationReloadIndexInfo(Relation relation)
1637 bool indexOK;
1638 HeapTuple pg_class_tuple;
1639 Form_pg_class relp;
1641 /* Should be called only for invalidated indexes */
1642 Assert(relation->rd_rel->relkind == RELKIND_INDEX &&
1643 !relation->rd_isvalid);
1644 /* Should be closed at smgr level */
1645 Assert(relation->rd_smgr == NULL);
1648 * Read the pg_class row
1650 * Don't try to use an indexscan of pg_class_oid_index to reload the info
1651 * for pg_class_oid_index ...
1653 indexOK = (RelationGetRelid(relation) != ClassOidIndexId);
1654 pg_class_tuple = ScanPgRelation(RelationGetRelid(relation), indexOK);
1655 if (!HeapTupleIsValid(pg_class_tuple))
1656 elog(ERROR, "could not find pg_class tuple for index %u",
1657 RelationGetRelid(relation));
1658 relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
1659 memcpy(relation->rd_rel, relp, CLASS_TUPLE_SIZE);
1660 /* Reload reloptions in case they changed */
1661 if (relation->rd_options)
1662 pfree(relation->rd_options);
1663 RelationParseRelOptions(relation, pg_class_tuple);
1664 /* done with pg_class tuple */
1665 heap_freetuple(pg_class_tuple);
1666 /* We must recalculate physical address in case it changed */
1667 RelationInitPhysicalAddr(relation);
1668 /* Must reset targblock and fsm_nblocks_cache in case rel was truncated */
1669 relation->rd_targblock = InvalidBlockNumber;
1670 relation->rd_fsm_nblocks_cache = InvalidBlockNumber;
1671 /* Must free any AM cached data, too */
1672 if (relation->rd_amcache)
1673 pfree(relation->rd_amcache);
1674 relation->rd_amcache = NULL;
1677 * For a non-system index, there are fields of the pg_index row that are
1678 * allowed to change, so re-read that row and update the relcache entry.
1679 * Most of the info derived from pg_index (such as support function lookup
1680 * info) cannot change, and indeed the whole point of this routine is to
1681 * update the relcache entry without clobbering that data; so wholesale
1682 * replacement is not appropriate.
1684 if (!IsSystemRelation(relation))
1686 HeapTuple tuple;
1687 Form_pg_index index;
1689 tuple = SearchSysCache(INDEXRELID,
1690 ObjectIdGetDatum(RelationGetRelid(relation)),
1691 0, 0, 0);
1692 if (!HeapTupleIsValid(tuple))
1693 elog(ERROR, "cache lookup failed for index %u",
1694 RelationGetRelid(relation));
1695 index = (Form_pg_index) GETSTRUCT(tuple);
1697 relation->rd_index->indisvalid = index->indisvalid;
1698 relation->rd_index->indcheckxmin = index->indcheckxmin;
1699 relation->rd_index->indisready = index->indisready;
1700 HeapTupleHeaderSetXmin(relation->rd_indextuple->t_data,
1701 HeapTupleHeaderGetXmin(tuple->t_data));
1703 ReleaseSysCache(tuple);
1706 /* Okay, now it's valid again */
1707 relation->rd_isvalid = true;
1711 * RelationClearRelation
1713 * Physically blow away a relation cache entry, or reset it and rebuild
1714 * it from scratch (that is, from catalog entries). The latter path is
1715 * usually used when we are notified of a change to an open relation
1716 * (one with refcount > 0). However, this routine just does whichever
1717 * it's told to do; callers must determine which they want.
1719 * NB: when rebuilding, we'd better hold some lock on the relation.
1720 * In current usages this is presumed true because it has refcnt > 0.
1722 static void
1723 RelationClearRelation(Relation relation, bool rebuild)
1725 Oid old_reltype = relation->rd_rel->reltype;
1726 MemoryContext oldcxt;
1729 * Make sure smgr and lower levels close the relation's files, if they
1730 * weren't closed already. If the relation is not getting deleted, the
1731 * next smgr access should reopen the files automatically. This ensures
1732 * that the low-level file access state is updated after, say, a vacuum
1733 * truncation.
1735 RelationCloseSmgr(relation);
1738 * Never, never ever blow away a nailed-in system relation, because we'd
1739 * be unable to recover. However, we must reset rd_targblock, in case we
1740 * got called because of a relation cache flush that was triggered by
1741 * VACUUM.
1743 * If it's a nailed index, then we need to re-read the pg_class row to see
1744 * if its relfilenode changed. We can't necessarily do that here, because
1745 * we might be in a failed transaction. We assume it's okay to do it if
1746 * there are open references to the relcache entry (cf notes for
1747 * AtEOXact_RelationCache). Otherwise just mark the entry as possibly
1748 * invalid, and it'll be fixed when next opened.
1750 if (relation->rd_isnailed)
1752 relation->rd_targblock = InvalidBlockNumber;
1753 relation->rd_fsm_nblocks_cache = InvalidBlockNumber;
1754 if (relation->rd_rel->relkind == RELKIND_INDEX)
1756 relation->rd_isvalid = false; /* needs to be revalidated */
1757 if (relation->rd_refcnt > 1)
1758 RelationReloadIndexInfo(relation);
1760 return;
1764 * Even non-system indexes should not be blown away if they are open and
1765 * have valid index support information. This avoids problems with active
1766 * use of the index support information. As with nailed indexes, we
1767 * re-read the pg_class row to handle possible physical relocation of the
1768 * index, and we check for pg_index updates too.
1770 if (relation->rd_rel->relkind == RELKIND_INDEX &&
1771 relation->rd_refcnt > 0 &&
1772 relation->rd_indexcxt != NULL)
1774 relation->rd_isvalid = false; /* needs to be revalidated */
1775 RelationReloadIndexInfo(relation);
1776 return;
1780 * Remove relation from hash tables
1782 * Note: we might be reinserting it momentarily, but we must not have it
1783 * visible in the hash tables until it's valid again, so don't try to
1784 * optimize this away...
1786 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
1787 RelationCacheDelete(relation);
1788 MemoryContextSwitchTo(oldcxt);
1790 /* Clear out catcache's entries for this relation */
1791 CatalogCacheFlushRelation(RelationGetRelid(relation));
1794 * Free all the subsidiary data structures of the relcache entry. We
1795 * cannot free rd_att if we are trying to rebuild the entry, however,
1796 * because pointers to it may be cached in various places. The rule
1797 * manager might also have pointers into the rewrite rules. So to begin
1798 * with, we can only get rid of these fields:
1800 FreeTriggerDesc(relation->trigdesc);
1801 if (relation->rd_indextuple)
1802 pfree(relation->rd_indextuple);
1803 if (relation->rd_am)
1804 pfree(relation->rd_am);
1805 if (relation->rd_rel)
1806 pfree(relation->rd_rel);
1807 if (relation->rd_options)
1808 pfree(relation->rd_options);
1809 list_free(relation->rd_indexlist);
1810 bms_free(relation->rd_indexattr);
1811 if (relation->rd_indexcxt)
1812 MemoryContextDelete(relation->rd_indexcxt);
1815 * If we're really done with the relcache entry, blow it away. But if
1816 * someone is still using it, reconstruct the whole deal without moving
1817 * the physical RelationData record (so that the someone's pointer is
1818 * still valid).
1820 if (!rebuild)
1822 /* ok to zap remaining substructure */
1823 flush_rowtype_cache(old_reltype);
1824 /* can't use DecrTupleDescRefCount here */
1825 Assert(relation->rd_att->tdrefcount > 0);
1826 if (--relation->rd_att->tdrefcount == 0)
1827 FreeTupleDesc(relation->rd_att);
1828 if (relation->rd_rulescxt)
1829 MemoryContextDelete(relation->rd_rulescxt);
1830 pfree(relation);
1832 else
1835 * When rebuilding an open relcache entry, must preserve ref count and
1836 * rd_createSubid/rd_newRelfilenodeSubid state. Also attempt to
1837 * preserve the tupledesc and rewrite-rule substructures in place.
1838 * (Note: the refcount mechanism for tupledescs may eventually ensure
1839 * that we don't really need to preserve the tupledesc in-place, but
1840 * for now there are still a lot of places that assume an open rel's
1841 * tupledesc won't move.)
1843 * Note that this process does not touch CurrentResourceOwner; which
1844 * is good because whatever ref counts the entry may have do not
1845 * necessarily belong to that resource owner.
1847 Oid save_relid = RelationGetRelid(relation);
1848 int old_refcnt = relation->rd_refcnt;
1849 SubTransactionId old_createSubid = relation->rd_createSubid;
1850 SubTransactionId old_newRelfilenodeSubid = relation->rd_newRelfilenodeSubid;
1851 struct PgStat_TableStatus *old_pgstat_info = relation->pgstat_info;
1852 TupleDesc old_att = relation->rd_att;
1853 RuleLock *old_rules = relation->rd_rules;
1854 MemoryContext old_rulescxt = relation->rd_rulescxt;
1856 if (RelationBuildDesc(save_relid, relation) != relation)
1858 /* Should only get here if relation was deleted */
1859 flush_rowtype_cache(old_reltype);
1860 Assert(old_att->tdrefcount > 0);
1861 if (--old_att->tdrefcount == 0)
1862 FreeTupleDesc(old_att);
1863 if (old_rulescxt)
1864 MemoryContextDelete(old_rulescxt);
1865 pfree(relation);
1866 elog(ERROR, "relation %u deleted while still in use", save_relid);
1868 relation->rd_refcnt = old_refcnt;
1869 relation->rd_createSubid = old_createSubid;
1870 relation->rd_newRelfilenodeSubid = old_newRelfilenodeSubid;
1871 relation->pgstat_info = old_pgstat_info;
1873 if (equalTupleDescs(old_att, relation->rd_att))
1875 /* needn't flush typcache here */
1876 Assert(relation->rd_att->tdrefcount == 1);
1877 if (--relation->rd_att->tdrefcount == 0)
1878 FreeTupleDesc(relation->rd_att);
1879 relation->rd_att = old_att;
1881 else
1883 flush_rowtype_cache(old_reltype);
1884 Assert(old_att->tdrefcount > 0);
1885 if (--old_att->tdrefcount == 0)
1886 FreeTupleDesc(old_att);
1888 if (equalRuleLocks(old_rules, relation->rd_rules))
1890 if (relation->rd_rulescxt)
1891 MemoryContextDelete(relation->rd_rulescxt);
1892 relation->rd_rules = old_rules;
1893 relation->rd_rulescxt = old_rulescxt;
1895 else
1897 if (old_rulescxt)
1898 MemoryContextDelete(old_rulescxt);
1904 * RelationFlushRelation
1906 * Rebuild the relation if it is open (refcount > 0), else blow it away.
1908 static void
1909 RelationFlushRelation(Relation relation)
1911 bool rebuild;
1913 if (relation->rd_createSubid != InvalidSubTransactionId ||
1914 relation->rd_newRelfilenodeSubid != InvalidSubTransactionId)
1917 * New relcache entries are always rebuilt, not flushed; else we'd
1918 * forget the "new" status of the relation, which is a useful
1919 * optimization to have. Ditto for the new-relfilenode status.
1921 rebuild = true;
1923 else
1926 * Pre-existing rels can be dropped from the relcache if not open.
1928 rebuild = !RelationHasReferenceCountZero(relation);
1931 RelationClearRelation(relation, rebuild);
1935 * RelationForgetRelation - unconditionally remove a relcache entry
1937 * External interface for destroying a relcache entry when we
1938 * drop the relation.
1940 void
1941 RelationForgetRelation(Oid rid)
1943 Relation relation;
1945 RelationIdCacheLookup(rid, relation);
1947 if (!PointerIsValid(relation))
1948 return; /* not in cache, nothing to do */
1950 if (!RelationHasReferenceCountZero(relation))
1951 elog(ERROR, "relation %u is still open", rid);
1953 /* Unconditionally destroy the relcache entry */
1954 RelationClearRelation(relation, false);
1958 * RelationCacheInvalidateEntry
1960 * This routine is invoked for SI cache flush messages.
1962 * Any relcache entry matching the relid must be flushed. (Note: caller has
1963 * already determined that the relid belongs to our database or is a shared
1964 * relation.)
1966 * We used to skip local relations, on the grounds that they could
1967 * not be targets of cross-backend SI update messages; but it seems
1968 * safer to process them, so that our *own* SI update messages will
1969 * have the same effects during CommandCounterIncrement for both
1970 * local and nonlocal relations.
1972 void
1973 RelationCacheInvalidateEntry(Oid relationId)
1975 Relation relation;
1977 RelationIdCacheLookup(relationId, relation);
1979 if (PointerIsValid(relation))
1981 relcacheInvalsReceived++;
1982 RelationFlushRelation(relation);
1987 * RelationCacheInvalidate
1988 * Blow away cached relation descriptors that have zero reference counts,
1989 * and rebuild those with positive reference counts. Also reset the smgr
1990 * relation cache.
1992 * This is currently used only to recover from SI message buffer overflow,
1993 * so we do not touch new-in-transaction relations; they cannot be targets
1994 * of cross-backend SI updates (and our own updates now go through a
1995 * separate linked list that isn't limited by the SI message buffer size).
1996 * Likewise, we need not discard new-relfilenode-in-transaction hints,
1997 * since any invalidation of those would be a local event.
1999 * We do this in two phases: the first pass deletes deletable items, and
2000 * the second one rebuilds the rebuildable items. This is essential for
2001 * safety, because hash_seq_search only copes with concurrent deletion of
2002 * the element it is currently visiting. If a second SI overflow were to
2003 * occur while we are walking the table, resulting in recursive entry to
2004 * this routine, we could crash because the inner invocation blows away
2005 * the entry next to be visited by the outer scan. But this way is OK,
2006 * because (a) during the first pass we won't process any more SI messages,
2007 * so hash_seq_search will complete safely; (b) during the second pass we
2008 * only hold onto pointers to nondeletable entries.
2010 * The two-phase approach also makes it easy to ensure that we process
2011 * nailed-in-cache indexes before other nondeletable items, and that we
2012 * process pg_class_oid_index first of all. In scenarios where a nailed
2013 * index has been given a new relfilenode, we have to detect that update
2014 * before the nailed index is used in reloading any other relcache entry.
2016 void
2017 RelationCacheInvalidate(void)
2019 HASH_SEQ_STATUS status;
2020 RelIdCacheEnt *idhentry;
2021 Relation relation;
2022 List *rebuildFirstList = NIL;
2023 List *rebuildList = NIL;
2024 ListCell *l;
2026 /* Phase 1 */
2027 hash_seq_init(&status, RelationIdCache);
2029 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
2031 relation = idhentry->reldesc;
2033 /* Must close all smgr references to avoid leaving dangling ptrs */
2034 RelationCloseSmgr(relation);
2036 /* Ignore new relations, since they are never SI targets */
2037 if (relation->rd_createSubid != InvalidSubTransactionId)
2038 continue;
2040 relcacheInvalsReceived++;
2042 if (RelationHasReferenceCountZero(relation))
2044 /* Delete this entry immediately */
2045 Assert(!relation->rd_isnailed);
2046 RelationClearRelation(relation, false);
2048 else
2051 * Add this entry to list of stuff to rebuild in second pass.
2052 * pg_class_oid_index goes on the front of rebuildFirstList, other
2053 * nailed indexes on the back, and everything else into
2054 * rebuildList (in no particular order).
2056 if (relation->rd_isnailed &&
2057 relation->rd_rel->relkind == RELKIND_INDEX)
2059 if (RelationGetRelid(relation) == ClassOidIndexId)
2060 rebuildFirstList = lcons(relation, rebuildFirstList);
2061 else
2062 rebuildFirstList = lappend(rebuildFirstList, relation);
2064 else
2065 rebuildList = lcons(relation, rebuildList);
2070 * Now zap any remaining smgr cache entries. This must happen before we
2071 * start to rebuild entries, since that may involve catalog fetches which
2072 * will re-open catalog files.
2074 smgrcloseall();
2076 /* Phase 2: rebuild the items found to need rebuild in phase 1 */
2077 foreach(l, rebuildFirstList)
2079 relation = (Relation) lfirst(l);
2080 RelationClearRelation(relation, true);
2082 list_free(rebuildFirstList);
2083 foreach(l, rebuildList)
2085 relation = (Relation) lfirst(l);
2086 RelationClearRelation(relation, true);
2088 list_free(rebuildList);
2092 * AtEOXact_RelationCache
2094 * Clean up the relcache at main-transaction commit or abort.
2096 * Note: this must be called *before* processing invalidation messages.
2097 * In the case of abort, we don't want to try to rebuild any invalidated
2098 * cache entries (since we can't safely do database accesses). Therefore
2099 * we must reset refcnts before handling pending invalidations.
2101 * As of PostgreSQL 8.1, relcache refcnts should get released by the
2102 * ResourceOwner mechanism. This routine just does a debugging
2103 * cross-check that no pins remain. However, we also need to do special
2104 * cleanup when the current transaction created any relations or made use
2105 * of forced index lists.
2107 void
2108 AtEOXact_RelationCache(bool isCommit)
2110 HASH_SEQ_STATUS status;
2111 RelIdCacheEnt *idhentry;
2114 * To speed up transaction exit, we want to avoid scanning the relcache
2115 * unless there is actually something for this routine to do. Other than
2116 * the debug-only Assert checks, most transactions don't create any work
2117 * for us to do here, so we keep a static flag that gets set if there is
2118 * anything to do. (Currently, this means either a relation is created in
2119 * the current xact, or one is given a new relfilenode, or an index list
2120 * is forced.) For simplicity, the flag remains set till end of top-level
2121 * transaction, even though we could clear it at subtransaction end in
2122 * some cases.
2124 if (!need_eoxact_work
2125 #ifdef USE_ASSERT_CHECKING
2126 && !assert_enabled
2127 #endif
2129 return;
2131 hash_seq_init(&status, RelationIdCache);
2133 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
2135 Relation relation = idhentry->reldesc;
2138 * The relcache entry's ref count should be back to its normal
2139 * not-in-a-transaction state: 0 unless it's nailed in cache.
2141 * In bootstrap mode, this is NOT true, so don't check it --- the
2142 * bootstrap code expects relations to stay open across start/commit
2143 * transaction calls. (That seems bogus, but it's not worth fixing.)
2145 #ifdef USE_ASSERT_CHECKING
2146 if (!IsBootstrapProcessingMode())
2148 int expected_refcnt;
2150 expected_refcnt = relation->rd_isnailed ? 1 : 0;
2151 Assert(relation->rd_refcnt == expected_refcnt);
2153 #endif
2156 * Is it a relation created in the current transaction?
2158 * During commit, reset the flag to zero, since we are now out of the
2159 * creating transaction. During abort, simply delete the relcache
2160 * entry --- it isn't interesting any longer. (NOTE: if we have
2161 * forgotten the new-ness of a new relation due to a forced cache
2162 * flush, the entry will get deleted anyway by shared-cache-inval
2163 * processing of the aborted pg_class insertion.)
2165 if (relation->rd_createSubid != InvalidSubTransactionId)
2167 if (isCommit)
2168 relation->rd_createSubid = InvalidSubTransactionId;
2169 else
2171 RelationClearRelation(relation, false);
2172 continue;
2177 * Likewise, reset the hint about the relfilenode being new.
2179 relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
2182 * Flush any temporary index list.
2184 if (relation->rd_indexvalid == 2)
2186 list_free(relation->rd_indexlist);
2187 relation->rd_indexlist = NIL;
2188 relation->rd_oidindex = InvalidOid;
2189 relation->rd_indexvalid = 0;
2193 /* Once done with the transaction, we can reset need_eoxact_work */
2194 need_eoxact_work = false;
2198 * AtEOSubXact_RelationCache
2200 * Clean up the relcache at sub-transaction commit or abort.
2202 * Note: this must be called *before* processing invalidation messages.
2204 void
2205 AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid,
2206 SubTransactionId parentSubid)
2208 HASH_SEQ_STATUS status;
2209 RelIdCacheEnt *idhentry;
2212 * Skip the relcache scan if nothing to do --- see notes for
2213 * AtEOXact_RelationCache.
2215 if (!need_eoxact_work)
2216 return;
2218 hash_seq_init(&status, RelationIdCache);
2220 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
2222 Relation relation = idhentry->reldesc;
2225 * Is it a relation created in the current subtransaction?
2227 * During subcommit, mark it as belonging to the parent, instead.
2228 * During subabort, simply delete the relcache entry.
2230 if (relation->rd_createSubid == mySubid)
2232 if (isCommit)
2233 relation->rd_createSubid = parentSubid;
2234 else
2236 Assert(RelationHasReferenceCountZero(relation));
2237 RelationClearRelation(relation, false);
2238 continue;
2243 * Likewise, update or drop any new-relfilenode-in-subtransaction
2244 * hint.
2246 if (relation->rd_newRelfilenodeSubid == mySubid)
2248 if (isCommit)
2249 relation->rd_newRelfilenodeSubid = parentSubid;
2250 else
2251 relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
2255 * Flush any temporary index list.
2257 if (relation->rd_indexvalid == 2)
2259 list_free(relation->rd_indexlist);
2260 relation->rd_indexlist = NIL;
2261 relation->rd_oidindex = InvalidOid;
2262 relation->rd_indexvalid = 0;
2268 * RelationCacheMarkNewRelfilenode
2270 * Mark the rel as having been given a new relfilenode in the current
2271 * (sub) transaction. This is a hint that can be used to optimize
2272 * later operations on the rel in the same transaction.
2274 void
2275 RelationCacheMarkNewRelfilenode(Relation rel)
2277 /* Mark it... */
2278 rel->rd_newRelfilenodeSubid = GetCurrentSubTransactionId();
2279 /* ... and now we have eoxact cleanup work to do */
2280 need_eoxact_work = true;
2285 * RelationBuildLocalRelation
2286 * Build a relcache entry for an about-to-be-created relation,
2287 * and enter it into the relcache.
2289 Relation
2290 RelationBuildLocalRelation(const char *relname,
2291 Oid relnamespace,
2292 TupleDesc tupDesc,
2293 Oid relid,
2294 Oid reltablespace,
2295 bool shared_relation)
2297 Relation rel;
2298 MemoryContext oldcxt;
2299 int natts = tupDesc->natts;
2300 int i;
2301 bool has_not_null;
2302 bool nailit;
2304 AssertArg(natts >= 0);
2307 * check for creation of a rel that must be nailed in cache.
2309 * XXX this list had better match RelationCacheInitializePhase2's list.
2311 switch (relid)
2313 case RelationRelationId:
2314 case AttributeRelationId:
2315 case ProcedureRelationId:
2316 case TypeRelationId:
2317 nailit = true;
2318 break;
2319 default:
2320 nailit = false;
2321 break;
2325 * check that hardwired list of shared rels matches what's in the
2326 * bootstrap .bki file. If you get a failure here during initdb, you
2327 * probably need to fix IsSharedRelation() to match whatever you've done
2328 * to the set of shared relations.
2330 if (shared_relation != IsSharedRelation(relid))
2331 elog(ERROR, "shared_relation flag for \"%s\" does not match IsSharedRelation(%u)",
2332 relname, relid);
2335 * switch to the cache context to create the relcache entry.
2337 if (!CacheMemoryContext)
2338 CreateCacheMemoryContext();
2340 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2343 * allocate a new relation descriptor and fill in basic state fields.
2345 rel = (Relation) palloc0(sizeof(RelationData));
2347 rel->rd_targblock = InvalidBlockNumber;
2348 rel->rd_fsm_nblocks_cache = InvalidBlockNumber;
2350 /* make sure relation is marked as having no open file yet */
2351 rel->rd_smgr = NULL;
2353 /* mark it nailed if appropriate */
2354 rel->rd_isnailed = nailit;
2356 rel->rd_refcnt = nailit ? 1 : 0;
2358 /* it's being created in this transaction */
2359 rel->rd_createSubid = GetCurrentSubTransactionId();
2360 rel->rd_newRelfilenodeSubid = InvalidSubTransactionId;
2362 /* must flag that we have rels created in this transaction */
2363 need_eoxact_work = true;
2365 /* is it a temporary relation? */
2366 rel->rd_istemp = isTempOrToastNamespace(relnamespace);
2369 * create a new tuple descriptor from the one passed in. We do this
2370 * partly to copy it into the cache context, and partly because the new
2371 * relation can't have any defaults or constraints yet; they have to be
2372 * added in later steps, because they require additions to multiple system
2373 * catalogs. We can copy attnotnull constraints here, however.
2375 rel->rd_att = CreateTupleDescCopy(tupDesc);
2376 rel->rd_att->tdrefcount = 1; /* mark as refcounted */
2377 has_not_null = false;
2378 for (i = 0; i < natts; i++)
2380 rel->rd_att->attrs[i]->attnotnull = tupDesc->attrs[i]->attnotnull;
2381 has_not_null |= tupDesc->attrs[i]->attnotnull;
2384 if (has_not_null)
2386 TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
2388 constr->has_not_null = true;
2389 rel->rd_att->constr = constr;
2393 * initialize relation tuple form (caller may add/override data later)
2395 rel->rd_rel = (Form_pg_class) palloc0(CLASS_TUPLE_SIZE);
2397 namestrcpy(&rel->rd_rel->relname, relname);
2398 rel->rd_rel->relnamespace = relnamespace;
2400 rel->rd_rel->relkind = RELKIND_UNCATALOGED;
2401 rel->rd_rel->relhasoids = rel->rd_att->tdhasoid;
2402 rel->rd_rel->relnatts = natts;
2403 rel->rd_rel->reltype = InvalidOid;
2404 /* needed when bootstrapping: */
2405 rel->rd_rel->relowner = BOOTSTRAP_SUPERUSERID;
2408 * Insert relation physical and logical identifiers (OIDs) into the right
2409 * places. Note that the physical ID (relfilenode) is initially the same
2410 * as the logical ID (OID).
2412 rel->rd_rel->relisshared = shared_relation;
2414 RelationGetRelid(rel) = relid;
2416 for (i = 0; i < natts; i++)
2417 rel->rd_att->attrs[i]->attrelid = relid;
2419 rel->rd_rel->relfilenode = relid;
2420 rel->rd_rel->reltablespace = reltablespace;
2422 RelationInitLockInfo(rel); /* see lmgr.c */
2424 RelationInitPhysicalAddr(rel);
2427 * Okay to insert into the relcache hash tables.
2429 RelationCacheInsert(rel);
2432 * done building relcache entry.
2434 MemoryContextSwitchTo(oldcxt);
2436 /* It's fully valid */
2437 rel->rd_isvalid = true;
2440 * Caller expects us to pin the returned entry.
2442 RelationIncrementReferenceCount(rel);
2444 return rel;
2448 * RelationCacheInitialize
2450 * This initializes the relation descriptor cache. At the time
2451 * that this is invoked, we can't do database access yet (mainly
2452 * because the transaction subsystem is not up); all we are doing
2453 * is making an empty cache hashtable. This must be done before
2454 * starting the initialization transaction, because otherwise
2455 * AtEOXact_RelationCache would crash if that transaction aborts
2456 * before we can get the relcache set up.
2459 #define INITRELCACHESIZE 400
2461 void
2462 RelationCacheInitialize(void)
2464 MemoryContext oldcxt;
2465 HASHCTL ctl;
2468 * switch to cache memory context
2470 if (!CacheMemoryContext)
2471 CreateCacheMemoryContext();
2473 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2476 * create hashtable that indexes the relcache
2478 MemSet(&ctl, 0, sizeof(ctl));
2479 ctl.keysize = sizeof(Oid);
2480 ctl.entrysize = sizeof(RelIdCacheEnt);
2481 ctl.hash = oid_hash;
2482 RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
2483 &ctl, HASH_ELEM | HASH_FUNCTION);
2485 MemoryContextSwitchTo(oldcxt);
2489 * RelationCacheInitializePhase2
2491 * This is called as soon as the catcache and transaction system
2492 * are functional. At this point we can actually read data from
2493 * the system catalogs. We first try to read pre-computed relcache
2494 * entries from the pg_internal.init file. If that's missing or
2495 * broken, make phony entries for the minimum set of nailed-in-cache
2496 * relations. Then (unless bootstrapping) make sure we have entries
2497 * for the critical system indexes. Once we've done all this, we
2498 * have enough infrastructure to open any system catalog or use any
2499 * catcache. The last step is to rewrite pg_internal.init if needed.
2501 void
2502 RelationCacheInitializePhase2(void)
2504 HASH_SEQ_STATUS status;
2505 RelIdCacheEnt *idhentry;
2506 MemoryContext oldcxt;
2507 bool needNewCacheFile = false;
2510 * switch to cache memory context
2512 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2515 * Try to load the relcache cache file. If unsuccessful, bootstrap the
2516 * cache with pre-made descriptors for the critical "nailed-in" system
2517 * catalogs.
2519 if (IsBootstrapProcessingMode() ||
2520 !load_relcache_init_file())
2522 needNewCacheFile = true;
2524 formrdesc("pg_class", PG_CLASS_RELTYPE_OID,
2525 true, Natts_pg_class, Desc_pg_class);
2526 formrdesc("pg_attribute", PG_ATTRIBUTE_RELTYPE_OID,
2527 false, Natts_pg_attribute, Desc_pg_attribute);
2528 formrdesc("pg_proc", PG_PROC_RELTYPE_OID,
2529 true, Natts_pg_proc, Desc_pg_proc);
2530 formrdesc("pg_type", PG_TYPE_RELTYPE_OID,
2531 true, Natts_pg_type, Desc_pg_type);
2533 #define NUM_CRITICAL_RELS 4 /* fix if you change list above */
2536 MemoryContextSwitchTo(oldcxt);
2538 /* In bootstrap mode, the faked-up formrdesc info is all we'll have */
2539 if (IsBootstrapProcessingMode())
2540 return;
2543 * If we didn't get the critical system indexes loaded into relcache, do
2544 * so now. These are critical because the catcache and/or opclass cache
2545 * depend on them for fetches done during relcache load. Thus, we have an
2546 * infinite-recursion problem. We can break the recursion by doing
2547 * heapscans instead of indexscans at certain key spots. To avoid hobbling
2548 * performance, we only want to do that until we have the critical indexes
2549 * loaded into relcache. Thus, the flag criticalRelcachesBuilt is used to
2550 * decide whether to do heapscan or indexscan at the key spots, and we set
2551 * it true after we've loaded the critical indexes.
2553 * The critical indexes are marked as "nailed in cache", partly to make it
2554 * easy for load_relcache_init_file to count them, but mainly because we
2555 * cannot flush and rebuild them once we've set criticalRelcachesBuilt to
2556 * true. (NOTE: perhaps it would be possible to reload them by
2557 * temporarily setting criticalRelcachesBuilt to false again. For now,
2558 * though, we just nail 'em in.)
2560 * RewriteRelRulenameIndexId and TriggerRelidNameIndexId are not critical
2561 * in the same way as the others, because the critical catalogs don't
2562 * (currently) have any rules or triggers, and so these indexes can be
2563 * rebuilt without inducing recursion. However they are used during
2564 * relcache load when a rel does have rules or triggers, so we choose to
2565 * nail them for performance reasons.
2567 if (!criticalRelcachesBuilt)
2569 Relation ird;
2571 #define LOAD_CRIT_INDEX(indexoid) \
2572 do { \
2573 LockRelationOid(indexoid, AccessShareLock); \
2574 ird = RelationBuildDesc(indexoid, NULL); \
2575 if (ird == NULL) \
2576 elog(PANIC, "could not open critical system index %u", \
2577 indexoid); \
2578 ird->rd_isnailed = true; \
2579 ird->rd_refcnt = 1; \
2580 UnlockRelationOid(indexoid, AccessShareLock); \
2581 } while (0)
2583 LOAD_CRIT_INDEX(ClassOidIndexId);
2584 LOAD_CRIT_INDEX(AttributeRelidNumIndexId);
2585 LOAD_CRIT_INDEX(IndexRelidIndexId);
2586 LOAD_CRIT_INDEX(OpclassOidIndexId);
2587 LOAD_CRIT_INDEX(AccessMethodStrategyIndexId);
2588 LOAD_CRIT_INDEX(AccessMethodProcedureIndexId);
2589 LOAD_CRIT_INDEX(OperatorOidIndexId);
2590 LOAD_CRIT_INDEX(RewriteRelRulenameIndexId);
2591 LOAD_CRIT_INDEX(TriggerRelidNameIndexId);
2593 #define NUM_CRITICAL_INDEXES 9 /* fix if you change list above */
2595 criticalRelcachesBuilt = true;
2599 * Now, scan all the relcache entries and update anything that might be
2600 * wrong in the results from formrdesc or the relcache cache file. If we
2601 * faked up relcache entries using formrdesc, then read the real pg_class
2602 * rows and replace the fake entries with them. Also, if any of the
2603 * relcache entries have rules or triggers, load that info the hard way
2604 * since it isn't recorded in the cache file.
2606 hash_seq_init(&status, RelationIdCache);
2608 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
2610 Relation relation = idhentry->reldesc;
2613 * If it's a faked-up entry, read the real pg_class tuple.
2615 if (needNewCacheFile && relation->rd_isnailed)
2617 HeapTuple htup;
2618 Form_pg_class relp;
2620 htup = SearchSysCache(RELOID,
2621 ObjectIdGetDatum(RelationGetRelid(relation)),
2622 0, 0, 0);
2623 if (!HeapTupleIsValid(htup))
2624 elog(FATAL, "cache lookup failed for relation %u",
2625 RelationGetRelid(relation));
2626 relp = (Form_pg_class) GETSTRUCT(htup);
2629 * Copy tuple to relation->rd_rel. (See notes in
2630 * AllocateRelationDesc())
2632 Assert(relation->rd_rel != NULL);
2633 memcpy((char *) relation->rd_rel, (char *) relp, CLASS_TUPLE_SIZE);
2635 /* Update rd_options while we have the tuple */
2636 if (relation->rd_options)
2637 pfree(relation->rd_options);
2638 RelationParseRelOptions(relation, htup);
2641 * Also update the derived fields in rd_att.
2643 relation->rd_att->tdtypeid = relp->reltype;
2644 relation->rd_att->tdtypmod = -1; /* unnecessary, but... */
2645 relation->rd_att->tdhasoid = relp->relhasoids;
2647 ReleaseSysCache(htup);
2651 * Fix data that isn't saved in relcache cache file.
2653 if (relation->rd_rel->relhasrules && relation->rd_rules == NULL)
2654 RelationBuildRuleLock(relation);
2655 if (relation->rd_rel->relhastriggers && relation->trigdesc == NULL)
2656 RelationBuildTriggers(relation);
2660 * Lastly, write out a new relcache cache file if one is needed.
2662 if (needNewCacheFile)
2665 * Force all the catcaches to finish initializing and thereby open the
2666 * catalogs and indexes they use. This will preload the relcache with
2667 * entries for all the most important system catalogs and indexes, so
2668 * that the init file will be most useful for future backends.
2670 InitCatalogCachePhase2();
2672 /* now write the file */
2673 write_relcache_init_file();
2678 * GetPgClassDescriptor -- get a predefined tuple descriptor for pg_class
2679 * GetPgIndexDescriptor -- get a predefined tuple descriptor for pg_index
2681 * We need this kluge because we have to be able to access non-fixed-width
2682 * fields of pg_class and pg_index before we have the standard catalog caches
2683 * available. We use predefined data that's set up in just the same way as
2684 * the bootstrapped reldescs used by formrdesc(). The resulting tupdesc is
2685 * not 100% kosher: it does not have the correct rowtype OID in tdtypeid, nor
2686 * does it have a TupleConstr field. But it's good enough for the purpose of
2687 * extracting fields.
2689 static TupleDesc
2690 BuildHardcodedDescriptor(int natts, Form_pg_attribute attrs, bool hasoids)
2692 TupleDesc result;
2693 MemoryContext oldcxt;
2694 int i;
2696 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2698 result = CreateTemplateTupleDesc(natts, hasoids);
2699 result->tdtypeid = RECORDOID; /* not right, but we don't care */
2700 result->tdtypmod = -1;
2702 for (i = 0; i < natts; i++)
2704 memcpy(result->attrs[i], &attrs[i], ATTRIBUTE_TUPLE_SIZE);
2705 /* make sure attcacheoff is valid */
2706 result->attrs[i]->attcacheoff = -1;
2709 /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
2710 result->attrs[0]->attcacheoff = 0;
2712 /* Note: we don't bother to set up a TupleConstr entry */
2714 MemoryContextSwitchTo(oldcxt);
2716 return result;
2719 static TupleDesc
2720 GetPgClassDescriptor(void)
2722 static TupleDesc pgclassdesc = NULL;
2724 /* Already done? */
2725 if (pgclassdesc == NULL)
2726 pgclassdesc = BuildHardcodedDescriptor(Natts_pg_class,
2727 Desc_pg_class,
2728 true);
2730 return pgclassdesc;
2733 static TupleDesc
2734 GetPgIndexDescriptor(void)
2736 static TupleDesc pgindexdesc = NULL;
2738 /* Already done? */
2739 if (pgindexdesc == NULL)
2740 pgindexdesc = BuildHardcodedDescriptor(Natts_pg_index,
2741 Desc_pg_index,
2742 false);
2744 return pgindexdesc;
2747 static void
2748 AttrDefaultFetch(Relation relation)
2750 AttrDefault *attrdef = relation->rd_att->constr->defval;
2751 int ndef = relation->rd_att->constr->num_defval;
2752 Relation adrel;
2753 SysScanDesc adscan;
2754 ScanKeyData skey;
2755 HeapTuple htup;
2756 Datum val;
2757 bool isnull;
2758 int found;
2759 int i;
2761 ScanKeyInit(&skey,
2762 Anum_pg_attrdef_adrelid,
2763 BTEqualStrategyNumber, F_OIDEQ,
2764 ObjectIdGetDatum(RelationGetRelid(relation)));
2766 adrel = heap_open(AttrDefaultRelationId, AccessShareLock);
2767 adscan = systable_beginscan(adrel, AttrDefaultIndexId, true,
2768 SnapshotNow, 1, &skey);
2769 found = 0;
2771 while (HeapTupleIsValid(htup = systable_getnext(adscan)))
2773 Form_pg_attrdef adform = (Form_pg_attrdef) GETSTRUCT(htup);
2775 for (i = 0; i < ndef; i++)
2777 if (adform->adnum != attrdef[i].adnum)
2778 continue;
2779 if (attrdef[i].adbin != NULL)
2780 elog(WARNING, "multiple attrdef records found for attr %s of rel %s",
2781 NameStr(relation->rd_att->attrs[adform->adnum - 1]->attname),
2782 RelationGetRelationName(relation));
2783 else
2784 found++;
2786 val = fastgetattr(htup,
2787 Anum_pg_attrdef_adbin,
2788 adrel->rd_att, &isnull);
2789 if (isnull)
2790 elog(WARNING, "null adbin for attr %s of rel %s",
2791 NameStr(relation->rd_att->attrs[adform->adnum - 1]->attname),
2792 RelationGetRelationName(relation));
2793 else
2794 attrdef[i].adbin = MemoryContextStrdup(CacheMemoryContext,
2795 TextDatumGetCString(val));
2796 break;
2799 if (i >= ndef)
2800 elog(WARNING, "unexpected attrdef record found for attr %d of rel %s",
2801 adform->adnum, RelationGetRelationName(relation));
2804 systable_endscan(adscan);
2805 heap_close(adrel, AccessShareLock);
2807 if (found != ndef)
2808 elog(WARNING, "%d attrdef record(s) missing for rel %s",
2809 ndef - found, RelationGetRelationName(relation));
2812 static void
2813 CheckConstraintFetch(Relation relation)
2815 ConstrCheck *check = relation->rd_att->constr->check;
2816 int ncheck = relation->rd_att->constr->num_check;
2817 Relation conrel;
2818 SysScanDesc conscan;
2819 ScanKeyData skey[1];
2820 HeapTuple htup;
2821 Datum val;
2822 bool isnull;
2823 int found = 0;
2825 ScanKeyInit(&skey[0],
2826 Anum_pg_constraint_conrelid,
2827 BTEqualStrategyNumber, F_OIDEQ,
2828 ObjectIdGetDatum(RelationGetRelid(relation)));
2830 conrel = heap_open(ConstraintRelationId, AccessShareLock);
2831 conscan = systable_beginscan(conrel, ConstraintRelidIndexId, true,
2832 SnapshotNow, 1, skey);
2834 while (HeapTupleIsValid(htup = systable_getnext(conscan)))
2836 Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(htup);
2838 /* We want check constraints only */
2839 if (conform->contype != CONSTRAINT_CHECK)
2840 continue;
2842 if (found >= ncheck)
2843 elog(ERROR, "unexpected constraint record found for rel %s",
2844 RelationGetRelationName(relation));
2846 check[found].ccname = MemoryContextStrdup(CacheMemoryContext,
2847 NameStr(conform->conname));
2849 /* Grab and test conbin is actually set */
2850 val = fastgetattr(htup,
2851 Anum_pg_constraint_conbin,
2852 conrel->rd_att, &isnull);
2853 if (isnull)
2854 elog(ERROR, "null conbin for rel %s",
2855 RelationGetRelationName(relation));
2857 check[found].ccbin = MemoryContextStrdup(CacheMemoryContext,
2858 TextDatumGetCString(val));
2859 found++;
2862 systable_endscan(conscan);
2863 heap_close(conrel, AccessShareLock);
2865 if (found != ncheck)
2866 elog(ERROR, "%d constraint record(s) missing for rel %s",
2867 ncheck - found, RelationGetRelationName(relation));
2871 * RelationGetIndexList -- get a list of OIDs of indexes on this relation
2873 * The index list is created only if someone requests it. We scan pg_index
2874 * to find relevant indexes, and add the list to the relcache entry so that
2875 * we won't have to compute it again. Note that shared cache inval of a
2876 * relcache entry will delete the old list and set rd_indexvalid to 0,
2877 * so that we must recompute the index list on next request. This handles
2878 * creation or deletion of an index.
2880 * The returned list is guaranteed to be sorted in order by OID. This is
2881 * needed by the executor, since for index types that we obtain exclusive
2882 * locks on when updating the index, all backends must lock the indexes in
2883 * the same order or we will get deadlocks (see ExecOpenIndices()). Any
2884 * consistent ordering would do, but ordering by OID is easy.
2886 * Since shared cache inval causes the relcache's copy of the list to go away,
2887 * we return a copy of the list palloc'd in the caller's context. The caller
2888 * may list_free() the returned list after scanning it. This is necessary
2889 * since the caller will typically be doing syscache lookups on the relevant
2890 * indexes, and syscache lookup could cause SI messages to be processed!
2892 * We also update rd_oidindex, which this module treats as effectively part
2893 * of the index list. rd_oidindex is valid when rd_indexvalid isn't zero;
2894 * it is the pg_class OID of a unique index on OID when the relation has one,
2895 * and InvalidOid if there is no such index.
2897 List *
2898 RelationGetIndexList(Relation relation)
2900 Relation indrel;
2901 SysScanDesc indscan;
2902 ScanKeyData skey;
2903 HeapTuple htup;
2904 List *result;
2905 Oid oidIndex;
2906 MemoryContext oldcxt;
2908 /* Quick exit if we already computed the list. */
2909 if (relation->rd_indexvalid != 0)
2910 return list_copy(relation->rd_indexlist);
2913 * We build the list we intend to return (in the caller's context) while
2914 * doing the scan. After successfully completing the scan, we copy that
2915 * list into the relcache entry. This avoids cache-context memory leakage
2916 * if we get some sort of error partway through.
2918 result = NIL;
2919 oidIndex = InvalidOid;
2921 /* Prepare to scan pg_index for entries having indrelid = this rel. */
2922 ScanKeyInit(&skey,
2923 Anum_pg_index_indrelid,
2924 BTEqualStrategyNumber, F_OIDEQ,
2925 ObjectIdGetDatum(RelationGetRelid(relation)));
2927 indrel = heap_open(IndexRelationId, AccessShareLock);
2928 indscan = systable_beginscan(indrel, IndexIndrelidIndexId, true,
2929 SnapshotNow, 1, &skey);
2931 while (HeapTupleIsValid(htup = systable_getnext(indscan)))
2933 Form_pg_index index = (Form_pg_index) GETSTRUCT(htup);
2935 /* Add index's OID to result list in the proper order */
2936 result = insert_ordered_oid(result, index->indexrelid);
2938 /* Check to see if it is a unique, non-partial btree index on OID */
2939 if (index->indnatts == 1 &&
2940 index->indisunique &&
2941 index->indkey.values[0] == ObjectIdAttributeNumber &&
2942 index->indclass.values[0] == OID_BTREE_OPS_OID &&
2943 heap_attisnull(htup, Anum_pg_index_indpred))
2944 oidIndex = index->indexrelid;
2947 systable_endscan(indscan);
2948 heap_close(indrel, AccessShareLock);
2950 /* Now save a copy of the completed list in the relcache entry. */
2951 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2952 relation->rd_indexlist = list_copy(result);
2953 relation->rd_oidindex = oidIndex;
2954 relation->rd_indexvalid = 1;
2955 MemoryContextSwitchTo(oldcxt);
2957 return result;
2961 * insert_ordered_oid
2962 * Insert a new Oid into a sorted list of Oids, preserving ordering
2964 * Building the ordered list this way is O(N^2), but with a pretty small
2965 * constant, so for the number of entries we expect it will probably be
2966 * faster than trying to apply qsort(). Most tables don't have very many
2967 * indexes...
2969 static List *
2970 insert_ordered_oid(List *list, Oid datum)
2972 ListCell *prev;
2974 /* Does the datum belong at the front? */
2975 if (list == NIL || datum < linitial_oid(list))
2976 return lcons_oid(datum, list);
2977 /* No, so find the entry it belongs after */
2978 prev = list_head(list);
2979 for (;;)
2981 ListCell *curr = lnext(prev);
2983 if (curr == NULL || datum < lfirst_oid(curr))
2984 break; /* it belongs after 'prev', before 'curr' */
2986 prev = curr;
2988 /* Insert datum into list after 'prev' */
2989 lappend_cell_oid(list, prev, datum);
2990 return list;
2994 * RelationSetIndexList -- externally force the index list contents
2996 * This is used to temporarily override what we think the set of valid
2997 * indexes is (including the presence or absence of an OID index).
2998 * The forcing will be valid only until transaction commit or abort.
3000 * This should only be applied to nailed relations, because in a non-nailed
3001 * relation the hacked index list could be lost at any time due to SI
3002 * messages. In practice it is only used on pg_class (see REINDEX).
3004 * It is up to the caller to make sure the given list is correctly ordered.
3006 * We deliberately do not change rd_indexattr here: even when operating
3007 * with a temporary partial index list, HOT-update decisions must be made
3008 * correctly with respect to the full index set. It is up to the caller
3009 * to ensure that a correct rd_indexattr set has been cached before first
3010 * calling RelationSetIndexList; else a subsequent inquiry might cause a
3011 * wrong rd_indexattr set to get computed and cached.
3013 void
3014 RelationSetIndexList(Relation relation, List *indexIds, Oid oidIndex)
3016 MemoryContext oldcxt;
3018 Assert(relation->rd_isnailed);
3019 /* Copy the list into the cache context (could fail for lack of mem) */
3020 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3021 indexIds = list_copy(indexIds);
3022 MemoryContextSwitchTo(oldcxt);
3023 /* Okay to replace old list */
3024 list_free(relation->rd_indexlist);
3025 relation->rd_indexlist = indexIds;
3026 relation->rd_oidindex = oidIndex;
3027 relation->rd_indexvalid = 2; /* mark list as forced */
3028 /* must flag that we have a forced index list */
3029 need_eoxact_work = true;
3033 * RelationGetOidIndex -- get the pg_class OID of the relation's OID index
3035 * Returns InvalidOid if there is no such index.
3038 RelationGetOidIndex(Relation relation)
3040 List *ilist;
3043 * If relation doesn't have OIDs at all, caller is probably confused. (We
3044 * could just silently return InvalidOid, but it seems better to throw an
3045 * assertion.)
3047 Assert(relation->rd_rel->relhasoids);
3049 if (relation->rd_indexvalid == 0)
3051 /* RelationGetIndexList does the heavy lifting. */
3052 ilist = RelationGetIndexList(relation);
3053 list_free(ilist);
3054 Assert(relation->rd_indexvalid != 0);
3057 return relation->rd_oidindex;
3061 * RelationGetIndexExpressions -- get the index expressions for an index
3063 * We cache the result of transforming pg_index.indexprs into a node tree.
3064 * If the rel is not an index or has no expressional columns, we return NIL.
3065 * Otherwise, the returned tree is copied into the caller's memory context.
3066 * (We don't want to return a pointer to the relcache copy, since it could
3067 * disappear due to relcache invalidation.)
3069 List *
3070 RelationGetIndexExpressions(Relation relation)
3072 List *result;
3073 Datum exprsDatum;
3074 bool isnull;
3075 char *exprsString;
3076 MemoryContext oldcxt;
3078 /* Quick exit if we already computed the result. */
3079 if (relation->rd_indexprs)
3080 return (List *) copyObject(relation->rd_indexprs);
3082 /* Quick exit if there is nothing to do. */
3083 if (relation->rd_indextuple == NULL ||
3084 heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs))
3085 return NIL;
3088 * We build the tree we intend to return in the caller's context. After
3089 * successfully completing the work, we copy it into the relcache entry.
3090 * This avoids problems if we get some sort of error partway through.
3092 exprsDatum = heap_getattr(relation->rd_indextuple,
3093 Anum_pg_index_indexprs,
3094 GetPgIndexDescriptor(),
3095 &isnull);
3096 Assert(!isnull);
3097 exprsString = TextDatumGetCString(exprsDatum);
3098 result = (List *) stringToNode(exprsString);
3099 pfree(exprsString);
3102 * Run the expressions through eval_const_expressions. This is not just an
3103 * optimization, but is necessary, because the planner will be comparing
3104 * them to similarly-processed qual clauses, and may fail to detect valid
3105 * matches without this. We don't bother with canonicalize_qual, however.
3107 result = (List *) eval_const_expressions(NULL, (Node *) result);
3110 * Also mark any coercion format fields as "don't care", so that the
3111 * planner can match to both explicit and implicit coercions.
3113 set_coercionform_dontcare((Node *) result);
3115 /* May as well fix opfuncids too */
3116 fix_opfuncids((Node *) result);
3118 /* Now save a copy of the completed tree in the relcache entry. */
3119 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3120 relation->rd_indexprs = (List *) copyObject(result);
3121 MemoryContextSwitchTo(oldcxt);
3123 return result;
3127 * RelationGetIndexPredicate -- get the index predicate for an index
3129 * We cache the result of transforming pg_index.indpred into an implicit-AND
3130 * node tree (suitable for ExecQual).
3131 * If the rel is not an index or has no predicate, we return NIL.
3132 * Otherwise, the returned tree is copied into the caller's memory context.
3133 * (We don't want to return a pointer to the relcache copy, since it could
3134 * disappear due to relcache invalidation.)
3136 List *
3137 RelationGetIndexPredicate(Relation relation)
3139 List *result;
3140 Datum predDatum;
3141 bool isnull;
3142 char *predString;
3143 MemoryContext oldcxt;
3145 /* Quick exit if we already computed the result. */
3146 if (relation->rd_indpred)
3147 return (List *) copyObject(relation->rd_indpred);
3149 /* Quick exit if there is nothing to do. */
3150 if (relation->rd_indextuple == NULL ||
3151 heap_attisnull(relation->rd_indextuple, Anum_pg_index_indpred))
3152 return NIL;
3155 * We build the tree we intend to return in the caller's context. After
3156 * successfully completing the work, we copy it into the relcache entry.
3157 * This avoids problems if we get some sort of error partway through.
3159 predDatum = heap_getattr(relation->rd_indextuple,
3160 Anum_pg_index_indpred,
3161 GetPgIndexDescriptor(),
3162 &isnull);
3163 Assert(!isnull);
3164 predString = TextDatumGetCString(predDatum);
3165 result = (List *) stringToNode(predString);
3166 pfree(predString);
3169 * Run the expression through const-simplification and canonicalization.
3170 * This is not just an optimization, but is necessary, because the planner
3171 * will be comparing it to similarly-processed qual clauses, and may fail
3172 * to detect valid matches without this. This must match the processing
3173 * done to qual clauses in preprocess_expression()! (We can skip the
3174 * stuff involving subqueries, however, since we don't allow any in index
3175 * predicates.)
3177 result = (List *) eval_const_expressions(NULL, (Node *) result);
3179 result = (List *) canonicalize_qual((Expr *) result);
3182 * Also mark any coercion format fields as "don't care", so that the
3183 * planner can match to both explicit and implicit coercions.
3185 set_coercionform_dontcare((Node *) result);
3187 /* Also convert to implicit-AND format */
3188 result = make_ands_implicit((Expr *) result);
3190 /* May as well fix opfuncids too */
3191 fix_opfuncids((Node *) result);
3193 /* Now save a copy of the completed tree in the relcache entry. */
3194 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3195 relation->rd_indpred = (List *) copyObject(result);
3196 MemoryContextSwitchTo(oldcxt);
3198 return result;
3202 * RelationGetIndexAttrBitmap -- get a bitmap of index attribute numbers
3204 * The result has a bit set for each attribute used anywhere in the index
3205 * definitions of all the indexes on this relation. (This includes not only
3206 * simple index keys, but attributes used in expressions and partial-index
3207 * predicates.)
3209 * Attribute numbers are offset by FirstLowInvalidHeapAttributeNumber so that
3210 * we can include system attributes (e.g., OID) in the bitmap representation.
3212 * The returned result is palloc'd in the caller's memory context and should
3213 * be bms_free'd when not needed anymore.
3215 Bitmapset *
3216 RelationGetIndexAttrBitmap(Relation relation)
3218 Bitmapset *indexattrs;
3219 List *indexoidlist;
3220 ListCell *l;
3221 MemoryContext oldcxt;
3223 /* Quick exit if we already computed the result. */
3224 if (relation->rd_indexattr != NULL)
3225 return bms_copy(relation->rd_indexattr);
3227 /* Fast path if definitely no indexes */
3228 if (!RelationGetForm(relation)->relhasindex)
3229 return NULL;
3232 * Get cached list of index OIDs
3234 indexoidlist = RelationGetIndexList(relation);
3236 /* Fall out if no indexes (but relhasindex was set) */
3237 if (indexoidlist == NIL)
3238 return NULL;
3241 * For each index, add referenced attributes to indexattrs.
3243 indexattrs = NULL;
3244 foreach(l, indexoidlist)
3246 Oid indexOid = lfirst_oid(l);
3247 Relation indexDesc;
3248 IndexInfo *indexInfo;
3249 int i;
3251 indexDesc = index_open(indexOid, AccessShareLock);
3253 /* Extract index key information from the index's pg_index row */
3254 indexInfo = BuildIndexInfo(indexDesc);
3256 /* Collect simple attribute references */
3257 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
3259 int attrnum = indexInfo->ii_KeyAttrNumbers[i];
3261 if (attrnum != 0)
3262 indexattrs = bms_add_member(indexattrs,
3263 attrnum - FirstLowInvalidHeapAttributeNumber);
3266 /* Collect all attributes used in expressions, too */
3267 pull_varattnos((Node *) indexInfo->ii_Expressions, &indexattrs);
3269 /* Collect all attributes in the index predicate, too */
3270 pull_varattnos((Node *) indexInfo->ii_Predicate, &indexattrs);
3272 index_close(indexDesc, AccessShareLock);
3275 list_free(indexoidlist);
3277 /* Now save a copy of the bitmap in the relcache entry. */
3278 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3279 relation->rd_indexattr = bms_copy(indexattrs);
3280 MemoryContextSwitchTo(oldcxt);
3282 /* We return our original working copy for caller to play with */
3283 return indexattrs;
3288 * load_relcache_init_file, write_relcache_init_file
3290 * In late 1992, we started regularly having databases with more than
3291 * a thousand classes in them. With this number of classes, it became
3292 * critical to do indexed lookups on the system catalogs.
3294 * Bootstrapping these lookups is very hard. We want to be able to
3295 * use an index on pg_attribute, for example, but in order to do so,
3296 * we must have read pg_attribute for the attributes in the index,
3297 * which implies that we need to use the index.
3299 * In order to get around the problem, we do the following:
3301 * + When the database system is initialized (at initdb time), we
3302 * don't use indexes. We do sequential scans.
3304 * + When the backend is started up in normal mode, we load an image
3305 * of the appropriate relation descriptors, in internal format,
3306 * from an initialization file in the data/base/... directory.
3308 * + If the initialization file isn't there, then we create the
3309 * relation descriptors using sequential scans and write 'em to
3310 * the initialization file for use by subsequent backends.
3312 * We could dispense with the initialization file and just build the
3313 * critical reldescs the hard way on every backend startup, but that
3314 * slows down backend startup noticeably.
3316 * We can in fact go further, and save more relcache entries than
3317 * just the ones that are absolutely critical; this allows us to speed
3318 * up backend startup by not having to build such entries the hard way.
3319 * Presently, all the catalog and index entries that are referred to
3320 * by catcaches are stored in the initialization file.
3322 * The same mechanism that detects when catcache and relcache entries
3323 * need to be invalidated (due to catalog updates) also arranges to
3324 * unlink the initialization file when its contents may be out of date.
3325 * The file will then be rebuilt during the next backend startup.
3329 * load_relcache_init_file -- attempt to load cache from the init file
3331 * If successful, return TRUE and set criticalRelcachesBuilt to true.
3332 * If not successful, return FALSE.
3334 * NOTE: we assume we are already switched into CacheMemoryContext.
3336 static bool
3337 load_relcache_init_file(void)
3339 FILE *fp;
3340 char initfilename[MAXPGPATH];
3341 Relation *rels;
3342 int relno,
3343 num_rels,
3344 max_rels,
3345 nailed_rels,
3346 nailed_indexes,
3347 magic;
3348 int i;
3350 snprintf(initfilename, sizeof(initfilename), "%s/%s",
3351 DatabasePath, RELCACHE_INIT_FILENAME);
3353 fp = AllocateFile(initfilename, PG_BINARY_R);
3354 if (fp == NULL)
3355 return false;
3358 * Read the index relcache entries from the file. Note we will not enter
3359 * any of them into the cache if the read fails partway through; this
3360 * helps to guard against broken init files.
3362 max_rels = 100;
3363 rels = (Relation *) palloc(max_rels * sizeof(Relation));
3364 num_rels = 0;
3365 nailed_rels = nailed_indexes = 0;
3366 initFileRelationIds = NIL;
3368 /* check for correct magic number (compatible version) */
3369 if (fread(&magic, 1, sizeof(magic), fp) != sizeof(magic))
3370 goto read_failed;
3371 if (magic != RELCACHE_INIT_FILEMAGIC)
3372 goto read_failed;
3374 for (relno = 0;; relno++)
3376 Size len;
3377 size_t nread;
3378 Relation rel;
3379 Form_pg_class relform;
3380 bool has_not_null;
3382 /* first read the relation descriptor length */
3383 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3385 if (nread == 0)
3386 break; /* end of file */
3387 goto read_failed;
3390 /* safety check for incompatible relcache layout */
3391 if (len != sizeof(RelationData))
3392 goto read_failed;
3394 /* allocate another relcache header */
3395 if (num_rels >= max_rels)
3397 max_rels *= 2;
3398 rels = (Relation *) repalloc(rels, max_rels * sizeof(Relation));
3401 rel = rels[num_rels++] = (Relation) palloc(len);
3403 /* then, read the Relation structure */
3404 if ((nread = fread(rel, 1, len, fp)) != len)
3405 goto read_failed;
3407 /* next read the relation tuple form */
3408 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3409 goto read_failed;
3411 relform = (Form_pg_class) palloc(len);
3412 if ((nread = fread(relform, 1, len, fp)) != len)
3413 goto read_failed;
3415 rel->rd_rel = relform;
3417 /* initialize attribute tuple forms */
3418 rel->rd_att = CreateTemplateTupleDesc(relform->relnatts,
3419 relform->relhasoids);
3420 rel->rd_att->tdrefcount = 1; /* mark as refcounted */
3422 rel->rd_att->tdtypeid = relform->reltype;
3423 rel->rd_att->tdtypmod = -1; /* unnecessary, but... */
3425 /* next read all the attribute tuple form data entries */
3426 has_not_null = false;
3427 for (i = 0; i < relform->relnatts; i++)
3429 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3430 goto read_failed;
3431 if (len != ATTRIBUTE_TUPLE_SIZE)
3432 goto read_failed;
3433 if ((nread = fread(rel->rd_att->attrs[i], 1, len, fp)) != len)
3434 goto read_failed;
3436 has_not_null |= rel->rd_att->attrs[i]->attnotnull;
3439 /* next read the access method specific field */
3440 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3441 goto read_failed;
3442 if (len > 0)
3444 rel->rd_options = palloc(len);
3445 if ((nread = fread(rel->rd_options, 1, len, fp)) != len)
3446 goto read_failed;
3447 if (len != VARSIZE(rel->rd_options))
3448 goto read_failed; /* sanity check */
3450 else
3452 rel->rd_options = NULL;
3455 /* mark not-null status */
3456 if (has_not_null)
3458 TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
3460 constr->has_not_null = true;
3461 rel->rd_att->constr = constr;
3464 /* If it's an index, there's more to do */
3465 if (rel->rd_rel->relkind == RELKIND_INDEX)
3467 Form_pg_am am;
3468 MemoryContext indexcxt;
3469 Oid *opfamily;
3470 Oid *opcintype;
3471 Oid *operator;
3472 RegProcedure *support;
3473 int nsupport;
3474 int16 *indoption;
3476 /* Count nailed indexes to ensure we have 'em all */
3477 if (rel->rd_isnailed)
3478 nailed_indexes++;
3480 /* next, read the pg_index tuple */
3481 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3482 goto read_failed;
3484 rel->rd_indextuple = (HeapTuple) palloc(len);
3485 if ((nread = fread(rel->rd_indextuple, 1, len, fp)) != len)
3486 goto read_failed;
3488 /* Fix up internal pointers in the tuple -- see heap_copytuple */
3489 rel->rd_indextuple->t_data = (HeapTupleHeader) ((char *) rel->rd_indextuple + HEAPTUPLESIZE);
3490 rel->rd_index = (Form_pg_index) GETSTRUCT(rel->rd_indextuple);
3492 /* next, read the access method tuple form */
3493 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3494 goto read_failed;
3496 am = (Form_pg_am) palloc(len);
3497 if ((nread = fread(am, 1, len, fp)) != len)
3498 goto read_failed;
3499 rel->rd_am = am;
3502 * prepare index info context --- parameters should match
3503 * RelationInitIndexAccessInfo
3505 indexcxt = AllocSetContextCreate(CacheMemoryContext,
3506 RelationGetRelationName(rel),
3507 ALLOCSET_SMALL_MINSIZE,
3508 ALLOCSET_SMALL_INITSIZE,
3509 ALLOCSET_SMALL_MAXSIZE);
3510 rel->rd_indexcxt = indexcxt;
3512 /* next, read the vector of opfamily OIDs */
3513 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3514 goto read_failed;
3516 opfamily = (Oid *) MemoryContextAlloc(indexcxt, len);
3517 if ((nread = fread(opfamily, 1, len, fp)) != len)
3518 goto read_failed;
3520 rel->rd_opfamily = opfamily;
3522 /* next, read the vector of opcintype OIDs */
3523 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3524 goto read_failed;
3526 opcintype = (Oid *) MemoryContextAlloc(indexcxt, len);
3527 if ((nread = fread(opcintype, 1, len, fp)) != len)
3528 goto read_failed;
3530 rel->rd_opcintype = opcintype;
3532 /* next, read the vector of operator OIDs */
3533 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3534 goto read_failed;
3536 operator = (Oid *) MemoryContextAlloc(indexcxt, len);
3537 if ((nread = fread(operator, 1, len, fp)) != len)
3538 goto read_failed;
3540 rel->rd_operator = operator;
3542 /* next, read the vector of support procedures */
3543 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3544 goto read_failed;
3545 support = (RegProcedure *) MemoryContextAlloc(indexcxt, len);
3546 if ((nread = fread(support, 1, len, fp)) != len)
3547 goto read_failed;
3549 rel->rd_support = support;
3551 /* finally, read the vector of indoption values */
3552 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
3553 goto read_failed;
3555 indoption = (int16 *) MemoryContextAlloc(indexcxt, len);
3556 if ((nread = fread(indoption, 1, len, fp)) != len)
3557 goto read_failed;
3559 rel->rd_indoption = indoption;
3561 /* set up zeroed fmgr-info vectors */
3562 rel->rd_aminfo = (RelationAmInfo *)
3563 MemoryContextAllocZero(indexcxt, sizeof(RelationAmInfo));
3564 nsupport = relform->relnatts * am->amsupport;
3565 rel->rd_supportinfo = (FmgrInfo *)
3566 MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
3568 else
3570 /* Count nailed rels to ensure we have 'em all */
3571 if (rel->rd_isnailed)
3572 nailed_rels++;
3574 Assert(rel->rd_index == NULL);
3575 Assert(rel->rd_indextuple == NULL);
3576 Assert(rel->rd_am == NULL);
3577 Assert(rel->rd_indexcxt == NULL);
3578 Assert(rel->rd_aminfo == NULL);
3579 Assert(rel->rd_opfamily == NULL);
3580 Assert(rel->rd_opcintype == NULL);
3581 Assert(rel->rd_operator == NULL);
3582 Assert(rel->rd_support == NULL);
3583 Assert(rel->rd_supportinfo == NULL);
3584 Assert(rel->rd_indoption == NULL);
3588 * Rules and triggers are not saved (mainly because the internal
3589 * format is complex and subject to change). They must be rebuilt if
3590 * needed by RelationCacheInitializePhase2. This is not expected to
3591 * be a big performance hit since few system catalogs have such. Ditto
3592 * for index expressions and predicates.
3594 rel->rd_rules = NULL;
3595 rel->rd_rulescxt = NULL;
3596 rel->trigdesc = NULL;
3597 rel->rd_indexprs = NIL;
3598 rel->rd_indpred = NIL;
3601 * Reset transient-state fields in the relcache entry
3603 rel->rd_smgr = NULL;
3604 rel->rd_targblock = InvalidBlockNumber;
3605 rel->rd_fsm_nblocks_cache = InvalidBlockNumber;
3606 if (rel->rd_isnailed)
3607 rel->rd_refcnt = 1;
3608 else
3609 rel->rd_refcnt = 0;
3610 rel->rd_indexvalid = 0;
3611 rel->rd_indexlist = NIL;
3612 rel->rd_indexattr = NULL;
3613 rel->rd_oidindex = InvalidOid;
3614 rel->rd_createSubid = InvalidSubTransactionId;
3615 rel->rd_newRelfilenodeSubid = InvalidSubTransactionId;
3616 rel->rd_amcache = NULL;
3617 MemSet(&rel->pgstat_info, 0, sizeof(rel->pgstat_info));
3620 * Recompute lock and physical addressing info. This is needed in
3621 * case the pg_internal.init file was copied from some other database
3622 * by CREATE DATABASE.
3624 RelationInitLockInfo(rel);
3625 RelationInitPhysicalAddr(rel);
3629 * We reached the end of the init file without apparent problem. Did we
3630 * get the right number of nailed items? (This is a useful crosscheck in
3631 * case the set of critical rels or indexes changes.)
3633 if (nailed_rels != NUM_CRITICAL_RELS ||
3634 nailed_indexes != NUM_CRITICAL_INDEXES)
3635 goto read_failed;
3638 * OK, all appears well.
3640 * Now insert all the new relcache entries into the cache.
3642 for (relno = 0; relno < num_rels; relno++)
3644 RelationCacheInsert(rels[relno]);
3645 /* also make a list of their OIDs, for RelationIdIsInInitFile */
3646 initFileRelationIds = lcons_oid(RelationGetRelid(rels[relno]),
3647 initFileRelationIds);
3650 pfree(rels);
3651 FreeFile(fp);
3653 criticalRelcachesBuilt = true;
3654 return true;
3657 * init file is broken, so do it the hard way. We don't bother trying to
3658 * free the clutter we just allocated; it's not in the relcache so it
3659 * won't hurt.
3661 read_failed:
3662 pfree(rels);
3663 FreeFile(fp);
3665 return false;
3669 * Write out a new initialization file with the current contents
3670 * of the relcache.
3672 static void
3673 write_relcache_init_file(void)
3675 FILE *fp;
3676 char tempfilename[MAXPGPATH];
3677 char finalfilename[MAXPGPATH];
3678 int magic;
3679 HASH_SEQ_STATUS status;
3680 RelIdCacheEnt *idhentry;
3681 MemoryContext oldcxt;
3682 int i;
3685 * We must write a temporary file and rename it into place. Otherwise,
3686 * another backend starting at about the same time might crash trying to
3687 * read the partially-complete file.
3689 snprintf(tempfilename, sizeof(tempfilename), "%s/%s.%d",
3690 DatabasePath, RELCACHE_INIT_FILENAME, MyProcPid);
3691 snprintf(finalfilename, sizeof(finalfilename), "%s/%s",
3692 DatabasePath, RELCACHE_INIT_FILENAME);
3694 unlink(tempfilename); /* in case it exists w/wrong permissions */
3696 fp = AllocateFile(tempfilename, PG_BINARY_W);
3697 if (fp == NULL)
3700 * We used to consider this a fatal error, but we might as well
3701 * continue with backend startup ...
3703 ereport(WARNING,
3704 (errcode_for_file_access(),
3705 errmsg("could not create relation-cache initialization file \"%s\": %m",
3706 tempfilename),
3707 errdetail("Continuing anyway, but there's something wrong.")));
3708 return;
3712 * Write a magic number to serve as a file version identifier. We can
3713 * change the magic number whenever the relcache layout changes.
3715 magic = RELCACHE_INIT_FILEMAGIC;
3716 if (fwrite(&magic, 1, sizeof(magic), fp) != sizeof(magic))
3717 elog(FATAL, "could not write init file");
3720 * Write all the reldescs (in no particular order).
3722 hash_seq_init(&status, RelationIdCache);
3724 initFileRelationIds = NIL;
3726 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3728 Relation rel = idhentry->reldesc;
3729 Form_pg_class relform = rel->rd_rel;
3731 /* first write the relcache entry proper */
3732 write_item(rel, sizeof(RelationData), fp);
3734 /* next write the relation tuple form */
3735 write_item(relform, CLASS_TUPLE_SIZE, fp);
3737 /* next, do all the attribute tuple form data entries */
3738 for (i = 0; i < relform->relnatts; i++)
3740 write_item(rel->rd_att->attrs[i], ATTRIBUTE_TUPLE_SIZE, fp);
3743 /* next, do the access method specific field */
3744 write_item(rel->rd_options,
3745 (rel->rd_options ? VARSIZE(rel->rd_options) : 0),
3746 fp);
3748 /* If it's an index, there's more to do */
3749 if (rel->rd_rel->relkind == RELKIND_INDEX)
3751 Form_pg_am am = rel->rd_am;
3753 /* write the pg_index tuple */
3754 /* we assume this was created by heap_copytuple! */
3755 write_item(rel->rd_indextuple,
3756 HEAPTUPLESIZE + rel->rd_indextuple->t_len,
3757 fp);
3759 /* next, write the access method tuple form */
3760 write_item(am, sizeof(FormData_pg_am), fp);
3762 /* next, write the vector of opfamily OIDs */
3763 write_item(rel->rd_opfamily,
3764 relform->relnatts * sizeof(Oid),
3765 fp);
3767 /* next, write the vector of opcintype OIDs */
3768 write_item(rel->rd_opcintype,
3769 relform->relnatts * sizeof(Oid),
3770 fp);
3772 /* next, write the vector of operator OIDs */
3773 write_item(rel->rd_operator,
3774 relform->relnatts * (am->amstrategies * sizeof(Oid)),
3775 fp);
3777 /* next, write the vector of support procedures */
3778 write_item(rel->rd_support,
3779 relform->relnatts * (am->amsupport * sizeof(RegProcedure)),
3780 fp);
3782 /* finally, write the vector of indoption values */
3783 write_item(rel->rd_indoption,
3784 relform->relnatts * sizeof(int16),
3785 fp);
3788 /* also make a list of their OIDs, for RelationIdIsInInitFile */
3789 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3790 initFileRelationIds = lcons_oid(RelationGetRelid(rel),
3791 initFileRelationIds);
3792 MemoryContextSwitchTo(oldcxt);
3795 if (FreeFile(fp))
3796 elog(FATAL, "could not write init file");
3799 * Now we have to check whether the data we've so painstakingly
3800 * accumulated is already obsolete due to someone else's just-committed
3801 * catalog changes. If so, we just delete the temp file and leave it to
3802 * the next backend to try again. (Our own relcache entries will be
3803 * updated by SI message processing, but we can't be sure whether what we
3804 * wrote out was up-to-date.)
3806 * This mustn't run concurrently with RelationCacheInitFileInvalidate, so
3807 * grab a serialization lock for the duration.
3809 LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
3811 /* Make sure we have seen all incoming SI messages */
3812 AcceptInvalidationMessages();
3815 * If we have received any SI relcache invals since backend start, assume
3816 * we may have written out-of-date data.
3818 if (relcacheInvalsReceived == 0L)
3821 * OK, rename the temp file to its final name, deleting any
3822 * previously-existing init file.
3824 * Note: a failure here is possible under Cygwin, if some other
3825 * backend is holding open an unlinked-but-not-yet-gone init file. So
3826 * treat this as a noncritical failure; just remove the useless temp
3827 * file on failure.
3829 if (rename(tempfilename, finalfilename) < 0)
3830 unlink(tempfilename);
3832 else
3834 /* Delete the already-obsolete temp file */
3835 unlink(tempfilename);
3838 LWLockRelease(RelCacheInitLock);
3841 /* write a chunk of data preceded by its length */
3842 static void
3843 write_item(const void *data, Size len, FILE *fp)
3845 if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len))
3846 elog(FATAL, "could not write init file");
3847 if (fwrite(data, 1, len, fp) != len)
3848 elog(FATAL, "could not write init file");
3852 * Detect whether a given relation (identified by OID) is one of the ones
3853 * we store in the init file.
3855 * Note that we effectively assume that all backends running in a database
3856 * would choose to store the same set of relations in the init file;
3857 * otherwise there are cases where we'd fail to detect the need for an init
3858 * file invalidation. This does not seem likely to be a problem in practice.
3860 bool
3861 RelationIdIsInInitFile(Oid relationId)
3863 return list_member_oid(initFileRelationIds, relationId);
3867 * Invalidate (remove) the init file during commit of a transaction that
3868 * changed one or more of the relation cache entries that are kept in the
3869 * init file.
3871 * We actually need to remove the init file twice: once just before sending
3872 * the SI messages that include relcache inval for such relations, and once
3873 * just after sending them. The unlink before ensures that a backend that's
3874 * currently starting cannot read the now-obsolete init file and then miss
3875 * the SI messages that will force it to update its relcache entries. (This
3876 * works because the backend startup sequence gets into the PGPROC array before
3877 * trying to load the init file.) The unlink after is to synchronize with a
3878 * backend that may currently be trying to write an init file based on data
3879 * that we've just rendered invalid. Such a backend will see the SI messages,
3880 * but we can't leave the init file sitting around to fool later backends.
3882 * Ignore any failure to unlink the file, since it might not be there if
3883 * no backend has been started since the last removal.
3885 void
3886 RelationCacheInitFileInvalidate(bool beforeSend)
3888 char initfilename[MAXPGPATH];
3890 snprintf(initfilename, sizeof(initfilename), "%s/%s",
3891 DatabasePath, RELCACHE_INIT_FILENAME);
3893 if (beforeSend)
3895 /* no interlock needed here */
3896 unlink(initfilename);
3898 else
3901 * We need to interlock this against write_relcache_init_file, to
3902 * guard against possibility that someone renames a new-but-
3903 * already-obsolete init file into place just after we unlink. With
3904 * the interlock, it's certain that write_relcache_init_file will
3905 * notice our SI inval message before renaming into place, or else
3906 * that we will execute second and successfully unlink the file.
3908 LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
3909 unlink(initfilename);
3910 LWLockRelease(RelCacheInitLock);
3915 * Remove the init file for a given database during postmaster startup.
3917 * We used to keep the init file across restarts, but that is unsafe in PITR
3918 * scenarios, and even in simple crash-recovery cases there are windows for
3919 * the init file to become out-of-sync with the database. So now we just
3920 * remove it during startup and expect the first backend launch to rebuild it.
3921 * Of course, this has to happen in each database of the cluster. For
3922 * simplicity this is driven by flatfiles.c, which has to scan pg_database
3923 * anyway.
3925 void
3926 RelationCacheInitFileRemove(const char *dbPath)
3928 char initfilename[MAXPGPATH];
3930 snprintf(initfilename, sizeof(initfilename), "%s/%s",
3931 dbPath, RELCACHE_INIT_FILENAME);
3932 unlink(initfilename);
3933 /* ignore any error, since it might not be there at all */