1 /*-------------------------------------------------------------------------
4 * POSTGRES relation descriptor cache code
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/utils/cache/relcache.c,v 1.173 2002/09/02 01:05:06 tgl Exp $
13 *-------------------------------------------------------------------------
17 * RelationCacheInitialize - initialize relcache
18 * RelationCacheInitializePhase2 - finish initializing relcache
19 * RelationIdGetRelation - get a reldesc by relation id
20 * RelationSysNameGetRelation - get a reldesc by system rel name
21 * RelationIdCacheGetRelation - get a cached reldesc by relid
22 * RelationClose - close an open relation
25 * The following code contains many undocumented hacks. Please be
30 #include <sys/types.h>
36 #include "access/genam.h"
37 #include "access/heapam.h"
38 #include "access/istrat.h"
39 #include "catalog/catalog.h"
40 #include "catalog/catname.h"
41 #include "catalog/indexing.h"
42 #include "catalog/namespace.h"
43 #include "catalog/pg_amop.h"
44 #include "catalog/pg_amproc.h"
45 #include "catalog/pg_attrdef.h"
46 #include "catalog/pg_attribute.h"
47 #include "catalog/pg_constraint.h"
48 #include "catalog/pg_index.h"
49 #include "catalog/pg_namespace.h"
50 #include "catalog/pg_opclass.h"
51 #include "catalog/pg_proc.h"
52 #include "catalog/pg_rewrite.h"
53 #include "catalog/pg_type.h"
54 #include "commands/trigger.h"
55 #include "miscadmin.h"
56 #include "storage/smgr.h"
57 #include "utils/builtins.h"
58 #include "utils/catcache.h"
59 #include "utils/fmgroids.h"
60 #include "utils/inval.h"
61 #include "utils/lsyscache.h"
62 #include "utils/relcache.h"
63 #include "utils/syscache.h"
67 * name of relcache init file, used to speed up backend startup
69 #define RELCACHE_INIT_FILENAME "pg_internal.init"
72 * hardcoded tuple descriptors. see include/catalog/pg_attribute.h
74 static FormData_pg_attribute Desc_pg_class[Natts_pg_class] = {Schema_pg_class};
75 static FormData_pg_attribute Desc_pg_attribute[Natts_pg_attribute] = {Schema_pg_attribute};
76 static FormData_pg_attribute Desc_pg_proc[Natts_pg_proc] = {Schema_pg_proc};
77 static FormData_pg_attribute Desc_pg_type[Natts_pg_type] = {Schema_pg_type};
80 * Hash tables that index the relation cache
82 * Relations are looked up two ways, by OID and by name,
83 * thus there are two hash tables for referencing them.
85 * The OID index covers all relcache entries. The name index
86 * covers *only* system relations (only those in PG_CATALOG_NAMESPACE).
88 static HTAB *RelationIdCache;
89 static HTAB *RelationSysNameCache;
92 * Bufmgr uses RelFileNode for lookup. Actually, I would like to do
93 * not pass Relation to bufmgr & beyond at all and keep some cache
94 * in smgr, but no time to do it right way now. -- vadim 10/22/2000
96 static HTAB *RelationNodeCache;
99 * This flag is false until we have prepared the critical relcache entries
100 * that are needed to do indexscans on the tables read by relcache building.
102 bool criticalRelcachesBuilt = false;
105 * This flag is set if we discover that we need to write a new relcache
106 * cache file at the end of startup.
108 static bool needNewCacheFile = false;
111 * This counter counts relcache inval events received since backend startup
112 * (but only for rels that are actually in cache). Presently, we use it only
113 * to detect whether data about to be written by write_relcache_init_file()
114 * might already be obsolete.
116 static long relcacheInvalsReceived = 0L;
119 * This list remembers the OIDs of the relations cached in the relcache
122 static List *initFileRelationIds = NIL;
125 * RelationBuildDescInfo exists so code can be shared
126 * between RelationIdGetRelation() and RelationSysNameGetRelation()
128 typedef struct RelationBuildDescInfo
130 int infotype; /* lookup by id or by name */
132 #define INFO_RELNAME 2
135 Oid info_id; /* relation object id */
136 char *info_name; /* system relation name */
138 } RelationBuildDescInfo;
140 typedef struct relidcacheent
146 typedef struct relnamecacheent
152 typedef struct relnodecacheent
159 * macros to manipulate the lookup hashtables
161 #define RelationCacheInsert(RELATION) \
163 RelIdCacheEnt *idhentry; RelNodeCacheEnt *nodentry; bool found; \
164 idhentry = (RelIdCacheEnt*)hash_search(RelationIdCache, \
165 (void *) &(RELATION->rd_id), \
168 if (idhentry == NULL) \
169 elog(ERROR, "out of memory for relation descriptor cache"); \
170 /* used to give notice if found -- now just keep quiet */ \
171 idhentry->reldesc = RELATION; \
172 nodentry = (RelNodeCacheEnt*)hash_search(RelationNodeCache, \
173 (void *) &(RELATION->rd_node), \
176 if (nodentry == NULL) \
177 elog(ERROR, "out of memory for relation descriptor cache"); \
178 /* used to give notice if found -- now just keep quiet */ \
179 nodentry->reldesc = RELATION; \
180 if (IsSystemNamespace(RelationGetNamespace(RELATION))) \
182 char *relname = RelationGetRelationName(RELATION); \
183 RelNameCacheEnt *namehentry; \
184 namehentry = (RelNameCacheEnt*)hash_search(RelationSysNameCache, \
188 if (namehentry == NULL) \
189 elog(ERROR, "out of memory for relation descriptor cache"); \
190 /* used to give notice if found -- now just keep quiet */ \
191 namehentry->reldesc = RELATION; \
195 #define RelationIdCacheLookup(ID, RELATION) \
197 RelIdCacheEnt *hentry; \
198 hentry = (RelIdCacheEnt*)hash_search(RelationIdCache, \
199 (void *)&(ID), HASH_FIND,NULL); \
201 RELATION = hentry->reldesc; \
206 #define RelationSysNameCacheLookup(NAME, RELATION) \
208 RelNameCacheEnt *hentry; \
209 hentry = (RelNameCacheEnt*)hash_search(RelationSysNameCache, \
210 (void *) (NAME), HASH_FIND,NULL); \
212 RELATION = hentry->reldesc; \
217 #define RelationNodeCacheLookup(NODE, RELATION) \
219 RelNodeCacheEnt *hentry; \
220 hentry = (RelNodeCacheEnt*)hash_search(RelationNodeCache, \
221 (void *)&(NODE), HASH_FIND,NULL); \
223 RELATION = hentry->reldesc; \
228 #define RelationCacheDelete(RELATION) \
230 RelIdCacheEnt *idhentry; RelNodeCacheEnt *nodentry; \
231 idhentry = (RelIdCacheEnt*)hash_search(RelationIdCache, \
232 (void *)&(RELATION->rd_id), \
233 HASH_REMOVE, NULL); \
234 if (idhentry == NULL) \
235 elog(WARNING, "trying to delete a rd_id reldesc that does not exist."); \
236 nodentry = (RelNodeCacheEnt*)hash_search(RelationNodeCache, \
237 (void *)&(RELATION->rd_node), \
238 HASH_REMOVE, NULL); \
239 if (nodentry == NULL) \
240 elog(WARNING, "trying to delete a rd_node reldesc that does not exist."); \
241 if (IsSystemNamespace(RelationGetNamespace(RELATION))) \
243 char *relname = RelationGetRelationName(RELATION); \
244 RelNameCacheEnt *namehentry; \
245 namehentry = (RelNameCacheEnt*)hash_search(RelationSysNameCache, \
247 HASH_REMOVE, NULL); \
248 if (namehentry == NULL) \
249 elog(WARNING, "trying to delete a relname reldesc that does not exist."); \
255 * Special cache for opclass-related information
257 typedef struct opclasscacheent
259 Oid opclassoid; /* lookup key: OID of opclass */
260 bool valid; /* set TRUE after successful fill-in */
261 StrategyNumber numStrats; /* max # of strategies (from pg_am) */
262 StrategyNumber numSupport; /* max # of support procs (from pg_am) */
263 Oid *operatorOids; /* strategy operators' OIDs */
264 RegProcedure *operatorProcs; /* strategy operators' procs */
265 RegProcedure *supportProcs; /* support procs */
268 static HTAB *OpClassCache = NULL;
271 /* non-export function prototypes */
273 static void RelationClearRelation(Relation relation, bool rebuild);
275 #ifdef ENABLE_REINDEX_NAILED_RELATIONS
276 static void RelationReloadClassinfo(Relation relation);
277 #endif /* ENABLE_REINDEX_NAILED_RELATIONS */
278 static void RelationFlushRelation(Relation relation);
279 static Relation RelationSysNameCacheGetRelation(const char *relationName);
280 static bool load_relcache_init_file(void);
281 static void write_relcache_init_file(void);
283 static void formrdesc(const char *relationName, int natts,
284 FormData_pg_attribute *att);
286 static HeapTuple ScanPgRelation(RelationBuildDescInfo buildinfo);
287 static Relation AllocateRelationDesc(Relation relation, Form_pg_class relp);
288 static void RelationBuildTupleDesc(RelationBuildDescInfo buildinfo,
290 static Relation RelationBuildDesc(RelationBuildDescInfo buildinfo,
291 Relation oldrelation);
292 static void AttrDefaultFetch(Relation relation);
293 static void CheckConstraintFetch(Relation relation);
294 static List *insert_ordered_oid(List *list, Oid datum);
295 static void IndexSupportInitialize(Form_pg_index iform,
296 IndexStrategy indexStrategy,
298 RegProcedure *indexSupport,
299 StrategyNumber maxStrategyNumber,
300 StrategyNumber maxSupportNumber,
301 AttrNumber maxAttributeNumber);
302 static OpClassCacheEnt *LookupOpclassInfo(Oid operatorClassOid,
303 StrategyNumber numStrats,
304 StrategyNumber numSupport);
310 * this is used by RelationBuildDesc to find a pg_class
311 * tuple matching either a relation name or a relation id
312 * as specified in buildinfo.
314 * NB: the returned tuple has been copied into palloc'd storage
315 * and must eventually be freed with heap_freetuple.
318 ScanPgRelation(RelationBuildDescInfo buildinfo)
320 HeapTuple pg_class_tuple;
321 Relation pg_class_desc;
322 const char *indexRelname;
323 SysScanDesc pg_class_scan;
330 switch (buildinfo.infotype)
333 ScanKeyEntryInitialize(&key[0], 0,
334 ObjectIdAttributeNumber,
336 ObjectIdGetDatum(buildinfo.i.info_id));
338 indexRelname = ClassOidIndex;
342 ScanKeyEntryInitialize(&key[0], 0,
343 Anum_pg_class_relname,
345 NameGetDatum(buildinfo.i.info_name));
346 ScanKeyEntryInitialize(&key[1], 0,
347 Anum_pg_class_relnamespace,
349 ObjectIdGetDatum(PG_CATALOG_NAMESPACE));
351 indexRelname = ClassNameNspIndex;
355 elog(ERROR, "ScanPgRelation: bad buildinfo");
356 return NULL; /* keep compiler quiet */
360 * Open pg_class and fetch a tuple. Force heap scan if we haven't
361 * yet built the critical relcache entries (this includes initdb
362 * and startup without a pg_internal.init file).
364 pg_class_desc = heap_openr(RelationRelationName, AccessShareLock);
365 pg_class_scan = systable_beginscan(pg_class_desc, indexRelname,
366 criticalRelcachesBuilt,
370 pg_class_tuple = systable_getnext(pg_class_scan);
373 * Must copy tuple before releasing buffer.
375 if (HeapTupleIsValid(pg_class_tuple))
376 pg_class_tuple = heap_copytuple(pg_class_tuple);
379 systable_endscan(pg_class_scan);
380 heap_close(pg_class_desc, AccessShareLock);
382 return pg_class_tuple;
386 * AllocateRelationDesc
388 * This is used to allocate memory for a new relation descriptor
389 * and initialize the rd_rel field.
391 * If 'relation' is NULL, allocate a new RelationData object.
392 * If not, reuse the given object (that path is taken only when
393 * we have to rebuild a relcache entry during RelationClearRelation).
396 AllocateRelationDesc(Relation relation, Form_pg_class relp)
398 MemoryContext oldcxt;
399 Form_pg_class relationForm;
401 /* Relcache entries must live in CacheMemoryContext */
402 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
405 * allocate space for new relation descriptor, if needed
407 if (relation == NULL)
408 relation = (Relation) palloc(sizeof(RelationData));
411 * clear all fields of reldesc
413 MemSet((char *) relation, 0, sizeof(RelationData));
414 relation->rd_targblock = InvalidBlockNumber;
416 /* make sure relation is marked as having no open file yet */
417 relation->rd_fd = -1;
420 * Copy the relation tuple form
422 * We only allocate space for the fixed fields, ie, CLASS_TUPLE_SIZE.
423 * relacl is NOT stored in the relcache --- there'd be little point in
424 * it, since we don't copy the tuple's nullvalues bitmap and hence
425 * wouldn't know if the value is valid ... bottom line is that relacl
426 * *cannot* be retrieved from the relcache. Get it from the syscache
429 relationForm = (Form_pg_class) palloc(CLASS_TUPLE_SIZE);
431 memcpy((char *) relationForm, (char *) relp, CLASS_TUPLE_SIZE);
433 /* initialize relation tuple form */
434 relation->rd_rel = relationForm;
436 /* and allocate attribute tuple form storage */
437 relation->rd_att = CreateTemplateTupleDesc(relationForm->relnatts,
438 relationForm->relhasoids);
440 MemoryContextSwitchTo(oldcxt);
446 * RelationBuildTupleDesc
448 * Form the relation's tuple descriptor from information in
449 * the pg_attribute, pg_attrdef & pg_constraint system catalogs.
452 RelationBuildTupleDesc(RelationBuildDescInfo buildinfo,
455 HeapTuple pg_attribute_tuple;
456 Relation pg_attribute_desc;
457 SysScanDesc pg_attribute_scan;
461 AttrDefault *attrdef = NULL;
464 relation->rd_att->tdhasoid = RelationGetForm(relation)->relhasoids;
466 constr = (TupleConstr *) MemoryContextAlloc(CacheMemoryContext,
467 sizeof(TupleConstr));
468 constr->has_not_null = false;
471 * Form a scan key that selects only user attributes (attnum > 0).
472 * (Eliminating system attribute rows at the index level is lots
473 * faster than fetching them.)
475 ScanKeyEntryInitialize(&skey[0], 0,
476 Anum_pg_attribute_attrelid,
478 ObjectIdGetDatum(RelationGetRelid(relation)));
479 ScanKeyEntryInitialize(&skey[1], 0,
480 Anum_pg_attribute_attnum,
485 * Open pg_attribute and begin a scan. Force heap scan if we haven't
486 * yet built the critical relcache entries (this includes initdb
487 * and startup without a pg_internal.init file).
489 pg_attribute_desc = heap_openr(AttributeRelationName, AccessShareLock);
490 pg_attribute_scan = systable_beginscan(pg_attribute_desc,
491 AttributeRelidNumIndex,
492 criticalRelcachesBuilt,
497 * add attribute data to relation->rd_att
499 need = relation->rd_rel->relnatts;
501 while (HeapTupleIsValid(pg_attribute_tuple = systable_getnext(pg_attribute_scan)))
503 Form_pg_attribute attp;
505 attp = (Form_pg_attribute) GETSTRUCT(pg_attribute_tuple);
507 if (attp->attnum <= 0 ||
508 attp->attnum > relation->rd_rel->relnatts)
509 elog(ERROR, "Bogus attribute number %d for %s",
510 attp->attnum, RelationGetRelationName(relation));
512 relation->rd_att->attrs[attp->attnum - 1] =
513 (Form_pg_attribute) MemoryContextAlloc(CacheMemoryContext,
514 ATTRIBUTE_TUPLE_SIZE);
516 memcpy((char *) (relation->rd_att->attrs[attp->attnum - 1]),
518 ATTRIBUTE_TUPLE_SIZE);
520 /* Update constraint/default info */
521 if (attp->attnotnull)
522 constr->has_not_null = true;
528 attrdef = (AttrDefault *)
529 MemoryContextAlloc(CacheMemoryContext,
530 relation->rd_rel->relnatts *
531 sizeof(AttrDefault));
533 relation->rd_rel->relnatts * sizeof(AttrDefault));
535 attrdef[ndef].adnum = attp->attnum;
536 attrdef[ndef].adbin = NULL;
545 * end the scan and close the attribute relation
547 systable_endscan(pg_attribute_scan);
548 heap_close(pg_attribute_desc, AccessShareLock);
551 elog(ERROR, "catalog is missing %d attribute(s) for relid %u",
552 need, RelationGetRelid(relation));
555 * The attcacheoff values we read from pg_attribute should all be -1
556 * ("unknown"). Verify this if assert checking is on. They will be
557 * computed when and if needed during tuple access.
559 #ifdef USE_ASSERT_CHECKING
563 for (i = 0; i < relation->rd_rel->relnatts; i++)
564 Assert(relation->rd_att->attrs[i]->attcacheoff == -1);
569 * However, we can easily set the attcacheoff value for the first
570 * attribute: it must be zero. This eliminates the need for special
571 * cases for attnum=1 that used to exist in fastgetattr() and
574 relation->rd_att->attrs[0]->attcacheoff = 0;
577 * Set up constraint/default info
579 if (constr->has_not_null || ndef > 0 || relation->rd_rel->relchecks)
581 relation->rd_att->constr = constr;
583 if (ndef > 0) /* DEFAULTs */
585 if (ndef < relation->rd_rel->relnatts)
586 constr->defval = (AttrDefault *)
587 repalloc(attrdef, ndef * sizeof(AttrDefault));
589 constr->defval = attrdef;
590 constr->num_defval = ndef;
591 AttrDefaultFetch(relation);
594 constr->num_defval = 0;
596 if (relation->rd_rel->relchecks > 0) /* CHECKs */
598 constr->num_check = relation->rd_rel->relchecks;
599 constr->check = (ConstrCheck *)
600 MemoryContextAlloc(CacheMemoryContext,
601 constr->num_check * sizeof(ConstrCheck));
602 MemSet(constr->check, 0, constr->num_check * sizeof(ConstrCheck));
603 CheckConstraintFetch(relation);
606 constr->num_check = 0;
611 relation->rd_att->constr = NULL;
616 * RelationBuildRuleLock
618 * Form the relation's rewrite rules from information in
619 * the pg_rewrite system catalog.
621 * Note: The rule parsetrees are potentially very complex node structures.
622 * To allow these trees to be freed when the relcache entry is flushed,
623 * we make a private memory context to hold the RuleLock information for
624 * each relcache entry that has associated rules. The context is used
625 * just for rule info, not for any other subsidiary data of the relcache
626 * entry, because that keeps the update logic in RelationClearRelation()
627 * manageable. The other subsidiary data structures are simple enough
628 * to be easy to free explicitly, anyway.
631 RelationBuildRuleLock(Relation relation)
633 MemoryContext rulescxt;
634 MemoryContext oldcxt;
635 HeapTuple rewrite_tuple;
636 Relation rewrite_desc;
637 TupleDesc rewrite_tupdesc;
638 SysScanDesc rewrite_scan;
646 * Make the private context. Parameters are set on the assumption
647 * that it'll probably not contain much data.
649 rulescxt = AllocSetContextCreate(CacheMemoryContext,
650 RelationGetRelationName(relation),
654 relation->rd_rulescxt = rulescxt;
657 * allocate an array to hold the rewrite rules (the array is extended if
661 rules = (RewriteRule **)
662 MemoryContextAlloc(rulescxt, sizeof(RewriteRule *) * maxlocks);
668 ScanKeyEntryInitialize(&key, 0,
669 Anum_pg_rewrite_ev_class,
671 ObjectIdGetDatum(RelationGetRelid(relation)));
674 * open pg_rewrite and begin a scan
676 * Note: since we scan the rules using RewriteRelRulenameIndex,
677 * we will be reading the rules in name order, except possibly
678 * during emergency-recovery operations (ie, IsIgnoringSystemIndexes).
679 * This in turn ensures that rules will be fired in name order.
681 rewrite_desc = heap_openr(RewriteRelationName, AccessShareLock);
682 rewrite_tupdesc = RelationGetDescr(rewrite_desc);
683 rewrite_scan = systable_beginscan(rewrite_desc,
684 RewriteRelRulenameIndex,
688 while (HeapTupleIsValid(rewrite_tuple = systable_getnext(rewrite_scan)))
690 Form_pg_rewrite rewrite_form = (Form_pg_rewrite) GETSTRUCT(rewrite_tuple);
694 char *ruleaction_str;
695 char *rule_evqual_str;
698 rule = (RewriteRule *) MemoryContextAlloc(rulescxt,
699 sizeof(RewriteRule));
701 rule->ruleId = HeapTupleGetOid(rewrite_tuple);
703 rule->event = rewrite_form->ev_type - '0';
704 rule->attrno = rewrite_form->ev_attr;
705 rule->isInstead = rewrite_form->is_instead;
707 /* Must use heap_getattr to fetch ev_qual and ev_action */
709 ruleaction = heap_getattr(rewrite_tuple,
710 Anum_pg_rewrite_ev_action,
714 ruleaction_str = DatumGetCString(DirectFunctionCall1(textout,
716 oldcxt = MemoryContextSwitchTo(rulescxt);
717 rule->actions = (List *) stringToNode(ruleaction_str);
718 MemoryContextSwitchTo(oldcxt);
719 pfree(ruleaction_str);
721 rule_evqual = heap_getattr(rewrite_tuple,
722 Anum_pg_rewrite_ev_qual,
726 rule_evqual_str = DatumGetCString(DirectFunctionCall1(textout,
728 oldcxt = MemoryContextSwitchTo(rulescxt);
729 rule->qual = (Node *) stringToNode(rule_evqual_str);
730 MemoryContextSwitchTo(oldcxt);
731 pfree(rule_evqual_str);
733 if (numlocks >= maxlocks)
736 rules = (RewriteRule **)
737 repalloc(rules, sizeof(RewriteRule *) * maxlocks);
739 rules[numlocks++] = rule;
743 * end the scan and close the attribute relation
745 systable_endscan(rewrite_scan);
746 heap_close(rewrite_desc, AccessShareLock);
749 * form a RuleLock and insert into relation
751 rulelock = (RuleLock *) MemoryContextAlloc(rulescxt, sizeof(RuleLock));
752 rulelock->numLocks = numlocks;
753 rulelock->rules = rules;
755 relation->rd_rules = rulelock;
761 * Determine whether two RuleLocks are equivalent
763 * Probably this should be in the rules code someplace...
766 equalRuleLocks(RuleLock *rlock1, RuleLock *rlock2)
771 * As of 7.3 we assume the rule ordering is repeatable,
772 * because RelationBuildRuleLock should read 'em in a
773 * consistent order. So just compare corresponding slots.
779 if (rlock1->numLocks != rlock2->numLocks)
781 for (i = 0; i < rlock1->numLocks; i++)
783 RewriteRule *rule1 = rlock1->rules[i];
784 RewriteRule *rule2 = rlock2->rules[i];
786 if (rule1->ruleId != rule2->ruleId)
788 if (rule1->event != rule2->event)
790 if (rule1->attrno != rule2->attrno)
792 if (rule1->isInstead != rule2->isInstead)
794 if (!equal(rule1->qual, rule2->qual))
796 if (!equal(rule1->actions, rule2->actions))
800 else if (rlock2 != NULL)
806 /* ----------------------------------
809 * Build a relation descriptor --- either a new one, or by
810 * recycling the given old relation object. The latter case
811 * supports rebuilding a relcache entry without invalidating
813 * --------------------------------
816 RelationBuildDesc(RelationBuildDescInfo buildinfo,
817 Relation oldrelation)
821 HeapTuple pg_class_tuple;
823 MemoryContext oldcxt;
826 * find the tuple in pg_class corresponding to the given relation id
828 pg_class_tuple = ScanPgRelation(buildinfo);
831 * if no such tuple exists, return NULL
833 if (!HeapTupleIsValid(pg_class_tuple))
837 * get information from the pg_class_tuple
839 relid = HeapTupleGetOid(pg_class_tuple);
840 relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
843 * allocate storage for the relation descriptor, and copy
844 * pg_class_tuple to relation->rd_rel.
846 relation = AllocateRelationDesc(oldrelation, relp);
849 * now we can free the memory allocated for pg_class_tuple
851 heap_freetuple(pg_class_tuple);
854 * initialize the relation's relation id (relation->rd_id)
856 RelationGetRelid(relation) = relid;
859 * initialize relation->rd_refcnt
861 RelationSetReferenceCount(relation, 1);
864 * normal relations are not nailed into the cache; nor can a pre-existing
865 * relation be new. It could be temp though. (Actually, it could be new
866 * too, but it's okay to forget that fact if forced to flush the entry.)
868 relation->rd_isnailed = false;
869 relation->rd_isnew = false;
870 relation->rd_istemp = isTempNamespace(relation->rd_rel->relnamespace);
873 * initialize the tuple descriptor (relation->rd_att).
875 RelationBuildTupleDesc(buildinfo, relation);
878 * Fetch rules and triggers that affect this relation
880 if (relation->rd_rel->relhasrules)
881 RelationBuildRuleLock(relation);
884 relation->rd_rules = NULL;
885 relation->rd_rulescxt = NULL;
888 if (relation->rd_rel->reltriggers > 0)
889 RelationBuildTriggers(relation);
891 relation->trigdesc = NULL;
894 * if it's an index, initialize index-related information
896 if (OidIsValid(relation->rd_rel->relam))
897 RelationInitIndexAccessInfo(relation);
900 * initialize the relation lock manager information
902 RelationInitLockInfo(relation); /* see lmgr.c */
904 if (relation->rd_rel->relisshared)
905 relation->rd_node.tblNode = InvalidOid;
907 relation->rd_node.tblNode = MyDatabaseId;
908 relation->rd_node.relNode = relation->rd_rel->relfilenode;
910 /* make sure relation is marked as having no open file yet */
911 relation->rd_fd = -1;
914 * Insert newly created relation into relcache hash tables.
916 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
917 RelationCacheInsert(relation);
918 MemoryContextSwitchTo(oldcxt);
921 * If it's a temp rel, RelationGetNumberOfBlocks will assume that
922 * rd_nblocks is correct. Must forcibly update the block count when
923 * creating the relcache entry. But if we are doing a rebuild, don't
924 * do this yet; leave it to RelationClearRelation to do at the end.
925 * (Otherwise, an elog in RelationUpdateNumberOfBlocks would leave us
926 * with inconsistent relcache state.)
928 if (relation->rd_istemp && oldrelation == NULL)
929 RelationUpdateNumberOfBlocks(relation);
935 * Initialize index-access-method support data for an index relation
938 RelationInitIndexAccessInfo(Relation relation)
944 MemoryContext indexcxt;
945 IndexStrategy strategy;
947 RegProcedure *support;
948 FmgrInfo *supportinfo;
954 * Make a copy of the pg_index entry for the index. Note that this
955 * is a variable-length tuple.
957 tuple = SearchSysCache(INDEXRELID,
958 ObjectIdGetDatum(RelationGetRelid(relation)),
960 if (!HeapTupleIsValid(tuple))
961 elog(ERROR, "RelationInitIndexAccessInfo: no pg_index entry for index %u",
962 RelationGetRelid(relation));
963 iformsize = tuple->t_len - tuple->t_data->t_hoff;
964 iform = (Form_pg_index) MemoryContextAlloc(CacheMemoryContext, iformsize);
965 memcpy(iform, GETSTRUCT(tuple), iformsize);
966 ReleaseSysCache(tuple);
967 relation->rd_index = iform;
970 * Make a copy of the pg_am entry for the index's access method
972 tuple = SearchSysCache(AMOID,
973 ObjectIdGetDatum(relation->rd_rel->relam),
975 if (!HeapTupleIsValid(tuple))
976 elog(ERROR, "RelationInitIndexAccessInfo: cache lookup failed for AM %u",
977 relation->rd_rel->relam);
978 aform = (Form_pg_am) MemoryContextAlloc(CacheMemoryContext, sizeof *aform);
979 memcpy(aform, GETSTRUCT(tuple), sizeof *aform);
980 ReleaseSysCache(tuple);
981 relation->rd_am = aform;
983 natts = relation->rd_rel->relnatts;
984 amstrategies = aform->amstrategies;
985 amsupport = aform->amsupport;
988 * Make the private context to hold index access info. The reason we
989 * need a context, and not just a couple of pallocs, is so that we
990 * won't leak any subsidiary info attached to fmgr lookup records.
992 * Context parameters are set on the assumption that it'll probably not
995 indexcxt = AllocSetContextCreate(CacheMemoryContext,
996 RelationGetRelationName(relation),
1000 relation->rd_indexcxt = indexcxt;
1003 * Allocate arrays to hold data
1005 if (amstrategies > 0)
1007 int noperators = natts * amstrategies;
1010 stratSize = AttributeNumberGetIndexStrategySize(natts, amstrategies);
1011 strategy = (IndexStrategy) MemoryContextAlloc(indexcxt, stratSize);
1012 MemSet(strategy, 0, stratSize);
1014 MemoryContextAlloc(indexcxt, noperators * sizeof(Oid));
1015 MemSet(operator, 0, noperators * sizeof(Oid));
1025 int nsupport = natts * amsupport;
1027 support = (RegProcedure *)
1028 MemoryContextAlloc(indexcxt, nsupport * sizeof(RegProcedure));
1029 MemSet(support, 0, nsupport * sizeof(RegProcedure));
1030 supportinfo = (FmgrInfo *)
1031 MemoryContextAlloc(indexcxt, nsupport * sizeof(FmgrInfo));
1032 MemSet(supportinfo, 0, nsupport * sizeof(FmgrInfo));
1040 relation->rd_istrat = strategy;
1041 relation->rd_operator = operator;
1042 relation->rd_support = support;
1043 relation->rd_supportinfo = supportinfo;
1046 * Fill the strategy map and the support RegProcedure arrays.
1047 * (supportinfo is left as zeroes, and is filled on-the-fly when used)
1049 IndexSupportInitialize(iform,
1050 strategy, operator, support,
1051 amstrategies, amsupport, natts);
1055 * IndexSupportInitialize
1056 * Initializes an index strategy and associated support procedures,
1057 * given the index's pg_index tuple.
1059 * Data is returned into *indexStrategy, *indexOperator, and *indexSupport,
1060 * all of which are objects allocated by the caller.
1062 * The caller also passes maxStrategyNumber, maxSupportNumber, and
1063 * maxAttributeNumber, since these indicate the size of the arrays
1064 * it has allocated --- but in practice these numbers must always match
1065 * those obtainable from the system catalog entries for the index and
1069 IndexSupportInitialize(Form_pg_index iform,
1070 IndexStrategy indexStrategy,
1072 RegProcedure *indexSupport,
1073 StrategyNumber maxStrategyNumber,
1074 StrategyNumber maxSupportNumber,
1075 AttrNumber maxAttributeNumber)
1079 maxStrategyNumber = AMStrategies(maxStrategyNumber);
1082 * XXX note that the following assumes the INDEX tuple is well formed
1083 * and that the *key and *class are 0 terminated.
1085 for (attIndex = 0; attIndex < maxAttributeNumber; attIndex++)
1087 OpClassCacheEnt *opcentry;
1089 if (iform->indkey[attIndex] == InvalidAttrNumber ||
1090 !OidIsValid(iform->indclass[attIndex]))
1091 elog(ERROR, "IndexSupportInitialize: bogus pg_index tuple");
1093 /* look up the info for this opclass, using a cache */
1094 opcentry = LookupOpclassInfo(iform->indclass[attIndex],
1098 /* load the strategy information for the index operators */
1099 if (maxStrategyNumber > 0)
1103 StrategyNumber strategy;
1105 map = IndexStrategyGetStrategyMap(indexStrategy,
1108 opers = &indexOperator[attIndex * maxStrategyNumber];
1110 for (strategy = 0; strategy < maxStrategyNumber; strategy++)
1114 mapentry = StrategyMapGetScanKeyEntry(map, strategy + 1);
1115 if (RegProcedureIsValid(opcentry->operatorProcs[strategy]))
1117 MemSet(mapentry, 0, sizeof(*mapentry));
1118 mapentry->sk_flags = 0;
1119 mapentry->sk_procedure = opcentry->operatorProcs[strategy];
1121 * Mark mapentry->sk_func invalid, until and unless
1122 * someone sets it up.
1124 mapentry->sk_func.fn_oid = InvalidOid;
1127 ScanKeyEntrySetIllegal(mapentry);
1128 opers[strategy] = opcentry->operatorOids[strategy];
1132 /* if support routines exist for this access method, load them */
1133 if (maxSupportNumber > 0)
1135 RegProcedure *procs;
1136 StrategyNumber support;
1138 procs = &indexSupport[attIndex * maxSupportNumber];
1140 for (support = 0; support < maxSupportNumber; ++support)
1141 procs[support] = opcentry->supportProcs[support];
1149 * This routine maintains a per-opclass cache of the information needed
1150 * by IndexSupportInitialize(). This is more efficient than relying on
1151 * the catalog cache, because we can load all the info about a particular
1152 * opclass in a single indexscan of pg_amproc or pg_amop.
1154 * The information from pg_am about expected range of strategy and support
1155 * numbers is passed in, rather than being looked up, mainly because the
1156 * caller will have it already.
1158 * XXX There isn't any provision for flushing the cache. However, there
1159 * isn't any provision for flushing relcache entries when opclass info
1160 * changes, either :-(
1162 static OpClassCacheEnt *
1163 LookupOpclassInfo(Oid operatorClassOid,
1164 StrategyNumber numStrats,
1165 StrategyNumber numSupport)
1167 OpClassCacheEnt *opcentry;
1169 Relation pg_amop_desc;
1170 Relation pg_amproc_desc;
1171 SysScanDesc pg_amop_scan;
1172 SysScanDesc pg_amproc_scan;
1177 if (OpClassCache == NULL)
1179 /* First time through: initialize the opclass cache */
1182 if (!CacheMemoryContext)
1183 CreateCacheMemoryContext();
1185 MemSet(&ctl, 0, sizeof(ctl));
1186 ctl.keysize = sizeof(Oid);
1187 ctl.entrysize = sizeof(OpClassCacheEnt);
1188 ctl.hash = tag_hash;
1189 OpClassCache = hash_create("Operator class cache", 64,
1190 &ctl, HASH_ELEM | HASH_FUNCTION);
1193 opcentry = (OpClassCacheEnt *) hash_search(OpClassCache,
1194 (void *) &operatorClassOid,
1195 HASH_ENTER, &found);
1196 if (opcentry == NULL)
1197 elog(ERROR, "out of memory for operator class cache");
1199 if (found && opcentry->valid)
1201 /* Already made an entry for it */
1202 Assert(numStrats == opcentry->numStrats);
1203 Assert(numSupport == opcentry->numSupport);
1207 /* Need to fill in new entry */
1208 opcentry->valid = false; /* until known OK */
1209 opcentry->numStrats = numStrats;
1210 opcentry->numSupport = numSupport;
1214 opcentry->operatorOids = (Oid *)
1215 MemoryContextAlloc(CacheMemoryContext,
1216 numStrats * sizeof(Oid));
1217 MemSet(opcentry->operatorOids, 0, numStrats * sizeof(Oid));
1218 opcentry->operatorProcs = (RegProcedure *)
1219 MemoryContextAlloc(CacheMemoryContext,
1220 numStrats * sizeof(RegProcedure));
1221 MemSet(opcentry->operatorProcs, 0, numStrats * sizeof(RegProcedure));
1225 opcentry->operatorOids = NULL;
1226 opcentry->operatorProcs = NULL;
1231 opcentry->supportProcs = (RegProcedure *)
1232 MemoryContextAlloc(CacheMemoryContext,
1233 numSupport * sizeof(RegProcedure));
1234 MemSet(opcentry->supportProcs, 0, numSupport * sizeof(RegProcedure));
1237 opcentry->supportProcs = NULL;
1240 * To avoid infinite recursion during startup, force a heap scan if
1241 * we're looking up info for the opclasses used by the indexes we
1242 * would like to reference here.
1244 indexOK = criticalRelcachesBuilt ||
1245 (operatorClassOid != OID_BTREE_OPS_OID &&
1246 operatorClassOid != INT2_BTREE_OPS_OID);
1249 * Scan pg_amop to obtain operators for the opclass
1253 ScanKeyEntryInitialize(&key, 0,
1254 Anum_pg_amop_amopclaid,
1256 ObjectIdGetDatum(operatorClassOid));
1257 pg_amop_desc = heap_openr(AccessMethodOperatorRelationName,
1259 pg_amop_scan = systable_beginscan(pg_amop_desc,
1260 AccessMethodStrategyIndex,
1265 while (HeapTupleIsValid(htup = systable_getnext(pg_amop_scan)))
1267 Form_pg_amop amopform = (Form_pg_amop) GETSTRUCT(htup);
1269 if (amopform->amopstrategy <= 0 ||
1270 (StrategyNumber) amopform->amopstrategy > numStrats)
1271 elog(ERROR, "Bogus amopstrategy number %d for opclass %u",
1272 amopform->amopstrategy, operatorClassOid);
1273 opcentry->operatorOids[amopform->amopstrategy - 1] =
1275 opcentry->operatorProcs[amopform->amopstrategy - 1] =
1276 get_opcode(amopform->amopopr);
1279 systable_endscan(pg_amop_scan);
1280 heap_close(pg_amop_desc, AccessShareLock);
1284 * Scan pg_amproc to obtain support procs for the opclass
1288 ScanKeyEntryInitialize(&key, 0,
1289 Anum_pg_amproc_amopclaid,
1291 ObjectIdGetDatum(operatorClassOid));
1292 pg_amproc_desc = heap_openr(AccessMethodProcedureRelationName,
1294 pg_amproc_scan = systable_beginscan(pg_amproc_desc,
1295 AccessMethodProcedureIndex,
1300 while (HeapTupleIsValid(htup = systable_getnext(pg_amproc_scan)))
1302 Form_pg_amproc amprocform = (Form_pg_amproc) GETSTRUCT(htup);
1304 if (amprocform->amprocnum <= 0 ||
1305 (StrategyNumber) amprocform->amprocnum > numSupport)
1306 elog(ERROR, "Bogus amproc number %d for opclass %u",
1307 amprocform->amprocnum, operatorClassOid);
1309 opcentry->supportProcs[amprocform->amprocnum - 1] =
1313 systable_endscan(pg_amproc_scan);
1314 heap_close(pg_amproc_desc, AccessShareLock);
1317 opcentry->valid = true;
1325 * This is a special cut-down version of RelationBuildDesc()
1326 * used by RelationCacheInitialize() in initializing the relcache.
1327 * The relation descriptor is built just from the supplied parameters,
1328 * without actually looking at any system table entries. We cheat
1329 * quite a lot since we only need to work for a few basic system
1332 * formrdesc is currently used for: pg_class, pg_attribute, pg_proc,
1333 * and pg_type (see RelationCacheInitialize).
1335 * Note that these catalogs can't have constraints, default values,
1336 * rules, or triggers, since we don't cope with any of that.
1338 * NOTE: we assume we are already switched into CacheMemoryContext.
1341 formrdesc(const char *relationName,
1343 FormData_pg_attribute *att)
1349 * allocate new relation desc
1351 relation = (Relation) palloc(sizeof(RelationData));
1354 * clear all fields of reldesc
1356 MemSet((char *) relation, 0, sizeof(RelationData));
1357 relation->rd_targblock = InvalidBlockNumber;
1359 /* make sure relation is marked as having no open file yet */
1360 relation->rd_fd = -1;
1363 * initialize reference count
1365 RelationSetReferenceCount(relation, 1);
1368 * all entries built with this routine are nailed-in-cache; none are
1369 * for new or temp relations.
1371 relation->rd_isnailed = true;
1372 relation->rd_isnew = false;
1373 relation->rd_istemp = false;
1376 * initialize relation tuple form
1378 * The data we insert here is pretty incomplete/bogus, but it'll serve to
1379 * get us launched. RelationCacheInitializePhase2() will read the
1380 * real data from pg_class and replace what we've done here.
1382 relation->rd_rel = (Form_pg_class) palloc(CLASS_TUPLE_SIZE);
1383 MemSet(relation->rd_rel, 0, CLASS_TUPLE_SIZE);
1385 namestrcpy(&relation->rd_rel->relname, relationName);
1386 relation->rd_rel->relnamespace = PG_CATALOG_NAMESPACE;
1389 * It's important to distinguish between shared and non-shared
1390 * relations, even at bootstrap time, to make sure we know where they
1391 * are stored. At present, all relations that formrdesc is used for
1394 relation->rd_rel->relisshared = false;
1396 relation->rd_rel->relpages = 1;
1397 relation->rd_rel->reltuples = 1;
1398 relation->rd_rel->relkind = RELKIND_RELATION;
1399 relation->rd_rel->relhasoids = true;
1400 relation->rd_rel->relnatts = (int16) natts;
1403 * initialize attribute tuple form
1405 * Unlike the case with the relation tuple, this data had better be
1406 * right because it will never be replaced. The input values must be
1407 * correctly defined by macros in src/include/catalog/ headers.
1409 relation->rd_att = CreateTemplateTupleDesc(natts,
1410 relation->rd_rel->relhasoids);
1413 * initialize tuple desc info
1415 for (i = 0; i < natts; i++)
1417 relation->rd_att->attrs[i] = (Form_pg_attribute) palloc(ATTRIBUTE_TUPLE_SIZE);
1418 memcpy((char *) relation->rd_att->attrs[i],
1420 ATTRIBUTE_TUPLE_SIZE);
1421 /* make sure attcacheoff is valid */
1422 relation->rd_att->attrs[i]->attcacheoff = -1;
1425 /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
1426 relation->rd_att->attrs[0]->attcacheoff = 0;
1429 * initialize relation id from info in att array (my, this is ugly)
1431 RelationGetRelid(relation) = relation->rd_att->attrs[0]->attrelid;
1434 * initialize the relation's lock manager and RelFileNode information
1436 RelationInitLockInfo(relation); /* see lmgr.c */
1438 if (relation->rd_rel->relisshared)
1439 relation->rd_node.tblNode = InvalidOid;
1441 relation->rd_node.tblNode = MyDatabaseId;
1442 relation->rd_node.relNode =
1443 relation->rd_rel->relfilenode = RelationGetRelid(relation);
1446 * initialize the rel-has-index flag, using hardwired knowledge
1448 relation->rd_rel->relhasindex = false;
1450 /* In bootstrap mode, we have no indexes */
1451 if (!IsBootstrapProcessingMode())
1453 /* Otherwise, all the rels formrdesc is used for have indexes */
1454 relation->rd_rel->relhasindex = true;
1458 * add new reldesc to relcache
1460 RelationCacheInsert(relation);
1464 /* ----------------------------------------------------------------
1465 * Relation Descriptor Lookup Interface
1466 * ----------------------------------------------------------------
1470 * RelationIdCacheGetRelation
1472 * Lookup an existing reldesc by OID.
1474 * Only try to get the reldesc by looking in the cache,
1475 * do not go to the disk.
1477 * NB: relation ref count is incremented if successful.
1478 * Caller should eventually decrement count. (Usually,
1479 * that happens by calling RelationClose().)
1482 RelationIdCacheGetRelation(Oid relationId)
1486 RelationIdCacheLookup(relationId, rd);
1488 if (RelationIsValid(rd))
1489 RelationIncrementReferenceCount(rd);
1495 * RelationSysNameCacheGetRelation
1497 * As above, but lookup by name; only works for system catalogs.
1500 RelationSysNameCacheGetRelation(const char *relationName)
1506 * make sure that the name key used for hash lookup is properly
1509 namestrcpy(&name, relationName);
1510 RelationSysNameCacheLookup(NameStr(name), rd);
1512 if (RelationIsValid(rd))
1513 RelationIncrementReferenceCount(rd);
1519 RelationNodeCacheGetRelation(RelFileNode rnode)
1523 RelationNodeCacheLookup(rnode, rd);
1525 if (RelationIsValid(rd))
1526 RelationIncrementReferenceCount(rd);
1532 * RelationIdGetRelation
1534 * Lookup a reldesc by OID; make one if not already in cache.
1536 * NB: relation ref count is incremented, or set to 1 if new entry.
1537 * Caller should eventually decrement count. (Usually,
1538 * that happens by calling RelationClose().)
1541 RelationIdGetRelation(Oid relationId)
1544 RelationBuildDescInfo buildinfo;
1547 * first try and get a reldesc from the cache
1549 rd = RelationIdCacheGetRelation(relationId);
1550 if (RelationIsValid(rd))
1554 * no reldesc in the cache, so have RelationBuildDesc() build one and
1557 buildinfo.infotype = INFO_RELID;
1558 buildinfo.i.info_id = relationId;
1560 rd = RelationBuildDesc(buildinfo, NULL);
1565 * RelationSysNameGetRelation
1567 * As above, but lookup by name; only works for system catalogs.
1570 RelationSysNameGetRelation(const char *relationName)
1573 RelationBuildDescInfo buildinfo;
1576 * first try and get a reldesc from the cache
1578 rd = RelationSysNameCacheGetRelation(relationName);
1579 if (RelationIsValid(rd))
1583 * no reldesc in the cache, so have RelationBuildDesc() build one and
1586 buildinfo.infotype = INFO_RELNAME;
1587 buildinfo.i.info_name = (char *) relationName;
1589 rd = RelationBuildDesc(buildinfo, NULL);
1593 /* ----------------------------------------------------------------
1594 * cache invalidation support routines
1595 * ----------------------------------------------------------------
1599 * RelationClose - close an open relation
1601 * Actually, we just decrement the refcount.
1603 * NOTE: if compiled with -DRELCACHE_FORCE_RELEASE then relcache entries
1604 * will be freed as soon as their refcount goes to zero. In combination
1605 * with aset.c's CLOBBER_FREED_MEMORY option, this provides a good test
1606 * to catch references to already-released relcache entries. It slows
1607 * things down quite a bit, however.
1610 RelationClose(Relation relation)
1612 /* Note: no locking manipulations needed */
1613 RelationDecrementReferenceCount(relation);
1615 #ifdef RELCACHE_FORCE_RELEASE
1616 if (RelationHasReferenceCountZero(relation) &&
1617 !relation->rd_isnew)
1618 RelationClearRelation(relation, false);
1622 #ifdef ENABLE_REINDEX_NAILED_RELATIONS
1624 * RelationReloadClassinfo
1626 * This function is especially for nailed relations.
1627 * relhasindex/relfilenode could be changed even for
1631 RelationReloadClassinfo(Relation relation)
1633 RelationBuildDescInfo buildinfo;
1634 HeapTuple pg_class_tuple;
1637 if (!relation->rd_rel)
1639 buildinfo.infotype = INFO_RELID;
1640 buildinfo.i.info_id = relation->rd_id;
1641 pg_class_tuple = ScanPgRelation(buildinfo);
1642 if (!HeapTupleIsValid(pg_class_tuple))
1644 elog(ERROR, "RelationReloadClassinfo system relation id=%d doesn't exist", relation->rd_id);
1647 RelationCacheDelete(relation);
1648 relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
1649 memcpy((char *) relation->rd_rel, (char *) relp, CLASS_TUPLE_SIZE);
1650 relation->rd_node.relNode = relp->relfilenode;
1651 RelationCacheInsert(relation);
1652 heap_freetuple(pg_class_tuple);
1656 #endif /* ENABLE_REINDEX_NAILED_RELATIONS */
1659 * RelationClearRelation
1661 * Physically blow away a relation cache entry, or reset it and rebuild
1662 * it from scratch (that is, from catalog entries). The latter path is
1663 * usually used when we are notified of a change to an open relation
1664 * (one with refcount > 0). However, this routine just does whichever
1665 * it's told to do; callers must determine which they want.
1668 RelationClearRelation(Relation relation, bool rebuild)
1670 MemoryContext oldcxt;
1673 * Make sure smgr and lower levels close the relation's files, if they
1674 * weren't closed already. If the relation is not getting deleted,
1675 * the next smgr access should reopen the files automatically. This
1676 * ensures that the low-level file access state is updated after, say,
1677 * a vacuum truncation.
1679 if (relation->rd_fd >= 0)
1681 smgrclose(DEFAULT_SMGR, relation);
1682 relation->rd_fd = -1;
1686 * Never, never ever blow away a nailed-in system relation, because
1687 * we'd be unable to recover.
1689 if (relation->rd_isnailed)
1691 #ifdef ENABLE_REINDEX_NAILED_RELATIONS
1692 RelationReloadClassinfo(relation);
1693 #endif /* ENABLE_REINDEX_NAILED_RELATIONS */
1698 * Remove relation from hash tables
1700 * Note: we might be reinserting it momentarily, but we must not have it
1701 * visible in the hash tables until it's valid again, so don't try to
1702 * optimize this away...
1704 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
1705 RelationCacheDelete(relation);
1706 MemoryContextSwitchTo(oldcxt);
1708 /* Clear out catcache's entries for this relation */
1709 CatalogCacheFlushRelation(RelationGetRelid(relation));
1712 * Free all the subsidiary data structures of the relcache entry. We
1713 * cannot free rd_att if we are trying to rebuild the entry, however,
1714 * because pointers to it may be cached in various places. The trigger
1715 * manager might also have pointers into the trigdesc, and the rule
1716 * manager might have pointers into the rewrite rules. So to begin
1717 * with, we can only get rid of these fields:
1719 if (relation->rd_index)
1720 pfree(relation->rd_index);
1721 if (relation->rd_am)
1722 pfree(relation->rd_am);
1723 if (relation->rd_rel)
1724 pfree(relation->rd_rel);
1725 freeList(relation->rd_indexlist);
1726 if (relation->rd_indexcxt)
1727 MemoryContextDelete(relation->rd_indexcxt);
1730 * If we're really done with the relcache entry, blow it away. But if
1731 * someone is still using it, reconstruct the whole deal without
1732 * moving the physical RelationData record (so that the someone's
1733 * pointer is still valid).
1737 /* ok to zap remaining substructure */
1738 FreeTupleDesc(relation->rd_att);
1739 if (relation->rd_rulescxt)
1740 MemoryContextDelete(relation->rd_rulescxt);
1741 FreeTriggerDesc(relation->trigdesc);
1747 * When rebuilding an open relcache entry, must preserve ref count
1748 * and rd_isnew flag. Also attempt to preserve the tupledesc,
1749 * rewrite rules, and trigger substructures in place.
1751 int old_refcnt = relation->rd_refcnt;
1752 bool old_isnew = relation->rd_isnew;
1753 TupleDesc old_att = relation->rd_att;
1754 RuleLock *old_rules = relation->rd_rules;
1755 MemoryContext old_rulescxt = relation->rd_rulescxt;
1756 TriggerDesc *old_trigdesc = relation->trigdesc;
1757 RelationBuildDescInfo buildinfo;
1759 buildinfo.infotype = INFO_RELID;
1760 buildinfo.i.info_id = RelationGetRelid(relation);
1762 if (RelationBuildDesc(buildinfo, relation) != relation)
1764 /* Should only get here if relation was deleted */
1765 FreeTupleDesc(old_att);
1767 MemoryContextDelete(old_rulescxt);
1768 FreeTriggerDesc(old_trigdesc);
1770 elog(ERROR, "RelationClearRelation: relation %u deleted while still in use",
1771 buildinfo.i.info_id);
1773 RelationSetReferenceCount(relation, old_refcnt);
1774 relation->rd_isnew = old_isnew;
1775 if (equalTupleDescs(old_att, relation->rd_att))
1777 FreeTupleDesc(relation->rd_att);
1778 relation->rd_att = old_att;
1781 FreeTupleDesc(old_att);
1782 if (equalRuleLocks(old_rules, relation->rd_rules))
1784 if (relation->rd_rulescxt)
1785 MemoryContextDelete(relation->rd_rulescxt);
1786 relation->rd_rules = old_rules;
1787 relation->rd_rulescxt = old_rulescxt;
1792 MemoryContextDelete(old_rulescxt);
1794 if (equalTriggerDescs(old_trigdesc, relation->trigdesc))
1796 FreeTriggerDesc(relation->trigdesc);
1797 relation->trigdesc = old_trigdesc;
1800 FreeTriggerDesc(old_trigdesc);
1803 * Update rd_nblocks. This is kind of expensive, but I think we must
1804 * do it in case relation has been truncated... we definitely must
1805 * do it if the rel is new or temp, since RelationGetNumberOfBlocks
1806 * will subsequently assume that the block count is correct.
1808 RelationUpdateNumberOfBlocks(relation);
1813 * RelationFlushRelation
1815 * Rebuild the relation if it is open (refcount > 0), else blow it away.
1818 RelationFlushRelation(Relation relation)
1822 if (relation->rd_isnew)
1825 * New relcache entries are always rebuilt, not flushed; else we'd
1826 * forget the "new" status of the relation, which is a useful
1827 * optimization to have.
1834 * Pre-existing rels can be dropped from the relcache if not open.
1836 rebuild = !RelationHasReferenceCountZero(relation);
1839 RelationClearRelation(relation, rebuild);
1843 * RelationForgetRelation - unconditionally remove a relcache entry
1845 * External interface for destroying a relcache entry when we
1846 * drop the relation.
1849 RelationForgetRelation(Oid rid)
1853 RelationIdCacheLookup(rid, relation);
1855 if (!PointerIsValid(relation))
1856 return; /* not in cache, nothing to do */
1858 if (!RelationHasReferenceCountZero(relation))
1859 elog(ERROR, "RelationForgetRelation: relation %u is still open", rid);
1861 /* Unconditionally destroy the relcache entry */
1862 RelationClearRelation(relation, false);
1866 * RelationIdInvalidateRelationCacheByRelationId
1868 * This routine is invoked for SI cache flush messages.
1870 * We used to skip local relations, on the grounds that they could
1871 * not be targets of cross-backend SI update messages; but it seems
1872 * safer to process them, so that our *own* SI update messages will
1873 * have the same effects during CommandCounterIncrement for both
1874 * local and nonlocal relations.
1877 RelationIdInvalidateRelationCacheByRelationId(Oid relationId)
1881 RelationIdCacheLookup(relationId, relation);
1883 if (PointerIsValid(relation))
1885 relcacheInvalsReceived++;
1886 RelationFlushRelation(relation);
1891 * RelationCacheInvalidate
1892 * Blow away cached relation descriptors that have zero reference counts,
1893 * and rebuild those with positive reference counts.
1895 * This is currently used only to recover from SI message buffer overflow,
1896 * so we do not touch new-in-transaction relations; they cannot be targets
1897 * of cross-backend SI updates (and our own updates now go through a
1898 * separate linked list that isn't limited by the SI message buffer size).
1900 * We do this in two phases: the first pass deletes deletable items, and
1901 * the second one rebuilds the rebuildable items. This is essential for
1902 * safety, because hash_seq_search only copes with concurrent deletion of
1903 * the element it is currently visiting. If a second SI overflow were to
1904 * occur while we are walking the table, resulting in recursive entry to
1905 * this routine, we could crash because the inner invocation blows away
1906 * the entry next to be visited by the outer scan. But this way is OK,
1907 * because (a) during the first pass we won't process any more SI messages,
1908 * so hash_seq_search will complete safely; (b) during the second pass we
1909 * only hold onto pointers to nondeletable entries.
1912 RelationCacheInvalidate(void)
1914 HASH_SEQ_STATUS status;
1915 RelIdCacheEnt *idhentry;
1917 List *rebuildList = NIL;
1921 hash_seq_init(&status, RelationIdCache);
1923 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
1925 relation = idhentry->reldesc;
1927 /* Ignore new relations, since they are never SI targets */
1928 if (relation->rd_isnew)
1931 relcacheInvalsReceived++;
1933 if (RelationHasReferenceCountZero(relation))
1935 /* Delete this entry immediately */
1936 RelationClearRelation(relation, false);
1940 /* Add entry to list of stuff to rebuild in second pass */
1941 rebuildList = lcons(relation, rebuildList);
1945 /* Phase 2: rebuild the items found to need rebuild in phase 1 */
1946 foreach(l, rebuildList)
1948 relation = (Relation) lfirst(l);
1949 RelationClearRelation(relation, true);
1951 freeList(rebuildList);
1955 * AtEOXact_RelationCache
1957 * Clean up the relcache at transaction commit or abort.
1960 AtEOXact_RelationCache(bool commit)
1962 HASH_SEQ_STATUS status;
1963 RelIdCacheEnt *idhentry;
1965 hash_seq_init(&status, RelationIdCache);
1967 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
1969 Relation relation = idhentry->reldesc;
1970 int expected_refcnt;
1973 * Is it a relation created in the current transaction?
1975 * During commit, reset the flag to false, since we are now out of the
1976 * creating transaction. During abort, simply delete the relcache
1977 * entry --- it isn't interesting any longer. (NOTE: if we have
1978 * forgotten the isnew state of a new relation due to a forced cache
1979 * flush, the entry will get deleted anyway by shared-cache-inval
1980 * processing of the aborted pg_class insertion.)
1982 if (relation->rd_isnew)
1985 relation->rd_isnew = false;
1988 RelationClearRelation(relation, false);
1994 * During transaction abort, we must also reset relcache entry ref
1995 * counts to their normal not-in-a-transaction state. A ref count may
1996 * be too high because some routine was exited by elog() between
1997 * incrementing and decrementing the count.
1999 * During commit, we should not have to do this, but it's still useful
2000 * to check that the counts are correct to catch missed relcache
2003 * In bootstrap mode, do NOT reset the refcnt nor complain that it's
2004 * nonzero --- the bootstrap code expects relations to stay open
2005 * across start/commit transaction calls. (That seems bogus, but it's
2006 * not worth fixing.)
2008 expected_refcnt = relation->rd_isnailed ? 1 : 0;
2012 if (relation->rd_refcnt != expected_refcnt &&
2013 !IsBootstrapProcessingMode())
2015 elog(WARNING, "Relcache reference leak: relation \"%s\" has refcnt %d instead of %d",
2016 RelationGetRelationName(relation),
2017 relation->rd_refcnt, expected_refcnt);
2018 RelationSetReferenceCount(relation, expected_refcnt);
2023 /* abort case, just reset it quietly */
2024 RelationSetReferenceCount(relation, expected_refcnt);
2030 * RelationBuildLocalRelation
2031 * Build a relcache entry for an about-to-be-created relation,
2032 * and enter it into the relcache.
2035 RelationBuildLocalRelation(const char *relname,
2038 Oid relid, Oid dbid,
2043 MemoryContext oldcxt;
2044 int natts = tupDesc->natts;
2047 AssertArg(natts > 0);
2050 * switch to the cache context to create the relcache entry.
2052 if (!CacheMemoryContext)
2053 CreateCacheMemoryContext();
2055 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2058 * allocate a new relation descriptor and fill in basic state fields.
2060 rel = (Relation) palloc(sizeof(RelationData));
2061 MemSet((char *) rel, 0, sizeof(RelationData));
2063 rel->rd_targblock = InvalidBlockNumber;
2065 /* make sure relation is marked as having no open file yet */
2068 RelationSetReferenceCount(rel, 1);
2070 /* it's being created in this transaction */
2071 rel->rd_isnew = true;
2073 /* is it a temporary relation? */
2074 rel->rd_istemp = isTempNamespace(relnamespace);
2077 * nail the reldesc if this is a bootstrap create reln and we may need
2078 * it in the cache later on in the bootstrap process so we don't ever
2079 * want it kicked out. e.g. pg_attribute!!!
2082 rel->rd_isnailed = true;
2085 * create a new tuple descriptor from the one passed in. We do this
2086 * partly to copy it into the cache context, and partly because the
2087 * new relation can't have any defaults or constraints yet; they
2088 * have to be added in later steps, because they require additions
2089 * to multiple system catalogs. We can copy attnotnull constraints
2092 rel->rd_att = CreateTupleDescCopy(tupDesc);
2093 for (i = 0; i < natts; i++)
2094 rel->rd_att->attrs[i]->attnotnull = tupDesc->attrs[i]->attnotnull;
2097 * initialize relation tuple form (caller may add/override data later)
2099 rel->rd_rel = (Form_pg_class) palloc(CLASS_TUPLE_SIZE);
2100 MemSet((char *) rel->rd_rel, 0, CLASS_TUPLE_SIZE);
2102 namestrcpy(&rel->rd_rel->relname, relname);
2103 rel->rd_rel->relnamespace = relnamespace;
2105 rel->rd_rel->relkind = RELKIND_UNCATALOGED;
2106 rel->rd_rel->relhasoids = rel->rd_att->tdhasoid;
2107 rel->rd_rel->relnatts = natts;
2108 rel->rd_rel->reltype = InvalidOid;
2111 * Insert relation physical and logical identifiers (OIDs) into the
2114 rel->rd_rel->relisshared = (dbid == InvalidOid);
2116 RelationGetRelid(rel) = relid;
2118 for (i = 0; i < natts; i++)
2119 rel->rd_att->attrs[i]->attrelid = relid;
2121 rel->rd_node = rnode;
2122 rel->rd_rel->relfilenode = rnode.relNode;
2124 RelationInitLockInfo(rel); /* see lmgr.c */
2127 * Okay to insert into the relcache hash tables.
2129 RelationCacheInsert(rel);
2132 * done building relcache entry.
2134 MemoryContextSwitchTo(oldcxt);
2140 * RelationCacheInitialize
2142 * This initializes the relation descriptor cache. At the time
2143 * that this is invoked, we can't do database access yet (mainly
2144 * because the transaction subsystem is not up), so we can't get
2145 * "real" info. However it's okay to read the pg_internal.init
2146 * cache file, if one is available. Otherwise we make phony
2147 * entries for the minimum set of nailed-in-cache relations.
2150 #define INITRELCACHESIZE 400
2153 RelationCacheInitialize(void)
2155 MemoryContext oldcxt;
2159 * switch to cache memory context
2161 if (!CacheMemoryContext)
2162 CreateCacheMemoryContext();
2164 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2167 * create hashtables that index the relcache
2169 MemSet(&ctl, 0, sizeof(ctl));
2170 ctl.keysize = sizeof(NameData);
2171 ctl.entrysize = sizeof(RelNameCacheEnt);
2172 RelationSysNameCache = hash_create("Relcache by name", INITRELCACHESIZE,
2175 ctl.keysize = sizeof(Oid);
2176 ctl.entrysize = sizeof(RelIdCacheEnt);
2177 ctl.hash = tag_hash;
2178 RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
2179 &ctl, HASH_ELEM | HASH_FUNCTION);
2181 ctl.keysize = sizeof(RelFileNode);
2182 ctl.entrysize = sizeof(RelNodeCacheEnt);
2183 ctl.hash = tag_hash;
2184 RelationNodeCache = hash_create("Relcache by rnode", INITRELCACHESIZE,
2185 &ctl, HASH_ELEM | HASH_FUNCTION);
2188 * Try to load the relcache cache file. If successful, we're done
2189 * for now. Otherwise, initialize the cache with pre-made descriptors
2190 * for the critical "nailed-in" system catalogs.
2192 if (IsBootstrapProcessingMode() ||
2193 ! load_relcache_init_file())
2195 formrdesc(RelationRelationName,
2196 Natts_pg_class, Desc_pg_class);
2197 formrdesc(AttributeRelationName,
2198 Natts_pg_attribute, Desc_pg_attribute);
2199 formrdesc(ProcedureRelationName,
2200 Natts_pg_proc, Desc_pg_proc);
2201 formrdesc(TypeRelationName,
2202 Natts_pg_type, Desc_pg_type);
2204 #define NUM_CRITICAL_RELS 4 /* fix if you change list above */
2207 MemoryContextSwitchTo(oldcxt);
2211 * RelationCacheInitializePhase2
2213 * This is called as soon as the catcache and transaction system
2214 * are functional. At this point we can actually read data from
2215 * the system catalogs. Update the relcache entries made during
2216 * RelationCacheInitialize, and make sure we have entries for the
2217 * critical system indexes.
2220 RelationCacheInitializePhase2(void)
2222 HASH_SEQ_STATUS status;
2223 RelIdCacheEnt *idhentry;
2225 if (IsBootstrapProcessingMode())
2229 * If we didn't get the critical system indexes loaded into relcache,
2230 * do so now. These are critical because the catcache depends on them
2231 * for catcache fetches that are done during relcache load. Thus, we
2232 * have an infinite-recursion problem. We can break the recursion
2233 * by doing heapscans instead of indexscans at certain key spots.
2234 * To avoid hobbling performance, we only want to do that until we
2235 * have the critical indexes loaded into relcache. Thus, the flag
2236 * criticalRelcachesBuilt is used to decide whether to do heapscan
2237 * or indexscan at the key spots, and we set it true after we've loaded
2238 * the critical indexes.
2240 * The critical indexes are marked as "nailed in cache", partly to make
2241 * it easy for load_relcache_init_file to count them, but mainly
2242 * because we cannot flush and rebuild them once we've set
2243 * criticalRelcachesBuilt to true. (NOTE: perhaps it would be possible
2244 * to reload them by temporarily setting criticalRelcachesBuilt to
2245 * false again. For now, though, we just nail 'em in.)
2247 if (! criticalRelcachesBuilt)
2249 RelationBuildDescInfo buildinfo;
2252 #define LOAD_CRIT_INDEX(indname) \
2254 buildinfo.infotype = INFO_RELNAME; \
2255 buildinfo.i.info_name = (indname); \
2256 ird = RelationBuildDesc(buildinfo, NULL); \
2257 ird->rd_isnailed = true; \
2258 RelationSetReferenceCount(ird, 1); \
2261 LOAD_CRIT_INDEX(ClassNameNspIndex);
2262 LOAD_CRIT_INDEX(ClassOidIndex);
2263 LOAD_CRIT_INDEX(AttributeRelidNumIndex);
2264 LOAD_CRIT_INDEX(IndexRelidIndex);
2265 LOAD_CRIT_INDEX(AccessMethodStrategyIndex);
2266 LOAD_CRIT_INDEX(AccessMethodProcedureIndex);
2267 LOAD_CRIT_INDEX(OperatorOidIndex);
2269 #define NUM_CRITICAL_INDEXES 7 /* fix if you change list above */
2271 criticalRelcachesBuilt = true;
2275 * Now, scan all the relcache entries and update anything that might
2276 * be wrong in the results from formrdesc or the relcache cache file.
2277 * If we faked up relcache entries using formrdesc, then read
2278 * the real pg_class rows and replace the fake entries with them.
2279 * Also, if any of the relcache entries have rules or triggers,
2280 * load that info the hard way since it isn't recorded in the cache file.
2282 hash_seq_init(&status, RelationIdCache);
2284 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
2286 Relation relation = idhentry->reldesc;
2289 * If it's a faked-up entry, read the real pg_class tuple.
2291 if (needNewCacheFile && relation->rd_isnailed)
2296 htup = SearchSysCache(RELOID,
2297 ObjectIdGetDatum(RelationGetRelid(relation)),
2299 if (!HeapTupleIsValid(htup))
2300 elog(FATAL, "RelationCacheInitializePhase2: no pg_class entry for %s",
2301 RelationGetRelationName(relation));
2302 relp = (Form_pg_class) GETSTRUCT(htup);
2304 * Copy tuple to relation->rd_rel. (See notes in
2305 * AllocateRelationDesc())
2307 Assert(relation->rd_rel != NULL);
2308 memcpy((char *) relation->rd_rel, (char *) relp, CLASS_TUPLE_SIZE);
2309 relation->rd_att->tdhasoid = relp->relhasoids;
2311 ReleaseSysCache(htup);
2315 * Fix data that isn't saved in relcache cache file.
2317 if (relation->rd_rel->relhasrules && relation->rd_rules == NULL)
2318 RelationBuildRuleLock(relation);
2319 if (relation->rd_rel->reltriggers > 0 && relation->trigdesc == NULL)
2320 RelationBuildTriggers(relation);
2325 * RelationCacheInitializePhase3
2327 * Final step of relcache initialization: write out a new relcache
2328 * cache file if one is needed.
2331 RelationCacheInitializePhase3(void)
2333 if (IsBootstrapProcessingMode())
2336 if (needNewCacheFile)
2339 * Force all the catcaches to finish initializing and thereby
2340 * open the catalogs and indexes they use. This will preload
2341 * the relcache with entries for all the most important system
2342 * catalogs and indexes, so that the init file will be most
2343 * useful for future backends.
2345 InitCatalogCachePhase2();
2347 /* now write the file */
2348 write_relcache_init_file();
2353 /* used by XLogInitCache */
2354 void CreateDummyCaches(void);
2355 void DestroyDummyCaches(void);
2358 CreateDummyCaches(void)
2360 MemoryContext oldcxt;
2363 if (!CacheMemoryContext)
2364 CreateCacheMemoryContext();
2366 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2368 MemSet(&ctl, 0, sizeof(ctl));
2369 ctl.keysize = sizeof(NameData);
2370 ctl.entrysize = sizeof(RelNameCacheEnt);
2371 RelationSysNameCache = hash_create("Relcache by name", INITRELCACHESIZE,
2374 ctl.keysize = sizeof(Oid);
2375 ctl.entrysize = sizeof(RelIdCacheEnt);
2376 ctl.hash = tag_hash;
2377 RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
2378 &ctl, HASH_ELEM | HASH_FUNCTION);
2380 ctl.keysize = sizeof(RelFileNode);
2381 ctl.entrysize = sizeof(RelNodeCacheEnt);
2382 ctl.hash = tag_hash;
2383 RelationNodeCache = hash_create("Relcache by rnode", INITRELCACHESIZE,
2384 &ctl, HASH_ELEM | HASH_FUNCTION);
2386 MemoryContextSwitchTo(oldcxt);
2390 DestroyDummyCaches(void)
2392 MemoryContext oldcxt;
2394 if (!CacheMemoryContext)
2397 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2399 if (RelationIdCache)
2400 hash_destroy(RelationIdCache);
2401 if (RelationSysNameCache)
2402 hash_destroy(RelationSysNameCache);
2403 if (RelationNodeCache)
2404 hash_destroy(RelationNodeCache);
2406 RelationIdCache = RelationSysNameCache = RelationNodeCache = NULL;
2408 MemoryContextSwitchTo(oldcxt);
2412 AttrDefaultFetch(Relation relation)
2414 AttrDefault *attrdef = relation->rd_att->constr->defval;
2415 int ndef = relation->rd_att->constr->num_defval;
2425 ScanKeyEntryInitialize(&skey,
2427 (AttrNumber) Anum_pg_attrdef_adrelid,
2428 (RegProcedure) F_OIDEQ,
2429 ObjectIdGetDatum(RelationGetRelid(relation)));
2431 adrel = heap_openr(AttrDefaultRelationName, AccessShareLock);
2432 adscan = systable_beginscan(adrel, AttrDefaultIndex, true,
2437 while (HeapTupleIsValid(htup = systable_getnext(adscan)))
2439 Form_pg_attrdef adform = (Form_pg_attrdef) GETSTRUCT(htup);
2442 for (i = 0; i < ndef; i++)
2444 if (adform->adnum != attrdef[i].adnum)
2446 if (attrdef[i].adbin != NULL)
2447 elog(WARNING, "AttrDefaultFetch: second record found for attr %s in rel %s",
2448 NameStr(relation->rd_att->attrs[adform->adnum - 1]->attname),
2449 RelationGetRelationName(relation));
2451 val = fastgetattr(htup,
2452 Anum_pg_attrdef_adbin,
2453 adrel->rd_att, &isnull);
2455 elog(WARNING, "AttrDefaultFetch: adbin IS NULL for attr %s in rel %s",
2456 NameStr(relation->rd_att->attrs[adform->adnum - 1]->attname),
2457 RelationGetRelationName(relation));
2459 attrdef[i].adbin = MemoryContextStrdup(CacheMemoryContext,
2460 DatumGetCString(DirectFunctionCall1(textout,
2466 elog(WARNING, "AttrDefaultFetch: unexpected record found for attr %d in rel %s",
2468 RelationGetRelationName(relation));
2471 systable_endscan(adscan);
2472 heap_close(adrel, AccessShareLock);
2475 elog(WARNING, "AttrDefaultFetch: %d record(s) not found for rel %s",
2476 ndef - found, RelationGetRelationName(relation));
2480 CheckConstraintFetch(Relation relation)
2482 ConstrCheck *check = relation->rd_att->constr->check;
2483 int ncheck = relation->rd_att->constr->num_check;
2485 SysScanDesc conscan;
2486 ScanKeyData skey[1];
2492 ScanKeyEntryInitialize(&skey[0], 0x0,
2493 Anum_pg_constraint_conrelid, F_OIDEQ,
2494 ObjectIdGetDatum(RelationGetRelid(relation)));
2496 conrel = heap_openr(ConstraintRelationName, AccessShareLock);
2497 conscan = systable_beginscan(conrel, ConstraintRelidIndex, true,
2498 SnapshotNow, 1, skey);
2500 while (HeapTupleIsValid(htup = systable_getnext(conscan)))
2502 Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(htup);
2504 /* We want check constraints only */
2505 if (conform->contype != CONSTRAINT_CHECK)
2508 if (found == ncheck)
2509 elog(ERROR, "CheckConstraintFetch: unexpected record found for rel %s",
2510 RelationGetRelationName(relation));
2512 check[found].ccname = MemoryContextStrdup(CacheMemoryContext,
2513 NameStr(conform->conname));
2515 /* Grab and test conbin is actually set */
2516 val = fastgetattr(htup,
2517 Anum_pg_constraint_conbin,
2518 conrel->rd_att, &isnull);
2520 elog(ERROR, "CheckConstraintFetch: conbin IS NULL for rel %s",
2521 RelationGetRelationName(relation));
2523 check[found].ccbin = MemoryContextStrdup(CacheMemoryContext,
2524 DatumGetCString(DirectFunctionCall1(textout,
2529 systable_endscan(conscan);
2530 heap_close(conrel, AccessShareLock);
2532 if (found != ncheck)
2533 elog(ERROR, "CheckConstraintFetch: %d record(s) not found for rel %s",
2534 ncheck - found, RelationGetRelationName(relation));
2538 * RelationGetIndexList -- get a list of OIDs of indexes on this relation
2540 * The index list is created only if someone requests it. We scan pg_index
2541 * to find relevant indexes, and add the list to the relcache entry so that
2542 * we won't have to compute it again. Note that shared cache inval of a
2543 * relcache entry will delete the old list and set rd_indexfound to false,
2544 * so that we must recompute the index list on next request. This handles
2545 * creation or deletion of an index.
2547 * The returned list is guaranteed to be sorted in order by OID. This is
2548 * needed by the executor, since for index types that we obtain exclusive
2549 * locks on when updating the index, all backends must lock the indexes in
2550 * the same order or we will get deadlocks (see ExecOpenIndices()). Any
2551 * consistent ordering would do, but ordering by OID is easy.
2553 * Since shared cache inval causes the relcache's copy of the list to go away,
2554 * we return a copy of the list palloc'd in the caller's context. The caller
2555 * may freeList() the returned list after scanning it. This is necessary
2556 * since the caller will typically be doing syscache lookups on the relevant
2557 * indexes, and syscache lookup could cause SI messages to be processed!
2560 RelationGetIndexList(Relation relation)
2563 SysScanDesc indscan;
2567 MemoryContext oldcxt;
2569 /* Quick exit if we already computed the list. */
2570 if (relation->rd_indexfound)
2571 return listCopy(relation->rd_indexlist);
2574 * We build the list we intend to return (in the caller's context)
2575 * while doing the scan. After successfully completing the scan, we
2576 * copy that list into the relcache entry. This avoids cache-context
2577 * memory leakage if we get some sort of error partway through.
2581 /* Prepare to scan pg_index for entries having indrelid = this rel. */
2582 ScanKeyEntryInitialize(&skey,
2584 (AttrNumber) Anum_pg_index_indrelid,
2585 (RegProcedure) F_OIDEQ,
2586 ObjectIdGetDatum(RelationGetRelid(relation)));
2588 indrel = heap_openr(IndexRelationName, AccessShareLock);
2589 indscan = systable_beginscan(indrel, IndexIndrelidIndex, true,
2593 while (HeapTupleIsValid(htup = systable_getnext(indscan)))
2595 Form_pg_index index = (Form_pg_index) GETSTRUCT(htup);
2597 result = insert_ordered_oid(result, index->indexrelid);
2600 systable_endscan(indscan);
2601 heap_close(indrel, AccessShareLock);
2603 /* Now save a copy of the completed list in the relcache entry. */
2604 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2605 relation->rd_indexlist = listCopy(result);
2606 relation->rd_indexfound = true;
2607 MemoryContextSwitchTo(oldcxt);
2613 * insert_ordered_oid
2614 * Insert a new Oid into a sorted list of Oids, preserving ordering
2616 * Building the ordered list this way is O(N^2), but with a pretty small
2617 * constant, so for the number of entries we expect it will probably be
2618 * faster than trying to apply qsort(). Most tables don't have very many
2622 insert_ordered_oid(List *list, Oid datum)
2626 /* Does the datum belong at the front? */
2627 if (list == NIL || datum < (Oid) lfirsti(list))
2628 return lconsi(datum, list);
2629 /* No, so find the entry it belongs after */
2635 if (n == NIL || datum < (Oid) lfirsti(n))
2636 break; /* it belongs before n */
2639 /* Insert datum into list after item l */
2640 lnext(l) = lconsi(datum, lnext(l));
2646 * load_relcache_init_file, write_relcache_init_file
2648 * In late 1992, we started regularly having databases with more than
2649 * a thousand classes in them. With this number of classes, it became
2650 * critical to do indexed lookups on the system catalogs.
2652 * Bootstrapping these lookups is very hard. We want to be able to
2653 * use an index on pg_attribute, for example, but in order to do so,
2654 * we must have read pg_attribute for the attributes in the index,
2655 * which implies that we need to use the index.
2657 * In order to get around the problem, we do the following:
2659 * + When the database system is initialized (at initdb time), we
2660 * don't use indexes. We do sequential scans.
2662 * + When the backend is started up in normal mode, we load an image
2663 * of the appropriate relation descriptors, in internal format,
2664 * from an initialization file in the data/base/... directory.
2666 * + If the initialization file isn't there, then we create the
2667 * relation descriptors using sequential scans and write 'em to
2668 * the initialization file for use by subsequent backends.
2670 * We could dispense with the initialization file and just build the
2671 * critical reldescs the hard way on every backend startup, but that
2672 * slows down backend startup noticeably.
2674 * We can in fact go further, and save more relcache entries than
2675 * just the ones that are absolutely critical; this allows us to speed
2676 * up backend startup by not having to build such entries the hard way.
2677 * Presently, all the catalog and index entries that are referred to
2678 * by catcaches are stored in the initialization file.
2680 * The same mechanism that detects when catcache and relcache entries
2681 * need to be invalidated (due to catalog updates) also arranges to
2682 * unlink the initialization file when its contents may be out of date.
2683 * The file will then be rebuilt during the next backend startup.
2687 * load_relcache_init_file -- attempt to load cache from the init file
2689 * If successful, return TRUE and set criticalRelcachesBuilt to true.
2690 * If not successful, return FALSE and set needNewCacheFile to true.
2692 * NOTE: we assume we are already switched into CacheMemoryContext.
2695 load_relcache_init_file(void)
2698 char initfilename[MAXPGPATH];
2707 snprintf(initfilename, sizeof(initfilename), "%s/%s",
2708 DatabasePath, RELCACHE_INIT_FILENAME);
2710 fp = AllocateFile(initfilename, PG_BINARY_R);
2713 needNewCacheFile = true;
2718 * Read the index relcache entries from the file. Note we will not
2719 * enter any of them into the cache if the read fails partway through;
2720 * this helps to guard against broken init files.
2723 rels = (Relation *) palloc(max_rels * sizeof(Relation));
2725 nailed_rels = nailed_indexes = 0;
2726 initFileRelationIds = NIL;
2728 for (relno = 0; ; relno++)
2733 Form_pg_class relform;
2735 /* first read the relation descriptor length */
2736 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
2739 break; /* end of file */
2743 /* safety check for incompatible relcache layout */
2744 if (len != sizeof(RelationData))
2747 /* allocate another relcache header */
2748 if (num_rels >= max_rels)
2751 rels = (Relation *) repalloc(rels, max_rels * sizeof(Relation));
2754 rel = rels[num_rels++] = (Relation) palloc(len);
2756 /* then, read the Relation structure */
2757 if ((nread = fread(rel, 1, len, fp)) != len)
2760 /* next read the relation tuple form */
2761 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
2764 relform = (Form_pg_class) palloc(len);
2765 if ((nread = fread(relform, 1, len, fp)) != len)
2768 rel->rd_rel = relform;
2770 /* initialize attribute tuple forms */
2771 rel->rd_att = CreateTemplateTupleDesc(relform->relnatts,
2772 relform->relhasoids);
2774 /* next read all the attribute tuple form data entries */
2775 for (i = 0; i < relform->relnatts; i++)
2777 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
2780 rel->rd_att->attrs[i] = (Form_pg_attribute) palloc(len);
2782 if ((nread = fread(rel->rd_att->attrs[i], 1, len, fp)) != len)
2786 /* If it's an index, there's more to do */
2787 if (rel->rd_rel->relkind == RELKIND_INDEX)
2790 MemoryContext indexcxt;
2791 IndexStrategy strat;
2793 RegProcedure *support;
2797 /* Count nailed indexes to ensure we have 'em all */
2798 if (rel->rd_isnailed)
2801 /* next, read the pg_index tuple form */
2802 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
2805 rel->rd_index = (Form_pg_index) palloc(len);
2806 if ((nread = fread(rel->rd_index, 1, len, fp)) != len)
2809 /* next, read the access method tuple form */
2810 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
2813 am = (Form_pg_am) palloc(len);
2814 if ((nread = fread(am, 1, len, fp)) != len)
2819 * prepare index info context --- parameters should match
2820 * RelationInitIndexAccessInfo
2822 indexcxt = AllocSetContextCreate(CacheMemoryContext,
2823 RelationGetRelationName(rel),
2826 1024); /* maxsize */
2827 rel->rd_indexcxt = indexcxt;
2829 /* next, read the index strategy map */
2830 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
2833 strat = (IndexStrategy) MemoryContextAlloc(indexcxt, len);
2834 if ((nread = fread(strat, 1, len, fp)) != len)
2837 /* have to invalidate any FmgrInfo data in the strategy maps */
2838 nstrategies = am->amstrategies * relform->relnatts;
2839 for (i = 0; i < nstrategies; i++)
2840 strat->strategyMapData[i].entry[0].sk_func.fn_oid = InvalidOid;
2842 rel->rd_istrat = strat;
2844 /* next, read the vector of operator OIDs */
2845 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
2848 operator = (Oid *) MemoryContextAlloc(indexcxt, len);
2849 if ((nread = fread(operator, 1, len, fp)) != len)
2852 rel->rd_operator = operator;
2854 /* finally, read the vector of support procedures */
2855 if ((nread = fread(&len, 1, sizeof(len), fp)) != sizeof(len))
2857 support = (RegProcedure *) MemoryContextAlloc(indexcxt, len);
2858 if ((nread = fread(support, 1, len, fp)) != len)
2861 rel->rd_support = support;
2863 /* add a zeroed support-fmgr-info vector */
2864 nsupport = relform->relnatts * am->amsupport;
2865 rel->rd_supportinfo = (FmgrInfo *)
2866 MemoryContextAlloc(indexcxt, nsupport * sizeof(FmgrInfo));
2867 MemSet(rel->rd_supportinfo, 0, nsupport * sizeof(FmgrInfo));
2871 /* Count nailed rels to ensure we have 'em all */
2872 if (rel->rd_isnailed)
2875 Assert(rel->rd_index == NULL);
2876 Assert(rel->rd_am == NULL);
2877 Assert(rel->rd_indexcxt == NULL);
2878 Assert(rel->rd_istrat == NULL);
2879 Assert(rel->rd_operator == NULL);
2880 Assert(rel->rd_support == NULL);
2881 Assert(rel->rd_supportinfo == NULL);
2885 * Rules and triggers are not saved (mainly because the internal
2886 * format is complex and subject to change). They must be rebuilt
2887 * if needed by RelationCacheInitializePhase2. This is not expected
2888 * to be a big performance hit since few system catalogs have such.
2890 rel->rd_rules = NULL;
2891 rel->rd_rulescxt = NULL;
2892 rel->trigdesc = NULL;
2895 * Reset transient-state fields in the relcache entry
2898 rel->rd_targblock = InvalidBlockNumber;
2899 if (rel->rd_isnailed)
2900 RelationSetReferenceCount(rel, 1);
2902 RelationSetReferenceCount(rel, 0);
2903 rel->rd_indexfound = false;
2904 rel->rd_indexlist = NIL;
2905 MemSet(&rel->pgstat_info, 0, sizeof(rel->pgstat_info));
2908 * Make sure database ID is correct. This is needed in case the
2909 * pg_internal.init file was copied from some other database by
2912 if (rel->rd_rel->relisshared)
2913 rel->rd_node.tblNode = InvalidOid;
2915 rel->rd_node.tblNode = MyDatabaseId;
2917 RelationInitLockInfo(rel);
2921 * We reached the end of the init file without apparent problem.
2922 * Did we get the right number of nailed items? (This is a useful
2923 * crosscheck in case the set of critical rels or indexes changes.)
2925 if (nailed_rels != NUM_CRITICAL_RELS ||
2926 nailed_indexes != NUM_CRITICAL_INDEXES)
2930 * OK, all appears well.
2932 * Now insert all the new relcache entries into the cache.
2934 for (relno = 0; relno < num_rels; relno++)
2936 RelationCacheInsert(rels[relno]);
2937 /* also make a list of their OIDs, for RelationIdIsInInitFile */
2938 initFileRelationIds = lconsi((int) RelationGetRelid(rels[relno]),
2939 initFileRelationIds);
2945 criticalRelcachesBuilt = true;
2949 * init file is broken, so do it the hard way. We don't bother
2950 * trying to free the clutter we just allocated; it's not in the
2951 * relcache so it won't hurt.
2957 needNewCacheFile = true;
2962 * Write out a new initialization file with the current contents
2966 write_relcache_init_file(void)
2969 char tempfilename[MAXPGPATH];
2970 char finalfilename[MAXPGPATH];
2971 HASH_SEQ_STATUS status;
2972 RelIdCacheEnt *idhentry;
2973 MemoryContext oldcxt;
2977 * We must write a temporary file and rename it into place. Otherwise,
2978 * another backend starting at about the same time might crash trying
2979 * to read the partially-complete file.
2981 snprintf(tempfilename, sizeof(tempfilename), "%s/%s.%d",
2982 DatabasePath, RELCACHE_INIT_FILENAME, MyProcPid);
2983 snprintf(finalfilename, sizeof(finalfilename), "%s/%s",
2984 DatabasePath, RELCACHE_INIT_FILENAME);
2986 unlink(tempfilename); /* in case it exists w/wrong permissions */
2988 fp = AllocateFile(tempfilename, PG_BINARY_W);
2992 * We used to consider this a fatal error, but we might as well
2993 * continue with backend startup ...
2995 elog(WARNING, "Cannot create init file %s: %m\n\tContinuing anyway, but there's something wrong.", tempfilename);
3000 * Write all the reldescs (in no particular order).
3002 hash_seq_init(&status, RelationIdCache);
3004 initFileRelationIds = NIL;
3006 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3008 Relation rel = idhentry->reldesc;
3009 Form_pg_class relform = rel->rd_rel;
3013 * first write the relcache entry proper
3015 len = sizeof(RelationData);
3017 /* first, write the relation descriptor length */
3018 if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len))
3019 elog(FATAL, "cannot write init file -- descriptor length");
3021 /* next, write out the Relation structure */
3022 if (fwrite(rel, 1, len, fp) != len)
3023 elog(FATAL, "cannot write init file -- reldesc");
3025 /* next write the relation tuple form */
3026 len = sizeof(FormData_pg_class);
3027 if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len))
3028 elog(FATAL, "cannot write init file -- relation tuple form length");
3030 if (fwrite(relform, 1, len, fp) != len)
3031 elog(FATAL, "cannot write init file -- relation tuple form");
3033 /* next, do all the attribute tuple form data entries */
3034 for (i = 0; i < relform->relnatts; i++)
3036 len = ATTRIBUTE_TUPLE_SIZE;
3037 if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len))
3038 elog(FATAL, "cannot write init file -- length of attdesc %d", i);
3039 if (fwrite(rel->rd_att->attrs[i], 1, len, fp) != len)
3040 elog(FATAL, "cannot write init file -- attdesc %d", i);
3043 /* If it's an index, there's more to do */
3044 if (rel->rd_rel->relkind == RELKIND_INDEX)
3046 Form_pg_am am = rel->rd_am;
3050 * We need to write the index tuple form, but this is a bit
3051 * tricky since it's a variable-length struct. Rather than
3052 * hoping to intuit the length, fetch the pg_index tuple
3053 * afresh using the syscache, and write that.
3055 tuple = SearchSysCache(INDEXRELID,
3056 ObjectIdGetDatum(RelationGetRelid(rel)),
3058 if (!HeapTupleIsValid(tuple))
3059 elog(ERROR, "write_relcache_init_file: no pg_index entry for index %u",
3060 RelationGetRelid(rel));
3061 len = tuple->t_len - tuple->t_data->t_hoff;
3062 if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len))
3063 elog(FATAL, "cannot write init file -- index tuple form length");
3064 if (fwrite(GETSTRUCT(tuple), 1, len, fp) != len)
3065 elog(FATAL, "cannot write init file -- index tuple form");
3066 ReleaseSysCache(tuple);
3068 /* next, write the access method tuple form */
3069 len = sizeof(FormData_pg_am);
3070 if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len))
3071 elog(FATAL, "cannot write init file -- am tuple form length");
3073 if (fwrite(am, 1, len, fp) != len)
3074 elog(FATAL, "cannot write init file -- am tuple form");
3076 /* next, write the index strategy map */
3077 len = AttributeNumberGetIndexStrategySize(relform->relnatts,
3079 if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len))
3080 elog(FATAL, "cannot write init file -- strategy map length");
3082 if (fwrite(rel->rd_istrat, 1, len, fp) != len)
3083 elog(FATAL, "cannot write init file -- strategy map");
3085 /* next, write the vector of operator OIDs */
3086 len = relform->relnatts * (am->amstrategies * sizeof(Oid));
3087 if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len))
3088 elog(FATAL, "cannot write init file -- operator vector length");
3090 if (fwrite(rel->rd_operator, 1, len, fp) != len)
3091 elog(FATAL, "cannot write init file -- operator vector");
3093 /* finally, write the vector of support procedures */
3094 len = relform->relnatts * (am->amsupport * sizeof(RegProcedure));
3095 if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len))
3096 elog(FATAL, "cannot write init file -- support vector length");
3098 if (fwrite(rel->rd_support, 1, len, fp) != len)
3099 elog(FATAL, "cannot write init file -- support vector");
3102 /* also make a list of their OIDs, for RelationIdIsInInitFile */
3103 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3104 initFileRelationIds = lconsi((int) RelationGetRelid(rel),
3105 initFileRelationIds);
3106 MemoryContextSwitchTo(oldcxt);
3112 * Now we have to check whether the data we've so painstakingly
3113 * accumulated is already obsolete due to someone else's just-committed
3114 * catalog changes. If so, we just delete the temp file and leave it
3115 * to the next backend to try again. (Our own relcache entries will be
3116 * updated by SI message processing, but we can't be sure whether what
3117 * we wrote out was up-to-date.)
3119 * This mustn't run concurrently with RelationCacheInitFileInvalidate,
3120 * so grab a serialization lock for the duration.
3122 LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
3124 /* Make sure we have seen all incoming SI messages */
3125 AcceptInvalidationMessages();
3128 * If we have received any SI relcache invals since backend start,
3129 * assume we may have written out-of-date data.
3131 if (relcacheInvalsReceived == 0L)
3134 * OK, rename the temp file to its final name, deleting any
3135 * previously-existing init file.
3137 * Note: a failure here is possible under Cygwin, if some other
3138 * backend is holding open an unlinked-but-not-yet-gone init file.
3139 * So treat this as a noncritical failure.
3141 if (rename(tempfilename, finalfilename) < 0)
3143 elog(WARNING, "Cannot rename init file %s to %s: %m\n\tContinuing anyway, but there's something wrong.", tempfilename, finalfilename);
3145 * If we fail, try to clean up the useless temp file; don't bother
3146 * to complain if this fails too.
3148 unlink(tempfilename);
3153 /* Delete the already-obsolete temp file */
3154 unlink(tempfilename);
3157 LWLockRelease(RelCacheInitLock);
3161 * Detect whether a given relation (identified by OID) is one of the ones
3162 * we store in the init file.
3164 * Note that we effectively assume that all backends running in a database
3165 * would choose to store the same set of relations in the init file;
3166 * otherwise there are cases where we'd fail to detect the need for an init
3167 * file invalidation. This does not seem likely to be a problem in practice.
3170 RelationIdIsInInitFile(Oid relationId)
3172 return intMember((int) relationId, initFileRelationIds);
3176 * Invalidate (remove) the init file during commit of a transaction that
3177 * changed one or more of the relation cache entries that are kept in the
3180 * We actually need to remove the init file twice: once just before sending
3181 * the SI messages that include relcache inval for such relations, and once
3182 * just after sending them. The unlink before ensures that a backend that's
3183 * currently starting cannot read the now-obsolete init file and then miss
3184 * the SI messages that will force it to update its relcache entries. (This
3185 * works because the backend startup sequence gets into the PROC array before
3186 * trying to load the init file.) The unlink after is to synchronize with a
3187 * backend that may currently be trying to write an init file based on data
3188 * that we've just rendered invalid. Such a backend will see the SI messages,
3189 * but we can't leave the init file sitting around to fool later backends.
3191 * Ignore any failure to unlink the file, since it might not be there if
3192 * no backend has been started since the last removal.
3195 RelationCacheInitFileInvalidate(bool beforeSend)
3197 char initfilename[MAXPGPATH];
3199 snprintf(initfilename, sizeof(initfilename), "%s/%s",
3200 DatabasePath, RELCACHE_INIT_FILENAME);
3204 /* no interlock needed here */
3205 unlink(initfilename);
3210 * We need to interlock this against write_relcache_init_file,
3211 * to guard against possibility that someone renames a new-but-
3212 * already-obsolete init file into place just after we unlink.
3213 * With the interlock, it's certain that write_relcache_init_file
3214 * will notice our SI inval message before renaming into place,
3215 * or else that we will execute second and successfully unlink
3218 LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
3219 unlink(initfilename);
3220 LWLockRelease(RelCacheInitLock);