1 /*-------------------------------------------------------------------------
4 * POSTGRES relation descriptor cache code
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
13 *-------------------------------------------------------------------------
17 * RelationCacheInitialize - initialize relcache (to empty)
18 * RelationCacheInitializePhase2 - finish initializing relcache
19 * RelationIdGetRelation - get a reldesc by relation id
20 * RelationClose - close an open relation
23 * The following code contains many undocumented hacks. Please be
32 #include "access/genam.h"
33 #include "access/heapam.h"
34 #include "access/reloptions.h"
35 #include "access/sysattr.h"
36 #include "access/xact.h"
37 #include "catalog/catalog.h"
38 #include "catalog/index.h"
39 #include "catalog/indexing.h"
40 #include "catalog/namespace.h"
41 #include "catalog/pg_amop.h"
42 #include "catalog/pg_amproc.h"
43 #include "catalog/pg_attrdef.h"
44 #include "catalog/pg_authid.h"
45 #include "catalog/pg_constraint.h"
46 #include "catalog/pg_namespace.h"
47 #include "catalog/pg_opclass.h"
48 #include "catalog/pg_proc.h"
49 #include "catalog/pg_rewrite.h"
50 #include "catalog/pg_type.h"
51 #include "commands/trigger.h"
52 #include "miscadmin.h"
53 #include "optimizer/clauses.h"
54 #include "optimizer/planmain.h"
55 #include "optimizer/prep.h"
56 #include "optimizer/var.h"
57 #include "rewrite/rewriteDefine.h"
58 #include "storage/fd.h"
59 #include "storage/lmgr.h"
60 #include "storage/smgr.h"
61 #include "utils/builtins.h"
62 #include "utils/fmgroids.h"
63 #include "utils/inval.h"
64 #include "utils/memutils.h"
65 #include "utils/relcache.h"
66 #include "utils/resowner.h"
67 #include "utils/syscache.h"
68 #include "utils/tqual.h"
69 #include "utils/typcache.h"
73 * name of relcache init file, used to speed up backend startup
75 #define RELCACHE_INIT_FILENAME "pg_internal.init"
77 #define RELCACHE_INIT_FILEMAGIC 0x573264 /* version ID value */
80 * hardcoded tuple descriptors. see include/catalog/pg_attribute.h
82 static FormData_pg_attribute Desc_pg_class
[Natts_pg_class
] = {Schema_pg_class
};
83 static FormData_pg_attribute Desc_pg_attribute
[Natts_pg_attribute
] = {Schema_pg_attribute
};
84 static FormData_pg_attribute Desc_pg_proc
[Natts_pg_proc
] = {Schema_pg_proc
};
85 static FormData_pg_attribute Desc_pg_type
[Natts_pg_type
] = {Schema_pg_type
};
86 static FormData_pg_attribute Desc_pg_index
[Natts_pg_index
] = {Schema_pg_index
};
89 * Hash tables that index the relation cache
91 * We used to index the cache by both name and OID, but now there
92 * is only an index by OID.
94 typedef struct relidcacheent
100 static HTAB
*RelationIdCache
;
103 * This flag is false until we have prepared the critical relcache entries
104 * that are needed to do indexscans on the tables read by relcache building.
106 bool criticalRelcachesBuilt
= false;
109 * This counter counts relcache inval events received since backend startup
110 * (but only for rels that are actually in cache). Presently, we use it only
111 * to detect whether data about to be written by write_relcache_init_file()
112 * might already be obsolete.
114 static long relcacheInvalsReceived
= 0L;
117 * This list remembers the OIDs of the relations cached in the relcache
120 static List
*initFileRelationIds
= NIL
;
123 * This flag lets us optimize away work in AtEO(Sub)Xact_RelationCache().
125 static bool need_eoxact_work
= false;
129 * macros to manipulate the lookup hashtables
131 #define RelationCacheInsert(RELATION) \
133 RelIdCacheEnt *idhentry; bool found; \
134 idhentry = (RelIdCacheEnt*)hash_search(RelationIdCache, \
135 (void *) &(RELATION->rd_id), \
138 /* used to give notice if found -- now just keep quiet */ \
139 idhentry->reldesc = RELATION; \
142 #define RelationIdCacheLookup(ID, RELATION) \
144 RelIdCacheEnt *hentry; \
145 hentry = (RelIdCacheEnt*)hash_search(RelationIdCache, \
146 (void *) &(ID), HASH_FIND,NULL); \
148 RELATION = hentry->reldesc; \
153 #define RelationCacheDelete(RELATION) \
155 RelIdCacheEnt *idhentry; \
156 idhentry = (RelIdCacheEnt*)hash_search(RelationIdCache, \
157 (void *) &(RELATION->rd_id), \
158 HASH_REMOVE, NULL); \
159 if (idhentry == NULL) \
160 elog(WARNING, "trying to delete a rd_id reldesc that does not exist"); \
165 * Special cache for opclass-related information
167 * Note: only default operators and support procs get cached, ie, those with
168 * lefttype = righttype = opcintype.
170 typedef struct opclasscacheent
172 Oid opclassoid
; /* lookup key: OID of opclass */
173 bool valid
; /* set TRUE after successful fill-in */
174 StrategyNumber numStrats
; /* max # of strategies (from pg_am) */
175 StrategyNumber numSupport
; /* max # of support procs (from pg_am) */
176 Oid opcfamily
; /* OID of opclass's family */
177 Oid opcintype
; /* OID of opclass's declared input type */
178 Oid
*operatorOids
; /* strategy operators' OIDs */
179 RegProcedure
*supportProcs
; /* support procs */
182 static HTAB
*OpClassCache
= NULL
;
185 /* non-export function prototypes */
187 static void RelationClearRelation(Relation relation
, bool rebuild
);
189 static void RelationReloadIndexInfo(Relation relation
);
190 static void RelationFlushRelation(Relation relation
);
191 static bool load_relcache_init_file(void);
192 static void write_relcache_init_file(void);
193 static void write_item(const void *data
, Size len
, FILE *fp
);
195 static void formrdesc(const char *relationName
, Oid relationReltype
,
196 bool hasoids
, int natts
, FormData_pg_attribute
*att
);
198 static HeapTuple
ScanPgRelation(Oid targetRelId
, bool indexOK
);
199 static Relation
AllocateRelationDesc(Relation relation
, Form_pg_class relp
);
200 static void RelationParseRelOptions(Relation relation
, HeapTuple tuple
);
201 static void RelationBuildTupleDesc(Relation relation
);
202 static Relation
RelationBuildDesc(Oid targetRelId
, Relation oldrelation
);
203 static void RelationInitPhysicalAddr(Relation relation
);
204 static TupleDesc
GetPgClassDescriptor(void);
205 static TupleDesc
GetPgIndexDescriptor(void);
206 static void AttrDefaultFetch(Relation relation
);
207 static void CheckConstraintFetch(Relation relation
);
208 static List
*insert_ordered_oid(List
*list
, Oid datum
);
209 static void IndexSupportInitialize(oidvector
*indclass
,
211 RegProcedure
*indexSupport
,
214 StrategyNumber maxStrategyNumber
,
215 StrategyNumber maxSupportNumber
,
216 AttrNumber maxAttributeNumber
);
217 static OpClassCacheEnt
*LookupOpclassInfo(Oid operatorClassOid
,
218 StrategyNumber numStrats
,
219 StrategyNumber numSupport
);
225 * This is used by RelationBuildDesc to find a pg_class
226 * tuple matching targetRelId. The caller must hold at least
227 * AccessShareLock on the target relid to prevent concurrent-update
228 * scenarios --- else our SnapshotNow scan might fail to find any
229 * version that it thinks is live.
231 * NB: the returned tuple has been copied into palloc'd storage
232 * and must eventually be freed with heap_freetuple.
235 ScanPgRelation(Oid targetRelId
, bool indexOK
)
237 HeapTuple pg_class_tuple
;
238 Relation pg_class_desc
;
239 SysScanDesc pg_class_scan
;
246 ObjectIdAttributeNumber
,
247 BTEqualStrategyNumber
, F_OIDEQ
,
248 ObjectIdGetDatum(targetRelId
));
251 * Open pg_class and fetch a tuple. Force heap scan if we haven't yet
252 * built the critical relcache entries (this includes initdb and startup
253 * without a pg_internal.init file). The caller can also force a heap
254 * scan by setting indexOK == false.
256 pg_class_desc
= heap_open(RelationRelationId
, AccessShareLock
);
257 pg_class_scan
= systable_beginscan(pg_class_desc
, ClassOidIndexId
,
258 indexOK
&& criticalRelcachesBuilt
,
262 pg_class_tuple
= systable_getnext(pg_class_scan
);
265 * Must copy tuple before releasing buffer.
267 if (HeapTupleIsValid(pg_class_tuple
))
268 pg_class_tuple
= heap_copytuple(pg_class_tuple
);
271 systable_endscan(pg_class_scan
);
272 heap_close(pg_class_desc
, AccessShareLock
);
274 return pg_class_tuple
;
278 * AllocateRelationDesc
280 * This is used to allocate memory for a new relation descriptor
281 * and initialize the rd_rel field.
283 * If 'relation' is NULL, allocate a new RelationData object.
284 * If not, reuse the given object (that path is taken only when
285 * we have to rebuild a relcache entry during RelationClearRelation).
288 AllocateRelationDesc(Relation relation
, Form_pg_class relp
)
290 MemoryContext oldcxt
;
291 Form_pg_class relationForm
;
293 /* Relcache entries must live in CacheMemoryContext */
294 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
297 * allocate space for new relation descriptor, if needed
299 if (relation
== NULL
)
300 relation
= (Relation
) palloc(sizeof(RelationData
));
303 * clear all fields of reldesc
305 MemSet(relation
, 0, sizeof(RelationData
));
306 relation
->rd_targblock
= InvalidBlockNumber
;
307 relation
->rd_fsm_nblocks
= InvalidBlockNumber
;
308 relation
->rd_vm_nblocks
= InvalidBlockNumber
;
310 /* make sure relation is marked as having no open file yet */
311 relation
->rd_smgr
= NULL
;
314 * Copy the relation tuple form
316 * We only allocate space for the fixed fields, ie, CLASS_TUPLE_SIZE. The
317 * variable-length fields (relacl, reloptions) are NOT stored in the
318 * relcache --- there'd be little point in it, since we don't copy the
319 * tuple's nulls bitmap and hence wouldn't know if the values are valid.
320 * Bottom line is that relacl *cannot* be retrieved from the relcache. Get
321 * it from the syscache if you need it. The same goes for the original
322 * form of reloptions (however, we do store the parsed form of reloptions
325 relationForm
= (Form_pg_class
) palloc(CLASS_TUPLE_SIZE
);
327 memcpy(relationForm
, relp
, CLASS_TUPLE_SIZE
);
329 /* initialize relation tuple form */
330 relation
->rd_rel
= relationForm
;
332 /* and allocate attribute tuple form storage */
333 relation
->rd_att
= CreateTemplateTupleDesc(relationForm
->relnatts
,
334 relationForm
->relhasoids
);
335 /* which we mark as a reference-counted tupdesc */
336 relation
->rd_att
->tdrefcount
= 1;
338 MemoryContextSwitchTo(oldcxt
);
344 * RelationParseRelOptions
345 * Convert pg_class.reloptions into pre-parsed rd_options
347 * tuple is the real pg_class tuple (not rd_rel!) for relation
349 * Note: rd_rel and (if an index) rd_am must be valid already
352 RelationParseRelOptions(Relation relation
, HeapTuple tuple
)
356 relation
->rd_options
= NULL
;
358 /* Fall out if relkind should not have options */
359 switch (relation
->rd_rel
->relkind
)
361 case RELKIND_RELATION
:
362 case RELKIND_TOASTVALUE
:
363 case RELKIND_UNCATALOGED
:
371 * Fetch reloptions from tuple; have to use a hardwired descriptor because
372 * we might not have any other for pg_class yet (consider executing this
373 * code for pg_class itself)
375 options
= extractRelOptions(tuple
,
376 GetPgClassDescriptor(),
377 relation
->rd_rel
->relkind
== RELKIND_INDEX
?
378 relation
->rd_am
->amoptions
: InvalidOid
);
380 /* Copy parsed data into CacheMemoryContext */
383 relation
->rd_options
= MemoryContextAlloc(CacheMemoryContext
,
385 memcpy(relation
->rd_options
, options
, VARSIZE(options
));
390 * RelationBuildTupleDesc
392 * Form the relation's tuple descriptor from information in
393 * the pg_attribute, pg_attrdef & pg_constraint system catalogs.
396 RelationBuildTupleDesc(Relation relation
)
398 HeapTuple pg_attribute_tuple
;
399 Relation pg_attribute_desc
;
400 SysScanDesc pg_attribute_scan
;
404 AttrDefault
*attrdef
= NULL
;
407 /* copy some fields from pg_class row to rd_att */
408 relation
->rd_att
->tdtypeid
= relation
->rd_rel
->reltype
;
409 relation
->rd_att
->tdtypmod
= -1; /* unnecessary, but... */
410 relation
->rd_att
->tdhasoid
= relation
->rd_rel
->relhasoids
;
412 constr
= (TupleConstr
*) MemoryContextAlloc(CacheMemoryContext
,
413 sizeof(TupleConstr
));
414 constr
->has_not_null
= false;
417 * Form a scan key that selects only user attributes (attnum > 0).
418 * (Eliminating system attribute rows at the index level is lots faster
419 * than fetching them.)
421 ScanKeyInit(&skey
[0],
422 Anum_pg_attribute_attrelid
,
423 BTEqualStrategyNumber
, F_OIDEQ
,
424 ObjectIdGetDatum(RelationGetRelid(relation
)));
425 ScanKeyInit(&skey
[1],
426 Anum_pg_attribute_attnum
,
427 BTGreaterStrategyNumber
, F_INT2GT
,
431 * Open pg_attribute and begin a scan. Force heap scan if we haven't yet
432 * built the critical relcache entries (this includes initdb and startup
433 * without a pg_internal.init file).
435 pg_attribute_desc
= heap_open(AttributeRelationId
, AccessShareLock
);
436 pg_attribute_scan
= systable_beginscan(pg_attribute_desc
,
437 AttributeRelidNumIndexId
,
438 criticalRelcachesBuilt
,
443 * add attribute data to relation->rd_att
445 need
= relation
->rd_rel
->relnatts
;
447 while (HeapTupleIsValid(pg_attribute_tuple
= systable_getnext(pg_attribute_scan
)))
449 Form_pg_attribute attp
;
451 attp
= (Form_pg_attribute
) GETSTRUCT(pg_attribute_tuple
);
453 if (attp
->attnum
<= 0 ||
454 attp
->attnum
> relation
->rd_rel
->relnatts
)
455 elog(ERROR
, "invalid attribute number %d for %s",
456 attp
->attnum
, RelationGetRelationName(relation
));
458 memcpy(relation
->rd_att
->attrs
[attp
->attnum
- 1],
460 ATTRIBUTE_FIXED_PART_SIZE
);
462 /* Update constraint/default info */
463 if (attp
->attnotnull
)
464 constr
->has_not_null
= true;
469 attrdef
= (AttrDefault
*)
470 MemoryContextAllocZero(CacheMemoryContext
,
471 relation
->rd_rel
->relnatts
*
472 sizeof(AttrDefault
));
473 attrdef
[ndef
].adnum
= attp
->attnum
;
474 attrdef
[ndef
].adbin
= NULL
;
483 * end the scan and close the attribute relation
485 systable_endscan(pg_attribute_scan
);
486 heap_close(pg_attribute_desc
, AccessShareLock
);
489 elog(ERROR
, "catalog is missing %d attribute(s) for relid %u",
490 need
, RelationGetRelid(relation
));
493 * The attcacheoff values we read from pg_attribute should all be -1
494 * ("unknown"). Verify this if assert checking is on. They will be
495 * computed when and if needed during tuple access.
497 #ifdef USE_ASSERT_CHECKING
501 for (i
= 0; i
< relation
->rd_rel
->relnatts
; i
++)
502 Assert(relation
->rd_att
->attrs
[i
]->attcacheoff
== -1);
507 * However, we can easily set the attcacheoff value for the first
508 * attribute: it must be zero. This eliminates the need for special cases
509 * for attnum=1 that used to exist in fastgetattr() and index_getattr().
511 if (relation
->rd_rel
->relnatts
> 0)
512 relation
->rd_att
->attrs
[0]->attcacheoff
= 0;
515 * Set up constraint/default info
517 if (constr
->has_not_null
|| ndef
> 0 || relation
->rd_rel
->relchecks
)
519 relation
->rd_att
->constr
= constr
;
521 if (ndef
> 0) /* DEFAULTs */
523 if (ndef
< relation
->rd_rel
->relnatts
)
524 constr
->defval
= (AttrDefault
*)
525 repalloc(attrdef
, ndef
* sizeof(AttrDefault
));
527 constr
->defval
= attrdef
;
528 constr
->num_defval
= ndef
;
529 AttrDefaultFetch(relation
);
532 constr
->num_defval
= 0;
534 if (relation
->rd_rel
->relchecks
> 0) /* CHECKs */
536 constr
->num_check
= relation
->rd_rel
->relchecks
;
537 constr
->check
= (ConstrCheck
*)
538 MemoryContextAllocZero(CacheMemoryContext
,
539 constr
->num_check
* sizeof(ConstrCheck
));
540 CheckConstraintFetch(relation
);
543 constr
->num_check
= 0;
548 relation
->rd_att
->constr
= NULL
;
553 * RelationBuildRuleLock
555 * Form the relation's rewrite rules from information in
556 * the pg_rewrite system catalog.
558 * Note: The rule parsetrees are potentially very complex node structures.
559 * To allow these trees to be freed when the relcache entry is flushed,
560 * we make a private memory context to hold the RuleLock information for
561 * each relcache entry that has associated rules. The context is used
562 * just for rule info, not for any other subsidiary data of the relcache
563 * entry, because that keeps the update logic in RelationClearRelation()
564 * manageable. The other subsidiary data structures are simple enough
565 * to be easy to free explicitly, anyway.
568 RelationBuildRuleLock(Relation relation
)
570 MemoryContext rulescxt
;
571 MemoryContext oldcxt
;
572 HeapTuple rewrite_tuple
;
573 Relation rewrite_desc
;
574 TupleDesc rewrite_tupdesc
;
575 SysScanDesc rewrite_scan
;
583 * Make the private context. Parameters are set on the assumption that
584 * it'll probably not contain much data.
586 rulescxt
= AllocSetContextCreate(CacheMemoryContext
,
587 RelationGetRelationName(relation
),
588 ALLOCSET_SMALL_MINSIZE
,
589 ALLOCSET_SMALL_INITSIZE
,
590 ALLOCSET_SMALL_MAXSIZE
);
591 relation
->rd_rulescxt
= rulescxt
;
594 * allocate an array to hold the rewrite rules (the array is extended if
598 rules
= (RewriteRule
**)
599 MemoryContextAlloc(rulescxt
, sizeof(RewriteRule
*) * maxlocks
);
606 Anum_pg_rewrite_ev_class
,
607 BTEqualStrategyNumber
, F_OIDEQ
,
608 ObjectIdGetDatum(RelationGetRelid(relation
)));
611 * open pg_rewrite and begin a scan
613 * Note: since we scan the rules using RewriteRelRulenameIndexId, we will
614 * be reading the rules in name order, except possibly during
615 * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
616 * ensures that rules will be fired in name order.
618 rewrite_desc
= heap_open(RewriteRelationId
, AccessShareLock
);
619 rewrite_tupdesc
= RelationGetDescr(rewrite_desc
);
620 rewrite_scan
= systable_beginscan(rewrite_desc
,
621 RewriteRelRulenameIndexId
,
625 while (HeapTupleIsValid(rewrite_tuple
= systable_getnext(rewrite_scan
)))
627 Form_pg_rewrite rewrite_form
= (Form_pg_rewrite
) GETSTRUCT(rewrite_tuple
);
633 rule
= (RewriteRule
*) MemoryContextAlloc(rulescxt
,
634 sizeof(RewriteRule
));
636 rule
->ruleId
= HeapTupleGetOid(rewrite_tuple
);
638 rule
->event
= rewrite_form
->ev_type
- '0';
639 rule
->attrno
= rewrite_form
->ev_attr
;
640 rule
->enabled
= rewrite_form
->ev_enabled
;
641 rule
->isInstead
= rewrite_form
->is_instead
;
644 * Must use heap_getattr to fetch ev_action and ev_qual. Also, the
645 * rule strings are often large enough to be toasted. To avoid
646 * leaking memory in the caller's context, do the detoasting here so
647 * we can free the detoasted version.
649 rule_datum
= heap_getattr(rewrite_tuple
,
650 Anum_pg_rewrite_ev_action
,
654 rule_str
= TextDatumGetCString(rule_datum
);
655 oldcxt
= MemoryContextSwitchTo(rulescxt
);
656 rule
->actions
= (List
*) stringToNode(rule_str
);
657 MemoryContextSwitchTo(oldcxt
);
660 rule_datum
= heap_getattr(rewrite_tuple
,
661 Anum_pg_rewrite_ev_qual
,
665 rule_str
= TextDatumGetCString(rule_datum
);
666 oldcxt
= MemoryContextSwitchTo(rulescxt
);
667 rule
->qual
= (Node
*) stringToNode(rule_str
);
668 MemoryContextSwitchTo(oldcxt
);
672 * We want the rule's table references to be checked as though by the
673 * table owner, not the user referencing the rule. Therefore, scan
674 * through the rule's actions and set the checkAsUser field on all
675 * rtable entries. We have to look at the qual as well, in case it
678 * The reason for doing this when the rule is loaded, rather than when
679 * it is stored, is that otherwise ALTER TABLE OWNER would have to
680 * grovel through stored rules to update checkAsUser fields. Scanning
681 * the rule tree during load is relatively cheap (compared to
682 * constructing it in the first place), so we do it here.
684 setRuleCheckAsUser((Node
*) rule
->actions
, relation
->rd_rel
->relowner
);
685 setRuleCheckAsUser(rule
->qual
, relation
->rd_rel
->relowner
);
687 if (numlocks
>= maxlocks
)
690 rules
= (RewriteRule
**)
691 repalloc(rules
, sizeof(RewriteRule
*) * maxlocks
);
693 rules
[numlocks
++] = rule
;
697 * end the scan and close the attribute relation
699 systable_endscan(rewrite_scan
);
700 heap_close(rewrite_desc
, AccessShareLock
);
703 * there might not be any rules (if relhasrules is out-of-date)
707 relation
->rd_rules
= NULL
;
708 relation
->rd_rulescxt
= NULL
;
709 MemoryContextDelete(rulescxt
);
714 * form a RuleLock and insert into relation
716 rulelock
= (RuleLock
*) MemoryContextAlloc(rulescxt
, sizeof(RuleLock
));
717 rulelock
->numLocks
= numlocks
;
718 rulelock
->rules
= rules
;
720 relation
->rd_rules
= rulelock
;
726 * Determine whether two RuleLocks are equivalent
728 * Probably this should be in the rules code someplace...
731 equalRuleLocks(RuleLock
*rlock1
, RuleLock
*rlock2
)
736 * As of 7.3 we assume the rule ordering is repeatable, because
737 * RelationBuildRuleLock should read 'em in a consistent order. So just
738 * compare corresponding slots.
744 if (rlock1
->numLocks
!= rlock2
->numLocks
)
746 for (i
= 0; i
< rlock1
->numLocks
; i
++)
748 RewriteRule
*rule1
= rlock1
->rules
[i
];
749 RewriteRule
*rule2
= rlock2
->rules
[i
];
751 if (rule1
->ruleId
!= rule2
->ruleId
)
753 if (rule1
->event
!= rule2
->event
)
755 if (rule1
->attrno
!= rule2
->attrno
)
757 if (rule1
->enabled
!= rule2
->enabled
)
759 if (rule1
->isInstead
!= rule2
->isInstead
)
761 if (!equal(rule1
->qual
, rule2
->qual
))
763 if (!equal(rule1
->actions
, rule2
->actions
))
767 else if (rlock2
!= NULL
)
776 * Build a relation descriptor --- either a new one, or by
777 * recycling the given old relation object. The latter case
778 * supports rebuilding a relcache entry without invalidating
779 * pointers to it. The caller must hold at least
780 * AccessShareLock on the target relid.
782 * Returns NULL if no pg_class row could be found for the given relid
783 * (suggesting we are trying to access a just-deleted relation).
784 * Any other error is reported via elog.
787 RelationBuildDesc(Oid targetRelId
, Relation oldrelation
)
791 HeapTuple pg_class_tuple
;
793 MemoryContext oldcxt
;
796 * find the tuple in pg_class corresponding to the given relation id
798 pg_class_tuple
= ScanPgRelation(targetRelId
, true);
801 * if no such tuple exists, return NULL
803 if (!HeapTupleIsValid(pg_class_tuple
))
807 * get information from the pg_class_tuple
809 relid
= HeapTupleGetOid(pg_class_tuple
);
810 relp
= (Form_pg_class
) GETSTRUCT(pg_class_tuple
);
813 * allocate storage for the relation descriptor, and copy pg_class_tuple
814 * to relation->rd_rel.
816 relation
= AllocateRelationDesc(oldrelation
, relp
);
819 * initialize the relation's relation id (relation->rd_id)
821 RelationGetRelid(relation
) = relid
;
824 * normal relations are not nailed into the cache; nor can a pre-existing
825 * relation be new. It could be temp though. (Actually, it could be new
826 * too, but it's okay to forget that fact if forced to flush the entry.)
828 relation
->rd_refcnt
= 0;
829 relation
->rd_isnailed
= false;
830 relation
->rd_createSubid
= InvalidSubTransactionId
;
831 relation
->rd_newRelfilenodeSubid
= InvalidSubTransactionId
;
832 relation
->rd_istemp
= relation
->rd_rel
->relistemp
;
833 if (relation
->rd_istemp
)
834 relation
->rd_islocaltemp
= isTempOrToastNamespace(relation
->rd_rel
->relnamespace
);
836 relation
->rd_islocaltemp
= false;
839 * initialize the tuple descriptor (relation->rd_att).
841 RelationBuildTupleDesc(relation
);
844 * Fetch rules and triggers that affect this relation
846 if (relation
->rd_rel
->relhasrules
)
847 RelationBuildRuleLock(relation
);
850 relation
->rd_rules
= NULL
;
851 relation
->rd_rulescxt
= NULL
;
854 if (relation
->rd_rel
->relhastriggers
)
855 RelationBuildTriggers(relation
);
857 relation
->trigdesc
= NULL
;
860 * if it's an index, initialize index-related information
862 if (OidIsValid(relation
->rd_rel
->relam
))
863 RelationInitIndexAccessInfo(relation
);
865 /* extract reloptions if any */
866 RelationParseRelOptions(relation
, pg_class_tuple
);
869 * initialize the relation lock manager information
871 RelationInitLockInfo(relation
); /* see lmgr.c */
874 * initialize physical addressing information for the relation
876 RelationInitPhysicalAddr(relation
);
878 /* make sure relation is marked as having no open file yet */
879 relation
->rd_smgr
= NULL
;
882 * now we can free the memory allocated for pg_class_tuple
884 heap_freetuple(pg_class_tuple
);
887 * Insert newly created relation into relcache hash tables.
889 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
890 RelationCacheInsert(relation
);
891 MemoryContextSwitchTo(oldcxt
);
893 /* It's fully valid */
894 relation
->rd_isvalid
= true;
900 * Initialize the physical addressing info (RelFileNode) for a relcache entry
903 RelationInitPhysicalAddr(Relation relation
)
905 if (relation
->rd_rel
->reltablespace
)
906 relation
->rd_node
.spcNode
= relation
->rd_rel
->reltablespace
;
908 relation
->rd_node
.spcNode
= MyDatabaseTableSpace
;
909 if (relation
->rd_rel
->relisshared
)
910 relation
->rd_node
.dbNode
= InvalidOid
;
912 relation
->rd_node
.dbNode
= MyDatabaseId
;
913 relation
->rd_node
.relNode
= relation
->rd_rel
->relfilenode
;
917 * Initialize index-access-method support data for an index relation
920 RelationInitIndexAccessInfo(Relation relation
)
925 Datum indoptionDatum
;
928 int2vector
*indoption
;
929 MemoryContext indexcxt
;
930 MemoryContext oldcontext
;
936 * Make a copy of the pg_index entry for the index. Since pg_index
937 * contains variable-length and possibly-null fields, we have to do this
938 * honestly rather than just treating it as a Form_pg_index struct.
940 tuple
= SearchSysCache(INDEXRELID
,
941 ObjectIdGetDatum(RelationGetRelid(relation
)),
943 if (!HeapTupleIsValid(tuple
))
944 elog(ERROR
, "cache lookup failed for index %u",
945 RelationGetRelid(relation
));
946 oldcontext
= MemoryContextSwitchTo(CacheMemoryContext
);
947 relation
->rd_indextuple
= heap_copytuple(tuple
);
948 relation
->rd_index
= (Form_pg_index
) GETSTRUCT(relation
->rd_indextuple
);
949 MemoryContextSwitchTo(oldcontext
);
950 ReleaseSysCache(tuple
);
953 * Make a copy of the pg_am entry for the index's access method
955 tuple
= SearchSysCache(AMOID
,
956 ObjectIdGetDatum(relation
->rd_rel
->relam
),
958 if (!HeapTupleIsValid(tuple
))
959 elog(ERROR
, "cache lookup failed for access method %u",
960 relation
->rd_rel
->relam
);
961 aform
= (Form_pg_am
) MemoryContextAlloc(CacheMemoryContext
, sizeof *aform
);
962 memcpy(aform
, GETSTRUCT(tuple
), sizeof *aform
);
963 ReleaseSysCache(tuple
);
964 relation
->rd_am
= aform
;
966 natts
= relation
->rd_rel
->relnatts
;
967 if (natts
!= relation
->rd_index
->indnatts
)
968 elog(ERROR
, "relnatts disagrees with indnatts for index %u",
969 RelationGetRelid(relation
));
970 amstrategies
= aform
->amstrategies
;
971 amsupport
= aform
->amsupport
;
974 * Make the private context to hold index access info. The reason we need
975 * a context, and not just a couple of pallocs, is so that we won't leak
976 * any subsidiary info attached to fmgr lookup records.
978 * Context parameters are set on the assumption that it'll probably not
981 indexcxt
= AllocSetContextCreate(CacheMemoryContext
,
982 RelationGetRelationName(relation
),
983 ALLOCSET_SMALL_MINSIZE
,
984 ALLOCSET_SMALL_INITSIZE
,
985 ALLOCSET_SMALL_MAXSIZE
);
986 relation
->rd_indexcxt
= indexcxt
;
989 * Allocate arrays to hold data
991 relation
->rd_aminfo
= (RelationAmInfo
*)
992 MemoryContextAllocZero(indexcxt
, sizeof(RelationAmInfo
));
994 relation
->rd_opfamily
= (Oid
*)
995 MemoryContextAllocZero(indexcxt
, natts
* sizeof(Oid
));
996 relation
->rd_opcintype
= (Oid
*)
997 MemoryContextAllocZero(indexcxt
, natts
* sizeof(Oid
));
999 if (amstrategies
> 0)
1000 relation
->rd_operator
= (Oid
*)
1001 MemoryContextAllocZero(indexcxt
,
1002 natts
* amstrategies
* sizeof(Oid
));
1004 relation
->rd_operator
= NULL
;
1008 int nsupport
= natts
* amsupport
;
1010 relation
->rd_support
= (RegProcedure
*)
1011 MemoryContextAllocZero(indexcxt
, nsupport
* sizeof(RegProcedure
));
1012 relation
->rd_supportinfo
= (FmgrInfo
*)
1013 MemoryContextAllocZero(indexcxt
, nsupport
* sizeof(FmgrInfo
));
1017 relation
->rd_support
= NULL
;
1018 relation
->rd_supportinfo
= NULL
;
1021 relation
->rd_indoption
= (int16
*)
1022 MemoryContextAllocZero(indexcxt
, natts
* sizeof(int16
));
1025 * indclass cannot be referenced directly through the C struct, because it
1026 * comes after the variable-width indkey field. Must extract the datum
1029 indclassDatum
= fastgetattr(relation
->rd_indextuple
,
1030 Anum_pg_index_indclass
,
1031 GetPgIndexDescriptor(),
1034 indclass
= (oidvector
*) DatumGetPointer(indclassDatum
);
1037 * Fill the operator and support procedure OID arrays, as well as the info
1038 * about opfamilies and opclass input types. (aminfo and supportinfo are
1039 * left as zeroes, and are filled on-the-fly when used)
1041 IndexSupportInitialize(indclass
,
1042 relation
->rd_operator
, relation
->rd_support
,
1043 relation
->rd_opfamily
, relation
->rd_opcintype
,
1044 amstrategies
, amsupport
, natts
);
1047 * Similarly extract indoption and copy it to the cache entry
1049 indoptionDatum
= fastgetattr(relation
->rd_indextuple
,
1050 Anum_pg_index_indoption
,
1051 GetPgIndexDescriptor(),
1054 indoption
= (int2vector
*) DatumGetPointer(indoptionDatum
);
1055 memcpy(relation
->rd_indoption
, indoption
->values
, natts
* sizeof(int16
));
1058 * expressions and predicate cache will be filled later
1060 relation
->rd_indexprs
= NIL
;
1061 relation
->rd_indpred
= NIL
;
1062 relation
->rd_amcache
= NULL
;
1066 * IndexSupportInitialize
1067 * Initializes an index's cached opclass information,
1068 * given the index's pg_index.indclass entry.
1070 * Data is returned into *indexOperator, *indexSupport, *opFamily, and
1071 * *opcInType, which are arrays allocated by the caller.
1073 * The caller also passes maxStrategyNumber, maxSupportNumber, and
1074 * maxAttributeNumber, since these indicate the size of the arrays
1075 * it has allocated --- but in practice these numbers must always match
1076 * those obtainable from the system catalog entries for the index and
1080 IndexSupportInitialize(oidvector
*indclass
,
1082 RegProcedure
*indexSupport
,
1085 StrategyNumber maxStrategyNumber
,
1086 StrategyNumber maxSupportNumber
,
1087 AttrNumber maxAttributeNumber
)
1091 for (attIndex
= 0; attIndex
< maxAttributeNumber
; attIndex
++)
1093 OpClassCacheEnt
*opcentry
;
1095 if (!OidIsValid(indclass
->values
[attIndex
]))
1096 elog(ERROR
, "bogus pg_index tuple");
1098 /* look up the info for this opclass, using a cache */
1099 opcentry
= LookupOpclassInfo(indclass
->values
[attIndex
],
1103 /* copy cached data into relcache entry */
1104 opFamily
[attIndex
] = opcentry
->opcfamily
;
1105 opcInType
[attIndex
] = opcentry
->opcintype
;
1106 if (maxStrategyNumber
> 0)
1107 memcpy(&indexOperator
[attIndex
* maxStrategyNumber
],
1108 opcentry
->operatorOids
,
1109 maxStrategyNumber
* sizeof(Oid
));
1110 if (maxSupportNumber
> 0)
1111 memcpy(&indexSupport
[attIndex
* maxSupportNumber
],
1112 opcentry
->supportProcs
,
1113 maxSupportNumber
* sizeof(RegProcedure
));
1120 * This routine maintains a per-opclass cache of the information needed
1121 * by IndexSupportInitialize(). This is more efficient than relying on
1122 * the catalog cache, because we can load all the info about a particular
1123 * opclass in a single indexscan of pg_amproc or pg_amop.
1125 * The information from pg_am about expected range of strategy and support
1126 * numbers is passed in, rather than being looked up, mainly because the
1127 * caller will have it already.
1129 * Note there is no provision for flushing the cache. This is OK at the
1130 * moment because there is no way to ALTER any interesting properties of an
1131 * existing opclass --- all you can do is drop it, which will result in
1132 * a useless but harmless dead entry in the cache. To support altering
1133 * opclass membership (not the same as opfamily membership!), we'd need to
1134 * be able to flush this cache as well as the contents of relcache entries
1137 static OpClassCacheEnt
*
1138 LookupOpclassInfo(Oid operatorClassOid
,
1139 StrategyNumber numStrats
,
1140 StrategyNumber numSupport
)
1142 OpClassCacheEnt
*opcentry
;
1146 ScanKeyData skey
[3];
1150 if (OpClassCache
== NULL
)
1152 /* First time through: initialize the opclass cache */
1155 if (!CacheMemoryContext
)
1156 CreateCacheMemoryContext();
1158 MemSet(&ctl
, 0, sizeof(ctl
));
1159 ctl
.keysize
= sizeof(Oid
);
1160 ctl
.entrysize
= sizeof(OpClassCacheEnt
);
1161 ctl
.hash
= oid_hash
;
1162 OpClassCache
= hash_create("Operator class cache", 64,
1163 &ctl
, HASH_ELEM
| HASH_FUNCTION
);
1166 opcentry
= (OpClassCacheEnt
*) hash_search(OpClassCache
,
1167 (void *) &operatorClassOid
,
1168 HASH_ENTER
, &found
);
1172 /* Need to allocate memory for new entry */
1173 opcentry
->valid
= false; /* until known OK */
1174 opcentry
->numStrats
= numStrats
;
1175 opcentry
->numSupport
= numSupport
;
1178 opcentry
->operatorOids
= (Oid
*)
1179 MemoryContextAllocZero(CacheMemoryContext
,
1180 numStrats
* sizeof(Oid
));
1182 opcentry
->operatorOids
= NULL
;
1185 opcentry
->supportProcs
= (RegProcedure
*)
1186 MemoryContextAllocZero(CacheMemoryContext
,
1187 numSupport
* sizeof(RegProcedure
));
1189 opcentry
->supportProcs
= NULL
;
1193 Assert(numStrats
== opcentry
->numStrats
);
1194 Assert(numSupport
== opcentry
->numSupport
);
1198 * When testing for cache-flush hazards, we intentionally disable the
1199 * operator class cache and force reloading of the info on each call. This
1200 * is helpful because we want to test the case where a cache flush occurs
1201 * while we are loading the info, and it's very hard to provoke that if
1202 * this happens only once per opclass per backend.
1204 #if defined(CLOBBER_CACHE_ALWAYS)
1205 opcentry
->valid
= false;
1208 if (opcentry
->valid
)
1212 * Need to fill in new entry.
1214 * To avoid infinite recursion during startup, force heap scans if we're
1215 * looking up info for the opclasses used by the indexes we would like to
1218 indexOK
= criticalRelcachesBuilt
||
1219 (operatorClassOid
!= OID_BTREE_OPS_OID
&&
1220 operatorClassOid
!= INT2_BTREE_OPS_OID
);
1223 * We have to fetch the pg_opclass row to determine its opfamily and
1224 * opcintype, which are needed to look up the operators and functions.
1225 * It'd be convenient to use the syscache here, but that probably doesn't
1226 * work while bootstrapping.
1228 ScanKeyInit(&skey
[0],
1229 ObjectIdAttributeNumber
,
1230 BTEqualStrategyNumber
, F_OIDEQ
,
1231 ObjectIdGetDatum(operatorClassOid
));
1232 rel
= heap_open(OperatorClassRelationId
, AccessShareLock
);
1233 scan
= systable_beginscan(rel
, OpclassOidIndexId
, indexOK
,
1234 SnapshotNow
, 1, skey
);
1236 if (HeapTupleIsValid(htup
= systable_getnext(scan
)))
1238 Form_pg_opclass opclassform
= (Form_pg_opclass
) GETSTRUCT(htup
);
1240 opcentry
->opcfamily
= opclassform
->opcfamily
;
1241 opcentry
->opcintype
= opclassform
->opcintype
;
1244 elog(ERROR
, "could not find tuple for opclass %u", operatorClassOid
);
1246 systable_endscan(scan
);
1247 heap_close(rel
, AccessShareLock
);
1251 * Scan pg_amop to obtain operators for the opclass. We only fetch the
1252 * default ones (those with lefttype = righttype = opcintype).
1256 ScanKeyInit(&skey
[0],
1257 Anum_pg_amop_amopfamily
,
1258 BTEqualStrategyNumber
, F_OIDEQ
,
1259 ObjectIdGetDatum(opcentry
->opcfamily
));
1260 ScanKeyInit(&skey
[1],
1261 Anum_pg_amop_amoplefttype
,
1262 BTEqualStrategyNumber
, F_OIDEQ
,
1263 ObjectIdGetDatum(opcentry
->opcintype
));
1264 ScanKeyInit(&skey
[2],
1265 Anum_pg_amop_amoprighttype
,
1266 BTEqualStrategyNumber
, F_OIDEQ
,
1267 ObjectIdGetDatum(opcentry
->opcintype
));
1268 rel
= heap_open(AccessMethodOperatorRelationId
, AccessShareLock
);
1269 scan
= systable_beginscan(rel
, AccessMethodStrategyIndexId
, indexOK
,
1270 SnapshotNow
, 3, skey
);
1272 while (HeapTupleIsValid(htup
= systable_getnext(scan
)))
1274 Form_pg_amop amopform
= (Form_pg_amop
) GETSTRUCT(htup
);
1276 if (amopform
->amopstrategy
<= 0 ||
1277 (StrategyNumber
) amopform
->amopstrategy
> numStrats
)
1278 elog(ERROR
, "invalid amopstrategy number %d for opclass %u",
1279 amopform
->amopstrategy
, operatorClassOid
);
1280 opcentry
->operatorOids
[amopform
->amopstrategy
- 1] =
1284 systable_endscan(scan
);
1285 heap_close(rel
, AccessShareLock
);
1289 * Scan pg_amproc to obtain support procs for the opclass. We only fetch
1290 * the default ones (those with lefttype = righttype = opcintype).
1294 ScanKeyInit(&skey
[0],
1295 Anum_pg_amproc_amprocfamily
,
1296 BTEqualStrategyNumber
, F_OIDEQ
,
1297 ObjectIdGetDatum(opcentry
->opcfamily
));
1298 ScanKeyInit(&skey
[1],
1299 Anum_pg_amproc_amproclefttype
,
1300 BTEqualStrategyNumber
, F_OIDEQ
,
1301 ObjectIdGetDatum(opcentry
->opcintype
));
1302 ScanKeyInit(&skey
[2],
1303 Anum_pg_amproc_amprocrighttype
,
1304 BTEqualStrategyNumber
, F_OIDEQ
,
1305 ObjectIdGetDatum(opcentry
->opcintype
));
1306 rel
= heap_open(AccessMethodProcedureRelationId
, AccessShareLock
);
1307 scan
= systable_beginscan(rel
, AccessMethodProcedureIndexId
, indexOK
,
1308 SnapshotNow
, 3, skey
);
1310 while (HeapTupleIsValid(htup
= systable_getnext(scan
)))
1312 Form_pg_amproc amprocform
= (Form_pg_amproc
) GETSTRUCT(htup
);
1314 if (amprocform
->amprocnum
<= 0 ||
1315 (StrategyNumber
) amprocform
->amprocnum
> numSupport
)
1316 elog(ERROR
, "invalid amproc number %d for opclass %u",
1317 amprocform
->amprocnum
, operatorClassOid
);
1319 opcentry
->supportProcs
[amprocform
->amprocnum
- 1] =
1323 systable_endscan(scan
);
1324 heap_close(rel
, AccessShareLock
);
1327 opcentry
->valid
= true;
1335 * This is a special cut-down version of RelationBuildDesc()
1336 * used by RelationCacheInitializePhase2() in initializing the relcache.
1337 * The relation descriptor is built just from the supplied parameters,
1338 * without actually looking at any system table entries. We cheat
1339 * quite a lot since we only need to work for a few basic system
1342 * formrdesc is currently used for: pg_class, pg_attribute, pg_proc,
1343 * and pg_type (see RelationCacheInitializePhase2).
1345 * Note that these catalogs can't have constraints (except attnotnull),
1346 * default values, rules, or triggers, since we don't cope with any of that.
1348 * NOTE: we assume we are already switched into CacheMemoryContext.
1351 formrdesc(const char *relationName
, Oid relationReltype
,
1352 bool hasoids
, int natts
, FormData_pg_attribute
*att
)
1359 * allocate new relation desc, clear all fields of reldesc
1361 relation
= (Relation
) palloc0(sizeof(RelationData
));
1362 relation
->rd_targblock
= InvalidBlockNumber
;
1363 relation
->rd_fsm_nblocks
= InvalidBlockNumber
;
1364 relation
->rd_vm_nblocks
= InvalidBlockNumber
;
1366 /* make sure relation is marked as having no open file yet */
1367 relation
->rd_smgr
= NULL
;
1370 * initialize reference count: 1 because it is nailed in cache
1372 relation
->rd_refcnt
= 1;
1375 * all entries built with this routine are nailed-in-cache; none are for
1376 * new or temp relations.
1378 relation
->rd_isnailed
= true;
1379 relation
->rd_createSubid
= InvalidSubTransactionId
;
1380 relation
->rd_newRelfilenodeSubid
= InvalidSubTransactionId
;
1381 relation
->rd_istemp
= false;
1382 relation
->rd_islocaltemp
= false;
1385 * initialize relation tuple form
1387 * The data we insert here is pretty incomplete/bogus, but it'll serve to
1388 * get us launched. RelationCacheInitializePhase2() will read the real
1389 * data from pg_class and replace what we've done here.
1391 relation
->rd_rel
= (Form_pg_class
) palloc0(CLASS_TUPLE_SIZE
);
1393 namestrcpy(&relation
->rd_rel
->relname
, relationName
);
1394 relation
->rd_rel
->relnamespace
= PG_CATALOG_NAMESPACE
;
1395 relation
->rd_rel
->reltype
= relationReltype
;
1398 * It's important to distinguish between shared and non-shared relations,
1399 * even at bootstrap time, to make sure we know where they are stored. At
1400 * present, all relations that formrdesc is used for are not shared.
1402 relation
->rd_rel
->relisshared
= false;
1405 * Likewise, we must know if a relation is temp ... but formrdesc is not
1406 * used for any temp relations.
1408 relation
->rd_rel
->relistemp
= false;
1410 relation
->rd_rel
->relpages
= 1;
1411 relation
->rd_rel
->reltuples
= 1;
1412 relation
->rd_rel
->relkind
= RELKIND_RELATION
;
1413 relation
->rd_rel
->relhasoids
= hasoids
;
1414 relation
->rd_rel
->relnatts
= (int16
) natts
;
1417 * initialize attribute tuple form
1419 * Unlike the case with the relation tuple, this data had better be right
1420 * because it will never be replaced. The input values must be correctly
1421 * defined by macros in src/include/catalog/ headers.
1423 relation
->rd_att
= CreateTemplateTupleDesc(natts
, hasoids
);
1424 relation
->rd_att
->tdrefcount
= 1; /* mark as refcounted */
1426 relation
->rd_att
->tdtypeid
= relationReltype
;
1427 relation
->rd_att
->tdtypmod
= -1; /* unnecessary, but... */
1430 * initialize tuple desc info
1432 has_not_null
= false;
1433 for (i
= 0; i
< natts
; i
++)
1435 memcpy(relation
->rd_att
->attrs
[i
],
1437 ATTRIBUTE_FIXED_PART_SIZE
);
1438 has_not_null
|= att
[i
].attnotnull
;
1439 /* make sure attcacheoff is valid */
1440 relation
->rd_att
->attrs
[i
]->attcacheoff
= -1;
1443 /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
1444 relation
->rd_att
->attrs
[0]->attcacheoff
= 0;
1446 /* mark not-null status */
1449 TupleConstr
*constr
= (TupleConstr
*) palloc0(sizeof(TupleConstr
));
1451 constr
->has_not_null
= true;
1452 relation
->rd_att
->constr
= constr
;
1456 * initialize relation id from info in att array (my, this is ugly)
1458 RelationGetRelid(relation
) = relation
->rd_att
->attrs
[0]->attrelid
;
1459 relation
->rd_rel
->relfilenode
= RelationGetRelid(relation
);
1462 * initialize the relation lock manager information
1464 RelationInitLockInfo(relation
); /* see lmgr.c */
1467 * initialize physical addressing information for the relation
1469 RelationInitPhysicalAddr(relation
);
1472 * initialize the rel-has-index flag, using hardwired knowledge
1474 if (IsBootstrapProcessingMode())
1476 /* In bootstrap mode, we have no indexes */
1477 relation
->rd_rel
->relhasindex
= false;
1481 /* Otherwise, all the rels formrdesc is used for have indexes */
1482 relation
->rd_rel
->relhasindex
= true;
1486 * add new reldesc to relcache
1488 RelationCacheInsert(relation
);
1490 /* It's fully valid */
1491 relation
->rd_isvalid
= true;
1495 /* ----------------------------------------------------------------
1496 * Relation Descriptor Lookup Interface
1497 * ----------------------------------------------------------------
1501 * RelationIdGetRelation
1503 * Lookup a reldesc by OID; make one if not already in cache.
1505 * Returns NULL if no pg_class row could be found for the given relid
1506 * (suggesting we are trying to access a just-deleted relation).
1507 * Any other error is reported via elog.
1509 * NB: caller should already have at least AccessShareLock on the
1510 * relation ID, else there are nasty race conditions.
1512 * NB: relation ref count is incremented, or set to 1 if new entry.
1513 * Caller should eventually decrement count. (Usually,
1514 * that happens by calling RelationClose().)
1517 RelationIdGetRelation(Oid relationId
)
1522 * first try to find reldesc in the cache
1524 RelationIdCacheLookup(relationId
, rd
);
1526 if (RelationIsValid(rd
))
1528 RelationIncrementReferenceCount(rd
);
1529 /* revalidate nailed index if necessary */
1530 if (!rd
->rd_isvalid
)
1531 RelationReloadIndexInfo(rd
);
1536 * no reldesc in the cache, so have RelationBuildDesc() build one and add
1539 rd
= RelationBuildDesc(relationId
, NULL
);
1540 if (RelationIsValid(rd
))
1541 RelationIncrementReferenceCount(rd
);
1545 /* ----------------------------------------------------------------
1546 * cache invalidation support routines
1547 * ----------------------------------------------------------------
1551 * RelationIncrementReferenceCount
1552 * Increments relation reference count.
1554 * Note: bootstrap mode has its own weird ideas about relation refcount
1555 * behavior; we ought to fix it someday, but for now, just disable
1556 * reference count ownership tracking in bootstrap mode.
1559 RelationIncrementReferenceCount(Relation rel
)
1561 ResourceOwnerEnlargeRelationRefs(CurrentResourceOwner
);
1562 rel
->rd_refcnt
+= 1;
1563 if (!IsBootstrapProcessingMode())
1564 ResourceOwnerRememberRelationRef(CurrentResourceOwner
, rel
);
1568 * RelationDecrementReferenceCount
1569 * Decrements relation reference count.
1572 RelationDecrementReferenceCount(Relation rel
)
1574 Assert(rel
->rd_refcnt
> 0);
1575 rel
->rd_refcnt
-= 1;
1576 if (!IsBootstrapProcessingMode())
1577 ResourceOwnerForgetRelationRef(CurrentResourceOwner
, rel
);
1581 * RelationClose - close an open relation
1583 * Actually, we just decrement the refcount.
1585 * NOTE: if compiled with -DRELCACHE_FORCE_RELEASE then relcache entries
1586 * will be freed as soon as their refcount goes to zero. In combination
1587 * with aset.c's CLOBBER_FREED_MEMORY option, this provides a good test
1588 * to catch references to already-released relcache entries. It slows
1589 * things down quite a bit, however.
1592 RelationClose(Relation relation
)
1594 /* Note: no locking manipulations needed */
1595 RelationDecrementReferenceCount(relation
);
1597 #ifdef RELCACHE_FORCE_RELEASE
1598 if (RelationHasReferenceCountZero(relation
) &&
1599 relation
->rd_createSubid
== InvalidSubTransactionId
&&
1600 relation
->rd_newRelfilenodeSubid
== InvalidSubTransactionId
)
1601 RelationClearRelation(relation
, false);
1606 * RelationReloadIndexInfo - reload minimal information for an open index
1608 * This function is used only for indexes. A relcache inval on an index
1609 * can mean that its pg_class or pg_index row changed. There are only
1610 * very limited changes that are allowed to an existing index's schema,
1611 * so we can update the relcache entry without a complete rebuild; which
1612 * is fortunate because we can't rebuild an index entry that is "nailed"
1613 * and/or in active use. We support full replacement of the pg_class row,
1614 * as well as updates of a few simple fields of the pg_index row.
1616 * We can't necessarily reread the catalog rows right away; we might be
1617 * in a failed transaction when we receive the SI notification. If so,
1618 * RelationClearRelation just marks the entry as invalid by setting
1619 * rd_isvalid to false. This routine is called to fix the entry when it
1622 * We assume that at the time we are called, we have at least AccessShareLock
1623 * on the target index. (Note: in the calls from RelationClearRelation,
1624 * this is legitimate because we know the rel has positive refcount.)
1627 RelationReloadIndexInfo(Relation relation
)
1630 HeapTuple pg_class_tuple
;
1633 /* Should be called only for invalidated indexes */
1634 Assert(relation
->rd_rel
->relkind
== RELKIND_INDEX
&&
1635 !relation
->rd_isvalid
);
1636 /* Should be closed at smgr level */
1637 Assert(relation
->rd_smgr
== NULL
);
1640 * Read the pg_class row
1642 * Don't try to use an indexscan of pg_class_oid_index to reload the info
1643 * for pg_class_oid_index ...
1645 indexOK
= (RelationGetRelid(relation
) != ClassOidIndexId
);
1646 pg_class_tuple
= ScanPgRelation(RelationGetRelid(relation
), indexOK
);
1647 if (!HeapTupleIsValid(pg_class_tuple
))
1648 elog(ERROR
, "could not find pg_class tuple for index %u",
1649 RelationGetRelid(relation
));
1650 relp
= (Form_pg_class
) GETSTRUCT(pg_class_tuple
);
1651 memcpy(relation
->rd_rel
, relp
, CLASS_TUPLE_SIZE
);
1652 /* Reload reloptions in case they changed */
1653 if (relation
->rd_options
)
1654 pfree(relation
->rd_options
);
1655 RelationParseRelOptions(relation
, pg_class_tuple
);
1656 /* done with pg_class tuple */
1657 heap_freetuple(pg_class_tuple
);
1658 /* We must recalculate physical address in case it changed */
1659 RelationInitPhysicalAddr(relation
);
1662 * Must reset targblock, fsm_nblocks and vm_nblocks in case rel was
1665 relation
->rd_targblock
= InvalidBlockNumber
;
1666 relation
->rd_fsm_nblocks
= InvalidBlockNumber
;
1667 relation
->rd_vm_nblocks
= InvalidBlockNumber
;
1668 /* Must free any AM cached data, too */
1669 if (relation
->rd_amcache
)
1670 pfree(relation
->rd_amcache
);
1671 relation
->rd_amcache
= NULL
;
1674 * For a non-system index, there are fields of the pg_index row that are
1675 * allowed to change, so re-read that row and update the relcache entry.
1676 * Most of the info derived from pg_index (such as support function lookup
1677 * info) cannot change, and indeed the whole point of this routine is to
1678 * update the relcache entry without clobbering that data; so wholesale
1679 * replacement is not appropriate.
1681 if (!IsSystemRelation(relation
))
1684 Form_pg_index index
;
1686 tuple
= SearchSysCache(INDEXRELID
,
1687 ObjectIdGetDatum(RelationGetRelid(relation
)),
1689 if (!HeapTupleIsValid(tuple
))
1690 elog(ERROR
, "cache lookup failed for index %u",
1691 RelationGetRelid(relation
));
1692 index
= (Form_pg_index
) GETSTRUCT(tuple
);
1694 relation
->rd_index
->indisvalid
= index
->indisvalid
;
1695 relation
->rd_index
->indcheckxmin
= index
->indcheckxmin
;
1696 relation
->rd_index
->indisready
= index
->indisready
;
1697 HeapTupleHeaderSetXmin(relation
->rd_indextuple
->t_data
,
1698 HeapTupleHeaderGetXmin(tuple
->t_data
));
1700 ReleaseSysCache(tuple
);
1703 /* Okay, now it's valid again */
1704 relation
->rd_isvalid
= true;
1708 * RelationClearRelation
1710 * Physically blow away a relation cache entry, or reset it and rebuild
1711 * it from scratch (that is, from catalog entries). The latter path is
1712 * usually used when we are notified of a change to an open relation
1713 * (one with refcount > 0). However, this routine just does whichever
1714 * it's told to do; callers must determine which they want.
1716 * NB: when rebuilding, we'd better hold some lock on the relation.
1717 * In current usages this is presumed true because it has refcnt > 0.
1720 RelationClearRelation(Relation relation
, bool rebuild
)
1722 Oid old_reltype
= relation
->rd_rel
->reltype
;
1723 MemoryContext oldcxt
;
1726 * Make sure smgr and lower levels close the relation's files, if they
1727 * weren't closed already. If the relation is not getting deleted, the
1728 * next smgr access should reopen the files automatically. This ensures
1729 * that the low-level file access state is updated after, say, a vacuum
1732 RelationCloseSmgr(relation
);
1735 * Never, never ever blow away a nailed-in system relation, because we'd
1736 * be unable to recover. However, we must reset rd_targblock, in case we
1737 * got called because of a relation cache flush that was triggered by
1740 * If it's a nailed index, then we need to re-read the pg_class row to see
1741 * if its relfilenode changed. We can't necessarily do that here, because
1742 * we might be in a failed transaction. We assume it's okay to do it if
1743 * there are open references to the relcache entry (cf notes for
1744 * AtEOXact_RelationCache). Otherwise just mark the entry as possibly
1745 * invalid, and it'll be fixed when next opened.
1747 if (relation
->rd_isnailed
)
1749 relation
->rd_targblock
= InvalidBlockNumber
;
1750 relation
->rd_fsm_nblocks
= InvalidBlockNumber
;
1751 relation
->rd_vm_nblocks
= InvalidBlockNumber
;
1752 if (relation
->rd_rel
->relkind
== RELKIND_INDEX
)
1754 relation
->rd_isvalid
= false; /* needs to be revalidated */
1755 if (relation
->rd_refcnt
> 1)
1756 RelationReloadIndexInfo(relation
);
1762 * Even non-system indexes should not be blown away if they are open and
1763 * have valid index support information. This avoids problems with active
1764 * use of the index support information. As with nailed indexes, we
1765 * re-read the pg_class row to handle possible physical relocation of the
1766 * index, and we check for pg_index updates too.
1768 if (relation
->rd_rel
->relkind
== RELKIND_INDEX
&&
1769 relation
->rd_refcnt
> 0 &&
1770 relation
->rd_indexcxt
!= NULL
)
1772 relation
->rd_isvalid
= false; /* needs to be revalidated */
1773 RelationReloadIndexInfo(relation
);
1778 * Remove relation from hash tables
1780 * Note: we might be reinserting it momentarily, but we must not have it
1781 * visible in the hash tables until it's valid again, so don't try to
1782 * optimize this away...
1784 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
1785 RelationCacheDelete(relation
);
1786 MemoryContextSwitchTo(oldcxt
);
1788 /* Clear out catcache's entries for this relation */
1789 CatalogCacheFlushRelation(RelationGetRelid(relation
));
1792 * Free all the subsidiary data structures of the relcache entry. We
1793 * cannot free rd_att if we are trying to rebuild the entry, however,
1794 * because pointers to it may be cached in various places. The rule
1795 * manager might also have pointers into the rewrite rules. So to begin
1796 * with, we can only get rid of these fields:
1798 FreeTriggerDesc(relation
->trigdesc
);
1799 if (relation
->rd_indextuple
)
1800 pfree(relation
->rd_indextuple
);
1801 if (relation
->rd_am
)
1802 pfree(relation
->rd_am
);
1803 if (relation
->rd_rel
)
1804 pfree(relation
->rd_rel
);
1805 if (relation
->rd_options
)
1806 pfree(relation
->rd_options
);
1807 list_free(relation
->rd_indexlist
);
1808 bms_free(relation
->rd_indexattr
);
1809 if (relation
->rd_indexcxt
)
1810 MemoryContextDelete(relation
->rd_indexcxt
);
1813 * If we're really done with the relcache entry, blow it away. But if
1814 * someone is still using it, reconstruct the whole deal without moving
1815 * the physical RelationData record (so that the someone's pointer is
1820 /* ok to zap remaining substructure */
1821 flush_rowtype_cache(old_reltype
);
1822 /* can't use DecrTupleDescRefCount here */
1823 Assert(relation
->rd_att
->tdrefcount
> 0);
1824 if (--relation
->rd_att
->tdrefcount
== 0)
1825 FreeTupleDesc(relation
->rd_att
);
1826 if (relation
->rd_rulescxt
)
1827 MemoryContextDelete(relation
->rd_rulescxt
);
1833 * When rebuilding an open relcache entry, must preserve ref count and
1834 * rd_createSubid/rd_newRelfilenodeSubid state. Also attempt to
1835 * preserve the tupledesc and rewrite-rule substructures in place.
1836 * (Note: the refcount mechanism for tupledescs may eventually ensure
1837 * that we don't really need to preserve the tupledesc in-place, but
1838 * for now there are still a lot of places that assume an open rel's
1839 * tupledesc won't move.)
1841 * Note that this process does not touch CurrentResourceOwner; which
1842 * is good because whatever ref counts the entry may have do not
1843 * necessarily belong to that resource owner.
1845 Oid save_relid
= RelationGetRelid(relation
);
1846 int old_refcnt
= relation
->rd_refcnt
;
1847 SubTransactionId old_createSubid
= relation
->rd_createSubid
;
1848 SubTransactionId old_newRelfilenodeSubid
= relation
->rd_newRelfilenodeSubid
;
1849 struct PgStat_TableStatus
*old_pgstat_info
= relation
->pgstat_info
;
1850 TupleDesc old_att
= relation
->rd_att
;
1851 RuleLock
*old_rules
= relation
->rd_rules
;
1852 MemoryContext old_rulescxt
= relation
->rd_rulescxt
;
1854 if (RelationBuildDesc(save_relid
, relation
) != relation
)
1856 /* Should only get here if relation was deleted */
1857 flush_rowtype_cache(old_reltype
);
1858 Assert(old_att
->tdrefcount
> 0);
1859 if (--old_att
->tdrefcount
== 0)
1860 FreeTupleDesc(old_att
);
1862 MemoryContextDelete(old_rulescxt
);
1864 elog(ERROR
, "relation %u deleted while still in use", save_relid
);
1866 relation
->rd_refcnt
= old_refcnt
;
1867 relation
->rd_createSubid
= old_createSubid
;
1868 relation
->rd_newRelfilenodeSubid
= old_newRelfilenodeSubid
;
1869 relation
->pgstat_info
= old_pgstat_info
;
1871 if (equalTupleDescs(old_att
, relation
->rd_att
))
1873 /* needn't flush typcache here */
1874 Assert(relation
->rd_att
->tdrefcount
== 1);
1875 if (--relation
->rd_att
->tdrefcount
== 0)
1876 FreeTupleDesc(relation
->rd_att
);
1877 relation
->rd_att
= old_att
;
1881 flush_rowtype_cache(old_reltype
);
1882 Assert(old_att
->tdrefcount
> 0);
1883 if (--old_att
->tdrefcount
== 0)
1884 FreeTupleDesc(old_att
);
1886 if (equalRuleLocks(old_rules
, relation
->rd_rules
))
1888 if (relation
->rd_rulescxt
)
1889 MemoryContextDelete(relation
->rd_rulescxt
);
1890 relation
->rd_rules
= old_rules
;
1891 relation
->rd_rulescxt
= old_rulescxt
;
1896 MemoryContextDelete(old_rulescxt
);
1902 * RelationFlushRelation
1904 * Rebuild the relation if it is open (refcount > 0), else blow it away.
1907 RelationFlushRelation(Relation relation
)
1911 if (relation
->rd_createSubid
!= InvalidSubTransactionId
||
1912 relation
->rd_newRelfilenodeSubid
!= InvalidSubTransactionId
)
1915 * New relcache entries are always rebuilt, not flushed; else we'd
1916 * forget the "new" status of the relation, which is a useful
1917 * optimization to have. Ditto for the new-relfilenode status.
1924 * Pre-existing rels can be dropped from the relcache if not open.
1926 rebuild
= !RelationHasReferenceCountZero(relation
);
1929 RelationClearRelation(relation
, rebuild
);
1933 * RelationForgetRelation - unconditionally remove a relcache entry
1935 * External interface for destroying a relcache entry when we
1936 * drop the relation.
1939 RelationForgetRelation(Oid rid
)
1943 RelationIdCacheLookup(rid
, relation
);
1945 if (!PointerIsValid(relation
))
1946 return; /* not in cache, nothing to do */
1948 if (!RelationHasReferenceCountZero(relation
))
1949 elog(ERROR
, "relation %u is still open", rid
);
1951 /* Unconditionally destroy the relcache entry */
1952 RelationClearRelation(relation
, false);
1956 * RelationCacheInvalidateEntry
1958 * This routine is invoked for SI cache flush messages.
1960 * Any relcache entry matching the relid must be flushed. (Note: caller has
1961 * already determined that the relid belongs to our database or is a shared
1964 * We used to skip local relations, on the grounds that they could
1965 * not be targets of cross-backend SI update messages; but it seems
1966 * safer to process them, so that our *own* SI update messages will
1967 * have the same effects during CommandCounterIncrement for both
1968 * local and nonlocal relations.
1971 RelationCacheInvalidateEntry(Oid relationId
)
1975 RelationIdCacheLookup(relationId
, relation
);
1977 if (PointerIsValid(relation
))
1979 relcacheInvalsReceived
++;
1980 RelationFlushRelation(relation
);
1985 * RelationCacheInvalidate
1986 * Blow away cached relation descriptors that have zero reference counts,
1987 * and rebuild those with positive reference counts. Also reset the smgr
1990 * This is currently used only to recover from SI message buffer overflow,
1991 * so we do not touch new-in-transaction relations; they cannot be targets
1992 * of cross-backend SI updates (and our own updates now go through a
1993 * separate linked list that isn't limited by the SI message buffer size).
1994 * Likewise, we need not discard new-relfilenode-in-transaction hints,
1995 * since any invalidation of those would be a local event.
1997 * We do this in two phases: the first pass deletes deletable items, and
1998 * the second one rebuilds the rebuildable items. This is essential for
1999 * safety, because hash_seq_search only copes with concurrent deletion of
2000 * the element it is currently visiting. If a second SI overflow were to
2001 * occur while we are walking the table, resulting in recursive entry to
2002 * this routine, we could crash because the inner invocation blows away
2003 * the entry next to be visited by the outer scan. But this way is OK,
2004 * because (a) during the first pass we won't process any more SI messages,
2005 * so hash_seq_search will complete safely; (b) during the second pass we
2006 * only hold onto pointers to nondeletable entries.
2008 * The two-phase approach also makes it easy to ensure that we process
2009 * nailed-in-cache indexes before other nondeletable items, and that we
2010 * process pg_class_oid_index first of all. In scenarios where a nailed
2011 * index has been given a new relfilenode, we have to detect that update
2012 * before the nailed index is used in reloading any other relcache entry.
2015 RelationCacheInvalidate(void)
2017 HASH_SEQ_STATUS status
;
2018 RelIdCacheEnt
*idhentry
;
2020 List
*rebuildFirstList
= NIL
;
2021 List
*rebuildList
= NIL
;
2025 hash_seq_init(&status
, RelationIdCache
);
2027 while ((idhentry
= (RelIdCacheEnt
*) hash_seq_search(&status
)) != NULL
)
2029 relation
= idhentry
->reldesc
;
2031 /* Must close all smgr references to avoid leaving dangling ptrs */
2032 RelationCloseSmgr(relation
);
2034 /* Ignore new relations, since they are never SI targets */
2035 if (relation
->rd_createSubid
!= InvalidSubTransactionId
)
2038 relcacheInvalsReceived
++;
2040 if (RelationHasReferenceCountZero(relation
))
2042 /* Delete this entry immediately */
2043 Assert(!relation
->rd_isnailed
);
2044 RelationClearRelation(relation
, false);
2049 * Add this entry to list of stuff to rebuild in second pass.
2050 * pg_class_oid_index goes on the front of rebuildFirstList, other
2051 * nailed indexes on the back, and everything else into
2052 * rebuildList (in no particular order).
2054 if (relation
->rd_isnailed
&&
2055 relation
->rd_rel
->relkind
== RELKIND_INDEX
)
2057 if (RelationGetRelid(relation
) == ClassOidIndexId
)
2058 rebuildFirstList
= lcons(relation
, rebuildFirstList
);
2060 rebuildFirstList
= lappend(rebuildFirstList
, relation
);
2063 rebuildList
= lcons(relation
, rebuildList
);
2068 * Now zap any remaining smgr cache entries. This must happen before we
2069 * start to rebuild entries, since that may involve catalog fetches which
2070 * will re-open catalog files.
2074 /* Phase 2: rebuild the items found to need rebuild in phase 1 */
2075 foreach(l
, rebuildFirstList
)
2077 relation
= (Relation
) lfirst(l
);
2078 RelationClearRelation(relation
, true);
2080 list_free(rebuildFirstList
);
2081 foreach(l
, rebuildList
)
2083 relation
= (Relation
) lfirst(l
);
2084 RelationClearRelation(relation
, true);
2086 list_free(rebuildList
);
2090 * AtEOXact_RelationCache
2092 * Clean up the relcache at main-transaction commit or abort.
2094 * Note: this must be called *before* processing invalidation messages.
2095 * In the case of abort, we don't want to try to rebuild any invalidated
2096 * cache entries (since we can't safely do database accesses). Therefore
2097 * we must reset refcnts before handling pending invalidations.
2099 * As of PostgreSQL 8.1, relcache refcnts should get released by the
2100 * ResourceOwner mechanism. This routine just does a debugging
2101 * cross-check that no pins remain. However, we also need to do special
2102 * cleanup when the current transaction created any relations or made use
2103 * of forced index lists.
2106 AtEOXact_RelationCache(bool isCommit
)
2108 HASH_SEQ_STATUS status
;
2109 RelIdCacheEnt
*idhentry
;
2112 * To speed up transaction exit, we want to avoid scanning the relcache
2113 * unless there is actually something for this routine to do. Other than
2114 * the debug-only Assert checks, most transactions don't create any work
2115 * for us to do here, so we keep a static flag that gets set if there is
2116 * anything to do. (Currently, this means either a relation is created in
2117 * the current xact, or one is given a new relfilenode, or an index list
2118 * is forced.) For simplicity, the flag remains set till end of top-level
2119 * transaction, even though we could clear it at subtransaction end in
2122 if (!need_eoxact_work
2123 #ifdef USE_ASSERT_CHECKING
2129 hash_seq_init(&status
, RelationIdCache
);
2131 while ((idhentry
= (RelIdCacheEnt
*) hash_seq_search(&status
)) != NULL
)
2133 Relation relation
= idhentry
->reldesc
;
2136 * The relcache entry's ref count should be back to its normal
2137 * not-in-a-transaction state: 0 unless it's nailed in cache.
2139 * In bootstrap mode, this is NOT true, so don't check it --- the
2140 * bootstrap code expects relations to stay open across start/commit
2141 * transaction calls. (That seems bogus, but it's not worth fixing.)
2143 #ifdef USE_ASSERT_CHECKING
2144 if (!IsBootstrapProcessingMode())
2146 int expected_refcnt
;
2148 expected_refcnt
= relation
->rd_isnailed
? 1 : 0;
2149 Assert(relation
->rd_refcnt
== expected_refcnt
);
2154 * Is it a relation created in the current transaction?
2156 * During commit, reset the flag to zero, since we are now out of the
2157 * creating transaction. During abort, simply delete the relcache
2158 * entry --- it isn't interesting any longer. (NOTE: if we have
2159 * forgotten the new-ness of a new relation due to a forced cache
2160 * flush, the entry will get deleted anyway by shared-cache-inval
2161 * processing of the aborted pg_class insertion.)
2163 if (relation
->rd_createSubid
!= InvalidSubTransactionId
)
2166 relation
->rd_createSubid
= InvalidSubTransactionId
;
2169 RelationClearRelation(relation
, false);
2175 * Likewise, reset the hint about the relfilenode being new.
2177 relation
->rd_newRelfilenodeSubid
= InvalidSubTransactionId
;
2180 * Flush any temporary index list.
2182 if (relation
->rd_indexvalid
== 2)
2184 list_free(relation
->rd_indexlist
);
2185 relation
->rd_indexlist
= NIL
;
2186 relation
->rd_oidindex
= InvalidOid
;
2187 relation
->rd_indexvalid
= 0;
2191 /* Once done with the transaction, we can reset need_eoxact_work */
2192 need_eoxact_work
= false;
2196 * AtEOSubXact_RelationCache
2198 * Clean up the relcache at sub-transaction commit or abort.
2200 * Note: this must be called *before* processing invalidation messages.
2203 AtEOSubXact_RelationCache(bool isCommit
, SubTransactionId mySubid
,
2204 SubTransactionId parentSubid
)
2206 HASH_SEQ_STATUS status
;
2207 RelIdCacheEnt
*idhentry
;
2210 * Skip the relcache scan if nothing to do --- see notes for
2211 * AtEOXact_RelationCache.
2213 if (!need_eoxact_work
)
2216 hash_seq_init(&status
, RelationIdCache
);
2218 while ((idhentry
= (RelIdCacheEnt
*) hash_seq_search(&status
)) != NULL
)
2220 Relation relation
= idhentry
->reldesc
;
2223 * Is it a relation created in the current subtransaction?
2225 * During subcommit, mark it as belonging to the parent, instead.
2226 * During subabort, simply delete the relcache entry.
2228 if (relation
->rd_createSubid
== mySubid
)
2231 relation
->rd_createSubid
= parentSubid
;
2234 Assert(RelationHasReferenceCountZero(relation
));
2235 RelationClearRelation(relation
, false);
2241 * Likewise, update or drop any new-relfilenode-in-subtransaction
2244 if (relation
->rd_newRelfilenodeSubid
== mySubid
)
2247 relation
->rd_newRelfilenodeSubid
= parentSubid
;
2249 relation
->rd_newRelfilenodeSubid
= InvalidSubTransactionId
;
2253 * Flush any temporary index list.
2255 if (relation
->rd_indexvalid
== 2)
2257 list_free(relation
->rd_indexlist
);
2258 relation
->rd_indexlist
= NIL
;
2259 relation
->rd_oidindex
= InvalidOid
;
2260 relation
->rd_indexvalid
= 0;
2266 * RelationCacheMarkNewRelfilenode
2268 * Mark the rel as having been given a new relfilenode in the current
2269 * (sub) transaction. This is a hint that can be used to optimize
2270 * later operations on the rel in the same transaction.
2273 RelationCacheMarkNewRelfilenode(Relation rel
)
2276 rel
->rd_newRelfilenodeSubid
= GetCurrentSubTransactionId();
2277 /* ... and now we have eoxact cleanup work to do */
2278 need_eoxact_work
= true;
2283 * RelationBuildLocalRelation
2284 * Build a relcache entry for an about-to-be-created relation,
2285 * and enter it into the relcache.
2288 RelationBuildLocalRelation(const char *relname
,
2293 bool shared_relation
)
2296 MemoryContext oldcxt
;
2297 int natts
= tupDesc
->natts
;
2302 AssertArg(natts
>= 0);
2305 * check for creation of a rel that must be nailed in cache.
2307 * XXX this list had better match RelationCacheInitializePhase2's list.
2311 case RelationRelationId
:
2312 case AttributeRelationId
:
2313 case ProcedureRelationId
:
2314 case TypeRelationId
:
2323 * check that hardwired list of shared rels matches what's in the
2324 * bootstrap .bki file. If you get a failure here during initdb, you
2325 * probably need to fix IsSharedRelation() to match whatever you've done
2326 * to the set of shared relations.
2328 if (shared_relation
!= IsSharedRelation(relid
))
2329 elog(ERROR
, "shared_relation flag for \"%s\" does not match IsSharedRelation(%u)",
2333 * switch to the cache context to create the relcache entry.
2335 if (!CacheMemoryContext
)
2336 CreateCacheMemoryContext();
2338 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
2341 * allocate a new relation descriptor and fill in basic state fields.
2343 rel
= (Relation
) palloc0(sizeof(RelationData
));
2345 rel
->rd_targblock
= InvalidBlockNumber
;
2346 rel
->rd_fsm_nblocks
= InvalidBlockNumber
;
2347 rel
->rd_vm_nblocks
= InvalidBlockNumber
;
2349 /* make sure relation is marked as having no open file yet */
2350 rel
->rd_smgr
= NULL
;
2352 /* mark it nailed if appropriate */
2353 rel
->rd_isnailed
= nailit
;
2355 rel
->rd_refcnt
= nailit
? 1 : 0;
2357 /* it's being created in this transaction */
2358 rel
->rd_createSubid
= GetCurrentSubTransactionId();
2359 rel
->rd_newRelfilenodeSubid
= InvalidSubTransactionId
;
2361 /* must flag that we have rels created in this transaction */
2362 need_eoxact_work
= true;
2364 /* it is temporary if and only if it is in my temp-table namespace */
2365 rel
->rd_istemp
= isTempOrToastNamespace(relnamespace
);
2366 rel
->rd_islocaltemp
= rel
->rd_istemp
;
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
;
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
;
2413 rel
->rd_rel
->relistemp
= rel
->rd_istemp
;
2415 RelationGetRelid(rel
) = relid
;
2417 for (i
= 0; i
< natts
; i
++)
2418 rel
->rd_att
->attrs
[i
]->attrelid
= relid
;
2420 rel
->rd_rel
->relfilenode
= relid
;
2421 rel
->rd_rel
->reltablespace
= reltablespace
;
2423 RelationInitLockInfo(rel
); /* see lmgr.c */
2425 RelationInitPhysicalAddr(rel
);
2428 * Okay to insert into the relcache hash tables.
2430 RelationCacheInsert(rel
);
2433 * done building relcache entry.
2435 MemoryContextSwitchTo(oldcxt
);
2437 /* It's fully valid */
2438 rel
->rd_isvalid
= true;
2441 * Caller expects us to pin the returned entry.
2443 RelationIncrementReferenceCount(rel
);
2449 * RelationCacheInitialize
2451 * This initializes the relation descriptor cache. At the time
2452 * that this is invoked, we can't do database access yet (mainly
2453 * because the transaction subsystem is not up); all we are doing
2454 * is making an empty cache hashtable. This must be done before
2455 * starting the initialization transaction, because otherwise
2456 * AtEOXact_RelationCache would crash if that transaction aborts
2457 * before we can get the relcache set up.
2460 #define INITRELCACHESIZE 400
2463 RelationCacheInitialize(void)
2465 MemoryContext oldcxt
;
2469 * switch to cache memory context
2471 if (!CacheMemoryContext
)
2472 CreateCacheMemoryContext();
2474 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
2477 * create hashtable that indexes the relcache
2479 MemSet(&ctl
, 0, sizeof(ctl
));
2480 ctl
.keysize
= sizeof(Oid
);
2481 ctl
.entrysize
= sizeof(RelIdCacheEnt
);
2482 ctl
.hash
= oid_hash
;
2483 RelationIdCache
= hash_create("Relcache by OID", INITRELCACHESIZE
,
2484 &ctl
, HASH_ELEM
| HASH_FUNCTION
);
2486 MemoryContextSwitchTo(oldcxt
);
2490 * RelationCacheInitializePhase2
2492 * This is called as soon as the catcache and transaction system
2493 * are functional. At this point we can actually read data from
2494 * the system catalogs. We first try to read pre-computed relcache
2495 * entries from the pg_internal.init file. If that's missing or
2496 * broken, make phony entries for the minimum set of nailed-in-cache
2497 * relations. Then (unless bootstrapping) make sure we have entries
2498 * for the critical system indexes. Once we've done all this, we
2499 * have enough infrastructure to open any system catalog or use any
2500 * catcache. The last step is to rewrite pg_internal.init if needed.
2503 RelationCacheInitializePhase2(void)
2505 HASH_SEQ_STATUS status
;
2506 RelIdCacheEnt
*idhentry
;
2507 MemoryContext oldcxt
;
2508 bool needNewCacheFile
= false;
2511 * switch to cache memory context
2513 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
2516 * Try to load the relcache cache file. If unsuccessful, bootstrap the
2517 * cache with pre-made descriptors for the critical "nailed-in" system
2520 if (IsBootstrapProcessingMode() ||
2521 !load_relcache_init_file())
2523 needNewCacheFile
= true;
2525 formrdesc("pg_class", PG_CLASS_RELTYPE_OID
,
2526 true, Natts_pg_class
, Desc_pg_class
);
2527 formrdesc("pg_attribute", PG_ATTRIBUTE_RELTYPE_OID
,
2528 false, Natts_pg_attribute
, Desc_pg_attribute
);
2529 formrdesc("pg_proc", PG_PROC_RELTYPE_OID
,
2530 true, Natts_pg_proc
, Desc_pg_proc
);
2531 formrdesc("pg_type", PG_TYPE_RELTYPE_OID
,
2532 true, Natts_pg_type
, Desc_pg_type
);
2534 #define NUM_CRITICAL_RELS 4 /* fix if you change list above */
2537 MemoryContextSwitchTo(oldcxt
);
2539 /* In bootstrap mode, the faked-up formrdesc info is all we'll have */
2540 if (IsBootstrapProcessingMode())
2544 * If we didn't get the critical system indexes loaded into relcache, do
2545 * so now. These are critical because the catcache and/or opclass cache
2546 * depend on them for fetches done during relcache load. Thus, we have an
2547 * infinite-recursion problem. We can break the recursion by doing
2548 * heapscans instead of indexscans at certain key spots. To avoid hobbling
2549 * performance, we only want to do that until we have the critical indexes
2550 * loaded into relcache. Thus, the flag criticalRelcachesBuilt is used to
2551 * decide whether to do heapscan or indexscan at the key spots, and we set
2552 * it true after we've loaded the critical indexes.
2554 * The critical indexes are marked as "nailed in cache", partly to make it
2555 * easy for load_relcache_init_file to count them, but mainly because we
2556 * cannot flush and rebuild them once we've set criticalRelcachesBuilt to
2557 * true. (NOTE: perhaps it would be possible to reload them by
2558 * temporarily setting criticalRelcachesBuilt to false again. For now,
2559 * though, we just nail 'em in.)
2561 * RewriteRelRulenameIndexId and TriggerRelidNameIndexId are not critical
2562 * in the same way as the others, because the critical catalogs don't
2563 * (currently) have any rules or triggers, and so these indexes can be
2564 * rebuilt without inducing recursion. However they are used during
2565 * relcache load when a rel does have rules or triggers, so we choose to
2566 * nail them for performance reasons.
2568 if (!criticalRelcachesBuilt
)
2572 #define LOAD_CRIT_INDEX(indexoid) \
2574 LockRelationOid(indexoid, AccessShareLock); \
2575 ird = RelationBuildDesc(indexoid, NULL); \
2577 elog(PANIC, "could not open critical system index %u", \
2579 ird->rd_isnailed = true; \
2580 ird->rd_refcnt = 1; \
2581 UnlockRelationOid(indexoid, AccessShareLock); \
2584 LOAD_CRIT_INDEX(ClassOidIndexId
);
2585 LOAD_CRIT_INDEX(AttributeRelidNumIndexId
);
2586 LOAD_CRIT_INDEX(IndexRelidIndexId
);
2587 LOAD_CRIT_INDEX(OpclassOidIndexId
);
2588 LOAD_CRIT_INDEX(AccessMethodStrategyIndexId
);
2589 LOAD_CRIT_INDEX(AccessMethodProcedureIndexId
);
2590 LOAD_CRIT_INDEX(OperatorOidIndexId
);
2591 LOAD_CRIT_INDEX(RewriteRelRulenameIndexId
);
2592 LOAD_CRIT_INDEX(TriggerRelidNameIndexId
);
2594 #define NUM_CRITICAL_INDEXES 9 /* fix if you change list above */
2596 criticalRelcachesBuilt
= true;
2600 * Now, scan all the relcache entries and update anything that might be
2601 * wrong in the results from formrdesc or the relcache cache file. If we
2602 * faked up relcache entries using formrdesc, then read the real pg_class
2603 * rows and replace the fake entries with them. Also, if any of the
2604 * relcache entries have rules or triggers, load that info the hard way
2605 * since it isn't recorded in the cache file.
2607 hash_seq_init(&status
, RelationIdCache
);
2609 while ((idhentry
= (RelIdCacheEnt
*) hash_seq_search(&status
)) != NULL
)
2611 Relation relation
= idhentry
->reldesc
;
2614 * If it's a faked-up entry, read the real pg_class tuple.
2616 if (needNewCacheFile
&& relation
->rd_isnailed
)
2621 htup
= SearchSysCache(RELOID
,
2622 ObjectIdGetDatum(RelationGetRelid(relation
)),
2624 if (!HeapTupleIsValid(htup
))
2625 elog(FATAL
, "cache lookup failed for relation %u",
2626 RelationGetRelid(relation
));
2627 relp
= (Form_pg_class
) GETSTRUCT(htup
);
2630 * Copy tuple to relation->rd_rel. (See notes in
2631 * AllocateRelationDesc())
2633 Assert(relation
->rd_rel
!= NULL
);
2634 memcpy((char *) relation
->rd_rel
, (char *) relp
, CLASS_TUPLE_SIZE
);
2636 /* Update rd_options while we have the tuple */
2637 if (relation
->rd_options
)
2638 pfree(relation
->rd_options
);
2639 RelationParseRelOptions(relation
, htup
);
2642 * Also update the derived fields in rd_att.
2644 relation
->rd_att
->tdtypeid
= relp
->reltype
;
2645 relation
->rd_att
->tdtypmod
= -1; /* unnecessary, but... */
2646 relation
->rd_att
->tdhasoid
= relp
->relhasoids
;
2648 ReleaseSysCache(htup
);
2652 * Fix data that isn't saved in relcache cache file.
2654 if (relation
->rd_rel
->relhasrules
&& relation
->rd_rules
== NULL
)
2655 RelationBuildRuleLock(relation
);
2656 if (relation
->rd_rel
->relhastriggers
&& relation
->trigdesc
== NULL
)
2657 RelationBuildTriggers(relation
);
2661 * Lastly, write out a new relcache cache file if one is needed.
2663 if (needNewCacheFile
)
2666 * Force all the catcaches to finish initializing and thereby open the
2667 * catalogs and indexes they use. This will preload the relcache with
2668 * entries for all the most important system catalogs and indexes, so
2669 * that the init file will be most useful for future backends.
2671 InitCatalogCachePhase2();
2673 /* now write the file */
2674 write_relcache_init_file();
2679 * GetPgClassDescriptor -- get a predefined tuple descriptor for pg_class
2680 * GetPgIndexDescriptor -- get a predefined tuple descriptor for pg_index
2682 * We need this kluge because we have to be able to access non-fixed-width
2683 * fields of pg_class and pg_index before we have the standard catalog caches
2684 * available. We use predefined data that's set up in just the same way as
2685 * the bootstrapped reldescs used by formrdesc(). The resulting tupdesc is
2686 * not 100% kosher: it does not have the correct rowtype OID in tdtypeid, nor
2687 * does it have a TupleConstr field. But it's good enough for the purpose of
2688 * extracting fields.
2691 BuildHardcodedDescriptor(int natts
, Form_pg_attribute attrs
, bool hasoids
)
2694 MemoryContext oldcxt
;
2697 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
2699 result
= CreateTemplateTupleDesc(natts
, hasoids
);
2700 result
->tdtypeid
= RECORDOID
; /* not right, but we don't care */
2701 result
->tdtypmod
= -1;
2703 for (i
= 0; i
< natts
; i
++)
2705 memcpy(result
->attrs
[i
], &attrs
[i
], ATTRIBUTE_FIXED_PART_SIZE
);
2706 /* make sure attcacheoff is valid */
2707 result
->attrs
[i
]->attcacheoff
= -1;
2710 /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
2711 result
->attrs
[0]->attcacheoff
= 0;
2713 /* Note: we don't bother to set up a TupleConstr entry */
2715 MemoryContextSwitchTo(oldcxt
);
2721 GetPgClassDescriptor(void)
2723 static TupleDesc pgclassdesc
= NULL
;
2726 if (pgclassdesc
== NULL
)
2727 pgclassdesc
= BuildHardcodedDescriptor(Natts_pg_class
,
2735 GetPgIndexDescriptor(void)
2737 static TupleDesc pgindexdesc
= NULL
;
2740 if (pgindexdesc
== NULL
)
2741 pgindexdesc
= BuildHardcodedDescriptor(Natts_pg_index
,
2749 AttrDefaultFetch(Relation relation
)
2751 AttrDefault
*attrdef
= relation
->rd_att
->constr
->defval
;
2752 int ndef
= relation
->rd_att
->constr
->num_defval
;
2763 Anum_pg_attrdef_adrelid
,
2764 BTEqualStrategyNumber
, F_OIDEQ
,
2765 ObjectIdGetDatum(RelationGetRelid(relation
)));
2767 adrel
= heap_open(AttrDefaultRelationId
, AccessShareLock
);
2768 adscan
= systable_beginscan(adrel
, AttrDefaultIndexId
, true,
2769 SnapshotNow
, 1, &skey
);
2772 while (HeapTupleIsValid(htup
= systable_getnext(adscan
)))
2774 Form_pg_attrdef adform
= (Form_pg_attrdef
) GETSTRUCT(htup
);
2776 for (i
= 0; i
< ndef
; i
++)
2778 if (adform
->adnum
!= attrdef
[i
].adnum
)
2780 if (attrdef
[i
].adbin
!= NULL
)
2781 elog(WARNING
, "multiple attrdef records found for attr %s of rel %s",
2782 NameStr(relation
->rd_att
->attrs
[adform
->adnum
- 1]->attname
),
2783 RelationGetRelationName(relation
));
2787 val
= fastgetattr(htup
,
2788 Anum_pg_attrdef_adbin
,
2789 adrel
->rd_att
, &isnull
);
2791 elog(WARNING
, "null adbin for attr %s of rel %s",
2792 NameStr(relation
->rd_att
->attrs
[adform
->adnum
- 1]->attname
),
2793 RelationGetRelationName(relation
));
2795 attrdef
[i
].adbin
= MemoryContextStrdup(CacheMemoryContext
,
2796 TextDatumGetCString(val
));
2801 elog(WARNING
, "unexpected attrdef record found for attr %d of rel %s",
2802 adform
->adnum
, RelationGetRelationName(relation
));
2805 systable_endscan(adscan
);
2806 heap_close(adrel
, AccessShareLock
);
2809 elog(WARNING
, "%d attrdef record(s) missing for rel %s",
2810 ndef
- found
, RelationGetRelationName(relation
));
2814 CheckConstraintFetch(Relation relation
)
2816 ConstrCheck
*check
= relation
->rd_att
->constr
->check
;
2817 int ncheck
= relation
->rd_att
->constr
->num_check
;
2819 SysScanDesc conscan
;
2820 ScanKeyData skey
[1];
2826 ScanKeyInit(&skey
[0],
2827 Anum_pg_constraint_conrelid
,
2828 BTEqualStrategyNumber
, F_OIDEQ
,
2829 ObjectIdGetDatum(RelationGetRelid(relation
)));
2831 conrel
= heap_open(ConstraintRelationId
, AccessShareLock
);
2832 conscan
= systable_beginscan(conrel
, ConstraintRelidIndexId
, true,
2833 SnapshotNow
, 1, skey
);
2835 while (HeapTupleIsValid(htup
= systable_getnext(conscan
)))
2837 Form_pg_constraint conform
= (Form_pg_constraint
) GETSTRUCT(htup
);
2839 /* We want check constraints only */
2840 if (conform
->contype
!= CONSTRAINT_CHECK
)
2843 if (found
>= ncheck
)
2844 elog(ERROR
, "unexpected constraint record found for rel %s",
2845 RelationGetRelationName(relation
));
2847 check
[found
].ccname
= MemoryContextStrdup(CacheMemoryContext
,
2848 NameStr(conform
->conname
));
2850 /* Grab and test conbin is actually set */
2851 val
= fastgetattr(htup
,
2852 Anum_pg_constraint_conbin
,
2853 conrel
->rd_att
, &isnull
);
2855 elog(ERROR
, "null conbin for rel %s",
2856 RelationGetRelationName(relation
));
2858 check
[found
].ccbin
= MemoryContextStrdup(CacheMemoryContext
,
2859 TextDatumGetCString(val
));
2863 systable_endscan(conscan
);
2864 heap_close(conrel
, AccessShareLock
);
2866 if (found
!= ncheck
)
2867 elog(ERROR
, "%d constraint record(s) missing for rel %s",
2868 ncheck
- found
, RelationGetRelationName(relation
));
2872 * RelationGetIndexList -- get a list of OIDs of indexes on this relation
2874 * The index list is created only if someone requests it. We scan pg_index
2875 * to find relevant indexes, and add the list to the relcache entry so that
2876 * we won't have to compute it again. Note that shared cache inval of a
2877 * relcache entry will delete the old list and set rd_indexvalid to 0,
2878 * so that we must recompute the index list on next request. This handles
2879 * creation or deletion of an index.
2881 * The returned list is guaranteed to be sorted in order by OID. This is
2882 * needed by the executor, since for index types that we obtain exclusive
2883 * locks on when updating the index, all backends must lock the indexes in
2884 * the same order or we will get deadlocks (see ExecOpenIndices()). Any
2885 * consistent ordering would do, but ordering by OID is easy.
2887 * Since shared cache inval causes the relcache's copy of the list to go away,
2888 * we return a copy of the list palloc'd in the caller's context. The caller
2889 * may list_free() the returned list after scanning it. This is necessary
2890 * since the caller will typically be doing syscache lookups on the relevant
2891 * indexes, and syscache lookup could cause SI messages to be processed!
2893 * We also update rd_oidindex, which this module treats as effectively part
2894 * of the index list. rd_oidindex is valid when rd_indexvalid isn't zero;
2895 * it is the pg_class OID of a unique index on OID when the relation has one,
2896 * and InvalidOid if there is no such index.
2899 RelationGetIndexList(Relation relation
)
2902 SysScanDesc indscan
;
2907 MemoryContext oldcxt
;
2909 /* Quick exit if we already computed the list. */
2910 if (relation
->rd_indexvalid
!= 0)
2911 return list_copy(relation
->rd_indexlist
);
2914 * We build the list we intend to return (in the caller's context) while
2915 * doing the scan. After successfully completing the scan, we copy that
2916 * list into the relcache entry. This avoids cache-context memory leakage
2917 * if we get some sort of error partway through.
2920 oidIndex
= InvalidOid
;
2922 /* Prepare to scan pg_index for entries having indrelid = this rel. */
2924 Anum_pg_index_indrelid
,
2925 BTEqualStrategyNumber
, F_OIDEQ
,
2926 ObjectIdGetDatum(RelationGetRelid(relation
)));
2928 indrel
= heap_open(IndexRelationId
, AccessShareLock
);
2929 indscan
= systable_beginscan(indrel
, IndexIndrelidIndexId
, true,
2930 SnapshotNow
, 1, &skey
);
2932 while (HeapTupleIsValid(htup
= systable_getnext(indscan
)))
2934 Form_pg_index index
= (Form_pg_index
) GETSTRUCT(htup
);
2936 /* Add index's OID to result list in the proper order */
2937 result
= insert_ordered_oid(result
, index
->indexrelid
);
2939 /* Check to see if it is a unique, non-partial btree index on OID */
2940 if (index
->indnatts
== 1 &&
2941 index
->indisunique
&&
2942 index
->indkey
.values
[0] == ObjectIdAttributeNumber
&&
2943 index
->indclass
.values
[0] == OID_BTREE_OPS_OID
&&
2944 heap_attisnull(htup
, Anum_pg_index_indpred
))
2945 oidIndex
= index
->indexrelid
;
2948 systable_endscan(indscan
);
2949 heap_close(indrel
, AccessShareLock
);
2951 /* Now save a copy of the completed list in the relcache entry. */
2952 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
2953 relation
->rd_indexlist
= list_copy(result
);
2954 relation
->rd_oidindex
= oidIndex
;
2955 relation
->rd_indexvalid
= 1;
2956 MemoryContextSwitchTo(oldcxt
);
2962 * insert_ordered_oid
2963 * Insert a new Oid into a sorted list of Oids, preserving ordering
2965 * Building the ordered list this way is O(N^2), but with a pretty small
2966 * constant, so for the number of entries we expect it will probably be
2967 * faster than trying to apply qsort(). Most tables don't have very many
2971 insert_ordered_oid(List
*list
, Oid datum
)
2975 /* Does the datum belong at the front? */
2976 if (list
== NIL
|| datum
< linitial_oid(list
))
2977 return lcons_oid(datum
, list
);
2978 /* No, so find the entry it belongs after */
2979 prev
= list_head(list
);
2982 ListCell
*curr
= lnext(prev
);
2984 if (curr
== NULL
|| datum
< lfirst_oid(curr
))
2985 break; /* it belongs after 'prev', before 'curr' */
2989 /* Insert datum into list after 'prev' */
2990 lappend_cell_oid(list
, prev
, datum
);
2995 * RelationSetIndexList -- externally force the index list contents
2997 * This is used to temporarily override what we think the set of valid
2998 * indexes is (including the presence or absence of an OID index).
2999 * The forcing will be valid only until transaction commit or abort.
3001 * This should only be applied to nailed relations, because in a non-nailed
3002 * relation the hacked index list could be lost at any time due to SI
3003 * messages. In practice it is only used on pg_class (see REINDEX).
3005 * It is up to the caller to make sure the given list is correctly ordered.
3007 * We deliberately do not change rd_indexattr here: even when operating
3008 * with a temporary partial index list, HOT-update decisions must be made
3009 * correctly with respect to the full index set. It is up to the caller
3010 * to ensure that a correct rd_indexattr set has been cached before first
3011 * calling RelationSetIndexList; else a subsequent inquiry might cause a
3012 * wrong rd_indexattr set to get computed and cached.
3015 RelationSetIndexList(Relation relation
, List
*indexIds
, Oid oidIndex
)
3017 MemoryContext oldcxt
;
3019 Assert(relation
->rd_isnailed
);
3020 /* Copy the list into the cache context (could fail for lack of mem) */
3021 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
3022 indexIds
= list_copy(indexIds
);
3023 MemoryContextSwitchTo(oldcxt
);
3024 /* Okay to replace old list */
3025 list_free(relation
->rd_indexlist
);
3026 relation
->rd_indexlist
= indexIds
;
3027 relation
->rd_oidindex
= oidIndex
;
3028 relation
->rd_indexvalid
= 2; /* mark list as forced */
3029 /* must flag that we have a forced index list */
3030 need_eoxact_work
= true;
3034 * RelationGetOidIndex -- get the pg_class OID of the relation's OID index
3036 * Returns InvalidOid if there is no such index.
3039 RelationGetOidIndex(Relation relation
)
3044 * If relation doesn't have OIDs at all, caller is probably confused. (We
3045 * could just silently return InvalidOid, but it seems better to throw an
3048 Assert(relation
->rd_rel
->relhasoids
);
3050 if (relation
->rd_indexvalid
== 0)
3052 /* RelationGetIndexList does the heavy lifting. */
3053 ilist
= RelationGetIndexList(relation
);
3055 Assert(relation
->rd_indexvalid
!= 0);
3058 return relation
->rd_oidindex
;
3062 * RelationGetIndexExpressions -- get the index expressions for an index
3064 * We cache the result of transforming pg_index.indexprs into a node tree.
3065 * If the rel is not an index or has no expressional columns, we return NIL.
3066 * Otherwise, the returned tree is copied into the caller's memory context.
3067 * (We don't want to return a pointer to the relcache copy, since it could
3068 * disappear due to relcache invalidation.)
3071 RelationGetIndexExpressions(Relation relation
)
3077 MemoryContext oldcxt
;
3079 /* Quick exit if we already computed the result. */
3080 if (relation
->rd_indexprs
)
3081 return (List
*) copyObject(relation
->rd_indexprs
);
3083 /* Quick exit if there is nothing to do. */
3084 if (relation
->rd_indextuple
== NULL
||
3085 heap_attisnull(relation
->rd_indextuple
, Anum_pg_index_indexprs
))
3089 * We build the tree we intend to return in the caller's context. After
3090 * successfully completing the work, we copy it into the relcache entry.
3091 * This avoids problems if we get some sort of error partway through.
3093 exprsDatum
= heap_getattr(relation
->rd_indextuple
,
3094 Anum_pg_index_indexprs
,
3095 GetPgIndexDescriptor(),
3098 exprsString
= TextDatumGetCString(exprsDatum
);
3099 result
= (List
*) stringToNode(exprsString
);
3103 * Run the expressions through eval_const_expressions. This is not just an
3104 * optimization, but is necessary, because the planner will be comparing
3105 * them to similarly-processed qual clauses, and may fail to detect valid
3106 * matches without this. We don't bother with canonicalize_qual, however.
3108 result
= (List
*) eval_const_expressions(NULL
, (Node
*) result
);
3111 * Also mark any coercion format fields as "don't care", so that the
3112 * planner can match to both explicit and implicit coercions.
3114 set_coercionform_dontcare((Node
*) result
);
3116 /* May as well fix opfuncids too */
3117 fix_opfuncids((Node
*) result
);
3119 /* Now save a copy of the completed tree in the relcache entry. */
3120 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
3121 relation
->rd_indexprs
= (List
*) copyObject(result
);
3122 MemoryContextSwitchTo(oldcxt
);
3128 * RelationGetIndexPredicate -- get the index predicate for an index
3130 * We cache the result of transforming pg_index.indpred into an implicit-AND
3131 * node tree (suitable for ExecQual).
3132 * If the rel is not an index or has no predicate, we return NIL.
3133 * Otherwise, the returned tree is copied into the caller's memory context.
3134 * (We don't want to return a pointer to the relcache copy, since it could
3135 * disappear due to relcache invalidation.)
3138 RelationGetIndexPredicate(Relation relation
)
3144 MemoryContext oldcxt
;
3146 /* Quick exit if we already computed the result. */
3147 if (relation
->rd_indpred
)
3148 return (List
*) copyObject(relation
->rd_indpred
);
3150 /* Quick exit if there is nothing to do. */
3151 if (relation
->rd_indextuple
== NULL
||
3152 heap_attisnull(relation
->rd_indextuple
, Anum_pg_index_indpred
))
3156 * We build the tree we intend to return in the caller's context. After
3157 * successfully completing the work, we copy it into the relcache entry.
3158 * This avoids problems if we get some sort of error partway through.
3160 predDatum
= heap_getattr(relation
->rd_indextuple
,
3161 Anum_pg_index_indpred
,
3162 GetPgIndexDescriptor(),
3165 predString
= TextDatumGetCString(predDatum
);
3166 result
= (List
*) stringToNode(predString
);
3170 * Run the expression through const-simplification and canonicalization.
3171 * This is not just an optimization, but is necessary, because the planner
3172 * will be comparing it to similarly-processed qual clauses, and may fail
3173 * to detect valid matches without this. This must match the processing
3174 * done to qual clauses in preprocess_expression()! (We can skip the
3175 * stuff involving subqueries, however, since we don't allow any in index
3178 result
= (List
*) eval_const_expressions(NULL
, (Node
*) result
);
3180 result
= (List
*) canonicalize_qual((Expr
*) result
);
3183 * Also mark any coercion format fields as "don't care", so that the
3184 * planner can match to both explicit and implicit coercions.
3186 set_coercionform_dontcare((Node
*) result
);
3188 /* Also convert to implicit-AND format */
3189 result
= make_ands_implicit((Expr
*) result
);
3191 /* May as well fix opfuncids too */
3192 fix_opfuncids((Node
*) result
);
3194 /* Now save a copy of the completed tree in the relcache entry. */
3195 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
3196 relation
->rd_indpred
= (List
*) copyObject(result
);
3197 MemoryContextSwitchTo(oldcxt
);
3203 * RelationGetIndexAttrBitmap -- get a bitmap of index attribute numbers
3205 * The result has a bit set for each attribute used anywhere in the index
3206 * definitions of all the indexes on this relation. (This includes not only
3207 * simple index keys, but attributes used in expressions and partial-index
3210 * Attribute numbers are offset by FirstLowInvalidHeapAttributeNumber so that
3211 * we can include system attributes (e.g., OID) in the bitmap representation.
3213 * The returned result is palloc'd in the caller's memory context and should
3214 * be bms_free'd when not needed anymore.
3217 RelationGetIndexAttrBitmap(Relation relation
)
3219 Bitmapset
*indexattrs
;
3222 MemoryContext oldcxt
;
3224 /* Quick exit if we already computed the result. */
3225 if (relation
->rd_indexattr
!= NULL
)
3226 return bms_copy(relation
->rd_indexattr
);
3228 /* Fast path if definitely no indexes */
3229 if (!RelationGetForm(relation
)->relhasindex
)
3233 * Get cached list of index OIDs
3235 indexoidlist
= RelationGetIndexList(relation
);
3237 /* Fall out if no indexes (but relhasindex was set) */
3238 if (indexoidlist
== NIL
)
3242 * For each index, add referenced attributes to indexattrs.
3245 foreach(l
, indexoidlist
)
3247 Oid indexOid
= lfirst_oid(l
);
3249 IndexInfo
*indexInfo
;
3252 indexDesc
= index_open(indexOid
, AccessShareLock
);
3254 /* Extract index key information from the index's pg_index row */
3255 indexInfo
= BuildIndexInfo(indexDesc
);
3257 /* Collect simple attribute references */
3258 for (i
= 0; i
< indexInfo
->ii_NumIndexAttrs
; i
++)
3260 int attrnum
= indexInfo
->ii_KeyAttrNumbers
[i
];
3263 indexattrs
= bms_add_member(indexattrs
,
3264 attrnum
- FirstLowInvalidHeapAttributeNumber
);
3267 /* Collect all attributes used in expressions, too */
3268 pull_varattnos((Node
*) indexInfo
->ii_Expressions
, &indexattrs
);
3270 /* Collect all attributes in the index predicate, too */
3271 pull_varattnos((Node
*) indexInfo
->ii_Predicate
, &indexattrs
);
3273 index_close(indexDesc
, AccessShareLock
);
3276 list_free(indexoidlist
);
3278 /* Now save a copy of the bitmap in the relcache entry. */
3279 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
3280 relation
->rd_indexattr
= bms_copy(indexattrs
);
3281 MemoryContextSwitchTo(oldcxt
);
3283 /* We return our original working copy for caller to play with */
3289 * load_relcache_init_file, write_relcache_init_file
3291 * In late 1992, we started regularly having databases with more than
3292 * a thousand classes in them. With this number of classes, it became
3293 * critical to do indexed lookups on the system catalogs.
3295 * Bootstrapping these lookups is very hard. We want to be able to
3296 * use an index on pg_attribute, for example, but in order to do so,
3297 * we must have read pg_attribute for the attributes in the index,
3298 * which implies that we need to use the index.
3300 * In order to get around the problem, we do the following:
3302 * + When the database system is initialized (at initdb time), we
3303 * don't use indexes. We do sequential scans.
3305 * + When the backend is started up in normal mode, we load an image
3306 * of the appropriate relation descriptors, in internal format,
3307 * from an initialization file in the data/base/... directory.
3309 * + If the initialization file isn't there, then we create the
3310 * relation descriptors using sequential scans and write 'em to
3311 * the initialization file for use by subsequent backends.
3313 * We could dispense with the initialization file and just build the
3314 * critical reldescs the hard way on every backend startup, but that
3315 * slows down backend startup noticeably.
3317 * We can in fact go further, and save more relcache entries than
3318 * just the ones that are absolutely critical; this allows us to speed
3319 * up backend startup by not having to build such entries the hard way.
3320 * Presently, all the catalog and index entries that are referred to
3321 * by catcaches are stored in the initialization file.
3323 * The same mechanism that detects when catcache and relcache entries
3324 * need to be invalidated (due to catalog updates) also arranges to
3325 * unlink the initialization file when its contents may be out of date.
3326 * The file will then be rebuilt during the next backend startup.
3330 * load_relcache_init_file -- attempt to load cache from the init file
3332 * If successful, return TRUE and set criticalRelcachesBuilt to true.
3333 * If not successful, return FALSE.
3335 * NOTE: we assume we are already switched into CacheMemoryContext.
3338 load_relcache_init_file(void)
3341 char initfilename
[MAXPGPATH
];
3351 snprintf(initfilename
, sizeof(initfilename
), "%s/%s",
3352 DatabasePath
, RELCACHE_INIT_FILENAME
);
3354 fp
= AllocateFile(initfilename
, PG_BINARY_R
);
3359 * Read the index relcache entries from the file. Note we will not enter
3360 * any of them into the cache if the read fails partway through; this
3361 * helps to guard against broken init files.
3364 rels
= (Relation
*) palloc(max_rels
* sizeof(Relation
));
3366 nailed_rels
= nailed_indexes
= 0;
3367 initFileRelationIds
= NIL
;
3369 /* check for correct magic number (compatible version) */
3370 if (fread(&magic
, 1, sizeof(magic
), fp
) != sizeof(magic
))
3372 if (magic
!= RELCACHE_INIT_FILEMAGIC
)
3375 for (relno
= 0;; relno
++)
3380 Form_pg_class relform
;
3383 /* first read the relation descriptor length */
3384 if ((nread
= fread(&len
, 1, sizeof(len
), fp
)) != sizeof(len
))
3387 break; /* end of file */
3391 /* safety check for incompatible relcache layout */
3392 if (len
!= sizeof(RelationData
))
3395 /* allocate another relcache header */
3396 if (num_rels
>= max_rels
)
3399 rels
= (Relation
*) repalloc(rels
, max_rels
* sizeof(Relation
));
3402 rel
= rels
[num_rels
++] = (Relation
) palloc(len
);
3404 /* then, read the Relation structure */
3405 if ((nread
= fread(rel
, 1, len
, fp
)) != len
)
3408 /* next read the relation tuple form */
3409 if ((nread
= fread(&len
, 1, sizeof(len
), fp
)) != sizeof(len
))
3412 relform
= (Form_pg_class
) palloc(len
);
3413 if ((nread
= fread(relform
, 1, len
, fp
)) != len
)
3416 rel
->rd_rel
= relform
;
3418 /* initialize attribute tuple forms */
3419 rel
->rd_att
= CreateTemplateTupleDesc(relform
->relnatts
,
3420 relform
->relhasoids
);
3421 rel
->rd_att
->tdrefcount
= 1; /* mark as refcounted */
3423 rel
->rd_att
->tdtypeid
= relform
->reltype
;
3424 rel
->rd_att
->tdtypmod
= -1; /* unnecessary, but... */
3426 /* next read all the attribute tuple form data entries */
3427 has_not_null
= false;
3428 for (i
= 0; i
< relform
->relnatts
; i
++)
3430 if ((nread
= fread(&len
, 1, sizeof(len
), fp
)) != sizeof(len
))
3432 if (len
!= ATTRIBUTE_FIXED_PART_SIZE
)
3434 if ((nread
= fread(rel
->rd_att
->attrs
[i
], 1, len
, fp
)) != len
)
3437 has_not_null
|= rel
->rd_att
->attrs
[i
]->attnotnull
;
3440 /* next read the access method specific field */
3441 if ((nread
= fread(&len
, 1, sizeof(len
), fp
)) != sizeof(len
))
3445 rel
->rd_options
= palloc(len
);
3446 if ((nread
= fread(rel
->rd_options
, 1, len
, fp
)) != len
)
3448 if (len
!= VARSIZE(rel
->rd_options
))
3449 goto read_failed
; /* sanity check */
3453 rel
->rd_options
= NULL
;
3456 /* mark not-null status */
3459 TupleConstr
*constr
= (TupleConstr
*) palloc0(sizeof(TupleConstr
));
3461 constr
->has_not_null
= true;
3462 rel
->rd_att
->constr
= constr
;
3465 /* If it's an index, there's more to do */
3466 if (rel
->rd_rel
->relkind
== RELKIND_INDEX
)
3469 MemoryContext indexcxt
;
3473 RegProcedure
*support
;
3477 /* Count nailed indexes to ensure we have 'em all */
3478 if (rel
->rd_isnailed
)
3481 /* next, read the pg_index tuple */
3482 if ((nread
= fread(&len
, 1, sizeof(len
), fp
)) != sizeof(len
))
3485 rel
->rd_indextuple
= (HeapTuple
) palloc(len
);
3486 if ((nread
= fread(rel
->rd_indextuple
, 1, len
, fp
)) != len
)
3489 /* Fix up internal pointers in the tuple -- see heap_copytuple */
3490 rel
->rd_indextuple
->t_data
= (HeapTupleHeader
) ((char *) rel
->rd_indextuple
+ HEAPTUPLESIZE
);
3491 rel
->rd_index
= (Form_pg_index
) GETSTRUCT(rel
->rd_indextuple
);
3493 /* next, read the access method tuple form */
3494 if ((nread
= fread(&len
, 1, sizeof(len
), fp
)) != sizeof(len
))
3497 am
= (Form_pg_am
) palloc(len
);
3498 if ((nread
= fread(am
, 1, len
, fp
)) != len
)
3503 * prepare index info context --- parameters should match
3504 * RelationInitIndexAccessInfo
3506 indexcxt
= AllocSetContextCreate(CacheMemoryContext
,
3507 RelationGetRelationName(rel
),
3508 ALLOCSET_SMALL_MINSIZE
,
3509 ALLOCSET_SMALL_INITSIZE
,
3510 ALLOCSET_SMALL_MAXSIZE
);
3511 rel
->rd_indexcxt
= indexcxt
;
3513 /* next, read the vector of opfamily OIDs */
3514 if ((nread
= fread(&len
, 1, sizeof(len
), fp
)) != sizeof(len
))
3517 opfamily
= (Oid
*) MemoryContextAlloc(indexcxt
, len
);
3518 if ((nread
= fread(opfamily
, 1, len
, fp
)) != len
)
3521 rel
->rd_opfamily
= opfamily
;
3523 /* next, read the vector of opcintype OIDs */
3524 if ((nread
= fread(&len
, 1, sizeof(len
), fp
)) != sizeof(len
))
3527 opcintype
= (Oid
*) MemoryContextAlloc(indexcxt
, len
);
3528 if ((nread
= fread(opcintype
, 1, len
, fp
)) != len
)
3531 rel
->rd_opcintype
= opcintype
;
3533 /* next, read the vector of operator OIDs */
3534 if ((nread
= fread(&len
, 1, sizeof(len
), fp
)) != sizeof(len
))
3537 operator = (Oid
*) MemoryContextAlloc(indexcxt
, len
);
3538 if ((nread
= fread(operator, 1, len
, fp
)) != len
)
3541 rel
->rd_operator
= operator;
3543 /* next, read the vector of support procedures */
3544 if ((nread
= fread(&len
, 1, sizeof(len
), fp
)) != sizeof(len
))
3546 support
= (RegProcedure
*) MemoryContextAlloc(indexcxt
, len
);
3547 if ((nread
= fread(support
, 1, len
, fp
)) != len
)
3550 rel
->rd_support
= support
;
3552 /* finally, read the vector of indoption values */
3553 if ((nread
= fread(&len
, 1, sizeof(len
), fp
)) != sizeof(len
))
3556 indoption
= (int16
*) MemoryContextAlloc(indexcxt
, len
);
3557 if ((nread
= fread(indoption
, 1, len
, fp
)) != len
)
3560 rel
->rd_indoption
= indoption
;
3562 /* set up zeroed fmgr-info vectors */
3563 rel
->rd_aminfo
= (RelationAmInfo
*)
3564 MemoryContextAllocZero(indexcxt
, sizeof(RelationAmInfo
));
3565 nsupport
= relform
->relnatts
* am
->amsupport
;
3566 rel
->rd_supportinfo
= (FmgrInfo
*)
3567 MemoryContextAllocZero(indexcxt
, nsupport
* sizeof(FmgrInfo
));
3571 /* Count nailed rels to ensure we have 'em all */
3572 if (rel
->rd_isnailed
)
3575 Assert(rel
->rd_index
== NULL
);
3576 Assert(rel
->rd_indextuple
== NULL
);
3577 Assert(rel
->rd_am
== NULL
);
3578 Assert(rel
->rd_indexcxt
== NULL
);
3579 Assert(rel
->rd_aminfo
== NULL
);
3580 Assert(rel
->rd_opfamily
== NULL
);
3581 Assert(rel
->rd_opcintype
== NULL
);
3582 Assert(rel
->rd_operator
== NULL
);
3583 Assert(rel
->rd_support
== NULL
);
3584 Assert(rel
->rd_supportinfo
== NULL
);
3585 Assert(rel
->rd_indoption
== NULL
);
3589 * Rules and triggers are not saved (mainly because the internal
3590 * format is complex and subject to change). They must be rebuilt if
3591 * needed by RelationCacheInitializePhase2. This is not expected to
3592 * be a big performance hit since few system catalogs have such. Ditto
3593 * for index expressions and predicates.
3595 rel
->rd_rules
= NULL
;
3596 rel
->rd_rulescxt
= NULL
;
3597 rel
->trigdesc
= NULL
;
3598 rel
->rd_indexprs
= NIL
;
3599 rel
->rd_indpred
= NIL
;
3602 * Reset transient-state fields in the relcache entry
3604 rel
->rd_smgr
= NULL
;
3605 rel
->rd_targblock
= InvalidBlockNumber
;
3606 rel
->rd_fsm_nblocks
= InvalidBlockNumber
;
3607 rel
->rd_vm_nblocks
= InvalidBlockNumber
;
3608 if (rel
->rd_isnailed
)
3612 rel
->rd_indexvalid
= 0;
3613 rel
->rd_indexlist
= NIL
;
3614 rel
->rd_indexattr
= NULL
;
3615 rel
->rd_oidindex
= InvalidOid
;
3616 rel
->rd_createSubid
= InvalidSubTransactionId
;
3617 rel
->rd_newRelfilenodeSubid
= InvalidSubTransactionId
;
3618 rel
->rd_amcache
= NULL
;
3619 MemSet(&rel
->pgstat_info
, 0, sizeof(rel
->pgstat_info
));
3622 * Recompute lock and physical addressing info. This is needed in
3623 * case the pg_internal.init file was copied from some other database
3624 * by CREATE DATABASE.
3626 RelationInitLockInfo(rel
);
3627 RelationInitPhysicalAddr(rel
);
3631 * We reached the end of the init file without apparent problem. Did we
3632 * get the right number of nailed items? (This is a useful crosscheck in
3633 * case the set of critical rels or indexes changes.)
3635 if (nailed_rels
!= NUM_CRITICAL_RELS
||
3636 nailed_indexes
!= NUM_CRITICAL_INDEXES
)
3640 * OK, all appears well.
3642 * Now insert all the new relcache entries into the cache.
3644 for (relno
= 0; relno
< num_rels
; relno
++)
3646 RelationCacheInsert(rels
[relno
]);
3647 /* also make a list of their OIDs, for RelationIdIsInInitFile */
3648 initFileRelationIds
= lcons_oid(RelationGetRelid(rels
[relno
]),
3649 initFileRelationIds
);
3655 criticalRelcachesBuilt
= true;
3659 * init file is broken, so do it the hard way. We don't bother trying to
3660 * free the clutter we just allocated; it's not in the relcache so it
3671 * Write out a new initialization file with the current contents
3675 write_relcache_init_file(void)
3678 char tempfilename
[MAXPGPATH
];
3679 char finalfilename
[MAXPGPATH
];
3681 HASH_SEQ_STATUS status
;
3682 RelIdCacheEnt
*idhentry
;
3683 MemoryContext oldcxt
;
3687 * We must write a temporary file and rename it into place. Otherwise,
3688 * another backend starting at about the same time might crash trying to
3689 * read the partially-complete file.
3691 snprintf(tempfilename
, sizeof(tempfilename
), "%s/%s.%d",
3692 DatabasePath
, RELCACHE_INIT_FILENAME
, MyProcPid
);
3693 snprintf(finalfilename
, sizeof(finalfilename
), "%s/%s",
3694 DatabasePath
, RELCACHE_INIT_FILENAME
);
3696 unlink(tempfilename
); /* in case it exists w/wrong permissions */
3698 fp
= AllocateFile(tempfilename
, PG_BINARY_W
);
3702 * We used to consider this a fatal error, but we might as well
3703 * continue with backend startup ...
3706 (errcode_for_file_access(),
3707 errmsg("could not create relation-cache initialization file \"%s\": %m",
3709 errdetail("Continuing anyway, but there's something wrong.")));
3714 * Write a magic number to serve as a file version identifier. We can
3715 * change the magic number whenever the relcache layout changes.
3717 magic
= RELCACHE_INIT_FILEMAGIC
;
3718 if (fwrite(&magic
, 1, sizeof(magic
), fp
) != sizeof(magic
))
3719 elog(FATAL
, "could not write init file");
3722 * Write all the reldescs (in no particular order).
3724 hash_seq_init(&status
, RelationIdCache
);
3726 initFileRelationIds
= NIL
;
3728 while ((idhentry
= (RelIdCacheEnt
*) hash_seq_search(&status
)) != NULL
)
3730 Relation rel
= idhentry
->reldesc
;
3731 Form_pg_class relform
= rel
->rd_rel
;
3733 /* first write the relcache entry proper */
3734 write_item(rel
, sizeof(RelationData
), fp
);
3736 /* next write the relation tuple form */
3737 write_item(relform
, CLASS_TUPLE_SIZE
, fp
);
3739 /* next, do all the attribute tuple form data entries */
3740 for (i
= 0; i
< relform
->relnatts
; i
++)
3742 write_item(rel
->rd_att
->attrs
[i
], ATTRIBUTE_FIXED_PART_SIZE
, fp
);
3745 /* next, do the access method specific field */
3746 write_item(rel
->rd_options
,
3747 (rel
->rd_options
? VARSIZE(rel
->rd_options
) : 0),
3750 /* If it's an index, there's more to do */
3751 if (rel
->rd_rel
->relkind
== RELKIND_INDEX
)
3753 Form_pg_am am
= rel
->rd_am
;
3755 /* write the pg_index tuple */
3756 /* we assume this was created by heap_copytuple! */
3757 write_item(rel
->rd_indextuple
,
3758 HEAPTUPLESIZE
+ rel
->rd_indextuple
->t_len
,
3761 /* next, write the access method tuple form */
3762 write_item(am
, sizeof(FormData_pg_am
), fp
);
3764 /* next, write the vector of opfamily OIDs */
3765 write_item(rel
->rd_opfamily
,
3766 relform
->relnatts
* sizeof(Oid
),
3769 /* next, write the vector of opcintype OIDs */
3770 write_item(rel
->rd_opcintype
,
3771 relform
->relnatts
* sizeof(Oid
),
3774 /* next, write the vector of operator OIDs */
3775 write_item(rel
->rd_operator
,
3776 relform
->relnatts
* (am
->amstrategies
* sizeof(Oid
)),
3779 /* next, write the vector of support procedures */
3780 write_item(rel
->rd_support
,
3781 relform
->relnatts
* (am
->amsupport
* sizeof(RegProcedure
)),
3784 /* finally, write the vector of indoption values */
3785 write_item(rel
->rd_indoption
,
3786 relform
->relnatts
* sizeof(int16
),
3790 /* also make a list of their OIDs, for RelationIdIsInInitFile */
3791 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
3792 initFileRelationIds
= lcons_oid(RelationGetRelid(rel
),
3793 initFileRelationIds
);
3794 MemoryContextSwitchTo(oldcxt
);
3798 elog(FATAL
, "could not write init file");
3801 * Now we have to check whether the data we've so painstakingly
3802 * accumulated is already obsolete due to someone else's just-committed
3803 * catalog changes. If so, we just delete the temp file and leave it to
3804 * the next backend to try again. (Our own relcache entries will be
3805 * updated by SI message processing, but we can't be sure whether what we
3806 * wrote out was up-to-date.)
3808 * This mustn't run concurrently with RelationCacheInitFileInvalidate, so
3809 * grab a serialization lock for the duration.
3811 LWLockAcquire(RelCacheInitLock
, LW_EXCLUSIVE
);
3813 /* Make sure we have seen all incoming SI messages */
3814 AcceptInvalidationMessages();
3817 * If we have received any SI relcache invals since backend start, assume
3818 * we may have written out-of-date data.
3820 if (relcacheInvalsReceived
== 0L)
3823 * OK, rename the temp file to its final name, deleting any
3824 * previously-existing init file.
3826 * Note: a failure here is possible under Cygwin, if some other
3827 * backend is holding open an unlinked-but-not-yet-gone init file. So
3828 * treat this as a noncritical failure; just remove the useless temp
3831 if (rename(tempfilename
, finalfilename
) < 0)
3832 unlink(tempfilename
);
3836 /* Delete the already-obsolete temp file */
3837 unlink(tempfilename
);
3840 LWLockRelease(RelCacheInitLock
);
3843 /* write a chunk of data preceded by its length */
3845 write_item(const void *data
, Size len
, FILE *fp
)
3847 if (fwrite(&len
, 1, sizeof(len
), fp
) != sizeof(len
))
3848 elog(FATAL
, "could not write init file");
3849 if (fwrite(data
, 1, len
, fp
) != len
)
3850 elog(FATAL
, "could not write init file");
3854 * Detect whether a given relation (identified by OID) is one of the ones
3855 * we store in the init file.
3857 * Note that we effectively assume that all backends running in a database
3858 * would choose to store the same set of relations in the init file;
3859 * otherwise there are cases where we'd fail to detect the need for an init
3860 * file invalidation. This does not seem likely to be a problem in practice.
3863 RelationIdIsInInitFile(Oid relationId
)
3865 return list_member_oid(initFileRelationIds
, relationId
);
3869 * Invalidate (remove) the init file during commit of a transaction that
3870 * changed one or more of the relation cache entries that are kept in the
3873 * We actually need to remove the init file twice: once just before sending
3874 * the SI messages that include relcache inval for such relations, and once
3875 * just after sending them. The unlink before ensures that a backend that's
3876 * currently starting cannot read the now-obsolete init file and then miss
3877 * the SI messages that will force it to update its relcache entries. (This
3878 * works because the backend startup sequence gets into the PGPROC array before
3879 * trying to load the init file.) The unlink after is to synchronize with a
3880 * backend that may currently be trying to write an init file based on data
3881 * that we've just rendered invalid. Such a backend will see the SI messages,
3882 * but we can't leave the init file sitting around to fool later backends.
3884 * Ignore any failure to unlink the file, since it might not be there if
3885 * no backend has been started since the last removal.
3888 RelationCacheInitFileInvalidate(bool beforeSend
)
3890 char initfilename
[MAXPGPATH
];
3892 snprintf(initfilename
, sizeof(initfilename
), "%s/%s",
3893 DatabasePath
, RELCACHE_INIT_FILENAME
);
3897 /* no interlock needed here */
3898 unlink(initfilename
);
3903 * We need to interlock this against write_relcache_init_file, to
3904 * guard against possibility that someone renames a new-but-
3905 * already-obsolete init file into place just after we unlink. With
3906 * the interlock, it's certain that write_relcache_init_file will
3907 * notice our SI inval message before renaming into place, or else
3908 * that we will execute second and successfully unlink the file.
3910 LWLockAcquire(RelCacheInitLock
, LW_EXCLUSIVE
);
3911 unlink(initfilename
);
3912 LWLockRelease(RelCacheInitLock
);
3917 * Remove the init file for a given database during postmaster startup.
3919 * We used to keep the init file across restarts, but that is unsafe in PITR
3920 * scenarios, and even in simple crash-recovery cases there are windows for
3921 * the init file to become out-of-sync with the database. So now we just
3922 * remove it during startup and expect the first backend launch to rebuild it.
3923 * Of course, this has to happen in each database of the cluster. For
3924 * simplicity this is driven by flatfiles.c, which has to scan pg_database
3928 RelationCacheInitFileRemove(const char *dbPath
)
3930 char initfilename
[MAXPGPATH
];
3932 snprintf(initfilename
, sizeof(initfilename
), "%s/%s",
3933 dbPath
, RELCACHE_INIT_FILENAME
);
3934 unlink(initfilename
);
3935 /* ignore any error, since it might not be there at all */