Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * relcache.c
4 : * POSTGRES relation descriptor cache code
5 : *
6 : * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/utils/cache/relcache.c
12 : *
13 : *-------------------------------------------------------------------------
14 : */
15 : /*
16 : * INTERFACE ROUTINES
17 : * RelationCacheInitialize - initialize relcache (to empty)
18 : * RelationCacheInitializePhase2 - initialize shared-catalog entries
19 : * RelationCacheInitializePhase3 - finish initializing relcache
20 : * RelationIdGetRelation - get a reldesc by relation id
21 : * RelationClose - close an open relation
22 : *
23 : * NOTES
24 : * The following code contains many undocumented hacks. Please be
25 : * careful....
26 : */
27 : #include "postgres.h"
28 :
29 : #include <sys/file.h>
30 : #include <fcntl.h>
31 : #include <unistd.h>
32 :
33 : #include "access/htup_details.h"
34 : #include "access/multixact.h"
35 : #include "access/parallel.h"
36 : #include "access/reloptions.h"
37 : #include "access/sysattr.h"
38 : #include "access/table.h"
39 : #include "access/tableam.h"
40 : #include "access/tupdesc_details.h"
41 : #include "access/xact.h"
42 : #include "catalog/binary_upgrade.h"
43 : #include "catalog/catalog.h"
44 : #include "catalog/indexing.h"
45 : #include "catalog/namespace.h"
46 : #include "catalog/partition.h"
47 : #include "catalog/pg_am.h"
48 : #include "catalog/pg_amproc.h"
49 : #include "catalog/pg_attrdef.h"
50 : #include "catalog/pg_auth_members.h"
51 : #include "catalog/pg_authid.h"
52 : #include "catalog/pg_constraint.h"
53 : #include "catalog/pg_database.h"
54 : #include "catalog/pg_namespace.h"
55 : #include "catalog/pg_opclass.h"
56 : #include "catalog/pg_proc.h"
57 : #include "catalog/pg_publication.h"
58 : #include "catalog/pg_rewrite.h"
59 : #include "catalog/pg_shseclabel.h"
60 : #include "catalog/pg_statistic_ext.h"
61 : #include "catalog/pg_subscription.h"
62 : #include "catalog/pg_tablespace.h"
63 : #include "catalog/pg_trigger.h"
64 : #include "catalog/pg_type.h"
65 : #include "catalog/schemapg.h"
66 : #include "catalog/storage.h"
67 : #include "commands/policy.h"
68 : #include "commands/publicationcmds.h"
69 : #include "commands/trigger.h"
70 : #include "common/int.h"
71 : #include "miscadmin.h"
72 : #include "nodes/makefuncs.h"
73 : #include "nodes/nodeFuncs.h"
74 : #include "optimizer/optimizer.h"
75 : #include "pgstat.h"
76 : #include "rewrite/rewriteDefine.h"
77 : #include "rewrite/rowsecurity.h"
78 : #include "storage/lmgr.h"
79 : #include "storage/smgr.h"
80 : #include "utils/array.h"
81 : #include "utils/builtins.h"
82 : #include "utils/catcache.h"
83 : #include "utils/datum.h"
84 : #include "utils/fmgroids.h"
85 : #include "utils/inval.h"
86 : #include "utils/lsyscache.h"
87 : #include "utils/memutils.h"
88 : #include "utils/relmapper.h"
89 : #include "utils/resowner.h"
90 : #include "utils/snapmgr.h"
91 : #include "utils/syscache.h"
92 :
93 : #define RELCACHE_INIT_FILEMAGIC 0x573266 /* version ID value */
94 :
95 : /*
96 : * Whether to bother checking if relation cache memory needs to be freed
97 : * eagerly. See also RelationBuildDesc() and pg_config_manual.h.
98 : */
99 : #if defined(RECOVER_RELATION_BUILD_MEMORY) && (RECOVER_RELATION_BUILD_MEMORY != 0)
100 : #define MAYBE_RECOVER_RELATION_BUILD_MEMORY 1
101 : #else
102 : #define RECOVER_RELATION_BUILD_MEMORY 0
103 : #ifdef DISCARD_CACHES_ENABLED
104 : #define MAYBE_RECOVER_RELATION_BUILD_MEMORY 1
105 : #endif
106 : #endif
107 :
108 : /*
109 : * hardcoded tuple descriptors, contents generated by genbki.pl
110 : */
111 : static const FormData_pg_attribute Desc_pg_class[Natts_pg_class] = {Schema_pg_class};
112 : static const FormData_pg_attribute Desc_pg_attribute[Natts_pg_attribute] = {Schema_pg_attribute};
113 : static const FormData_pg_attribute Desc_pg_proc[Natts_pg_proc] = {Schema_pg_proc};
114 : static const FormData_pg_attribute Desc_pg_type[Natts_pg_type] = {Schema_pg_type};
115 : static const FormData_pg_attribute Desc_pg_database[Natts_pg_database] = {Schema_pg_database};
116 : static const FormData_pg_attribute Desc_pg_authid[Natts_pg_authid] = {Schema_pg_authid};
117 : static const FormData_pg_attribute Desc_pg_auth_members[Natts_pg_auth_members] = {Schema_pg_auth_members};
118 : static const FormData_pg_attribute Desc_pg_index[Natts_pg_index] = {Schema_pg_index};
119 : static const FormData_pg_attribute Desc_pg_shseclabel[Natts_pg_shseclabel] = {Schema_pg_shseclabel};
120 : static const FormData_pg_attribute Desc_pg_subscription[Natts_pg_subscription] = {Schema_pg_subscription};
121 :
122 : /*
123 : * Hash tables that index the relation cache
124 : *
125 : * We used to index the cache by both name and OID, but now there
126 : * is only an index by OID.
127 : */
128 : typedef struct relidcacheent
129 : {
130 : Oid reloid;
131 : Relation reldesc;
132 : } RelIdCacheEnt;
133 :
134 : static HTAB *RelationIdCache;
135 :
136 : /*
137 : * This flag is false until we have prepared the critical relcache entries
138 : * that are needed to do indexscans on the tables read by relcache building.
139 : */
140 : bool criticalRelcachesBuilt = false;
141 :
142 : /*
143 : * This flag is false until we have prepared the critical relcache entries
144 : * for shared catalogs (which are the tables needed for login).
145 : */
146 : bool criticalSharedRelcachesBuilt = false;
147 :
148 : /*
149 : * This counter counts relcache inval events received since backend startup
150 : * (but only for rels that are actually in cache). Presently, we use it only
151 : * to detect whether data about to be written by write_relcache_init_file()
152 : * might already be obsolete.
153 : */
154 : static long relcacheInvalsReceived = 0L;
155 :
156 : /*
157 : * in_progress_list is a stack of ongoing RelationBuildDesc() calls. CREATE
158 : * INDEX CONCURRENTLY makes catalog changes under ShareUpdateExclusiveLock.
159 : * It critically relies on each backend absorbing those changes no later than
160 : * next transaction start. Hence, RelationBuildDesc() loops until it finishes
161 : * without accepting a relevant invalidation. (Most invalidation consumers
162 : * don't do this.)
163 : */
164 : typedef struct inprogressent
165 : {
166 : Oid reloid; /* OID of relation being built */
167 : bool invalidated; /* whether an invalidation arrived for it */
168 : } InProgressEnt;
169 :
170 : static InProgressEnt *in_progress_list;
171 : static int in_progress_list_len;
172 : static int in_progress_list_maxlen;
173 :
174 : /*
175 : * eoxact_list[] stores the OIDs of relations that (might) need AtEOXact
176 : * cleanup work. This list intentionally has limited size; if it overflows,
177 : * we fall back to scanning the whole hashtable. There is no value in a very
178 : * large list because (1) at some point, a hash_seq_search scan is faster than
179 : * retail lookups, and (2) the value of this is to reduce EOXact work for
180 : * short transactions, which can't have dirtied all that many tables anyway.
181 : * EOXactListAdd() does not bother to prevent duplicate list entries, so the
182 : * cleanup processing must be idempotent.
183 : */
184 : #define MAX_EOXACT_LIST 32
185 : static Oid eoxact_list[MAX_EOXACT_LIST];
186 : static int eoxact_list_len = 0;
187 : static bool eoxact_list_overflowed = false;
188 :
189 : #define EOXactListAdd(rel) \
190 : do { \
191 : if (eoxact_list_len < MAX_EOXACT_LIST) \
192 : eoxact_list[eoxact_list_len++] = (rel)->rd_id; \
193 : else \
194 : eoxact_list_overflowed = true; \
195 : } while (0)
196 :
197 : /*
198 : * EOXactTupleDescArray stores TupleDescs that (might) need AtEOXact
199 : * cleanup work. The array expands as needed; there is no hashtable because
200 : * we don't need to access individual items except at EOXact.
201 : */
202 : static TupleDesc *EOXactTupleDescArray;
203 : static int NextEOXactTupleDescNum = 0;
204 : static int EOXactTupleDescArrayLen = 0;
205 :
206 : /*
207 : * macros to manipulate the lookup hashtable
208 : */
209 : #define RelationCacheInsert(RELATION, replace_allowed) \
210 : do { \
211 : RelIdCacheEnt *hentry; bool found; \
212 : hentry = (RelIdCacheEnt *) hash_search(RelationIdCache, \
213 : &((RELATION)->rd_id), \
214 : HASH_ENTER, &found); \
215 : if (found) \
216 : { \
217 : /* see comments in RelationBuildDesc and RelationBuildLocalRelation */ \
218 : Relation _old_rel = hentry->reldesc; \
219 : Assert(replace_allowed); \
220 : hentry->reldesc = (RELATION); \
221 : if (RelationHasReferenceCountZero(_old_rel)) \
222 : RelationDestroyRelation(_old_rel, false); \
223 : else if (!IsBootstrapProcessingMode()) \
224 : elog(WARNING, "leaking still-referenced relcache entry for \"%s\"", \
225 : RelationGetRelationName(_old_rel)); \
226 : } \
227 : else \
228 : hentry->reldesc = (RELATION); \
229 : } while(0)
230 :
231 : #define RelationIdCacheLookup(ID, RELATION) \
232 : do { \
233 : RelIdCacheEnt *hentry; \
234 : hentry = (RelIdCacheEnt *) hash_search(RelationIdCache, \
235 : &(ID), \
236 : HASH_FIND, NULL); \
237 : if (hentry) \
238 : RELATION = hentry->reldesc; \
239 : else \
240 : RELATION = NULL; \
241 : } while(0)
242 :
243 : #define RelationCacheDelete(RELATION) \
244 : do { \
245 : RelIdCacheEnt *hentry; \
246 : hentry = (RelIdCacheEnt *) hash_search(RelationIdCache, \
247 : &((RELATION)->rd_id), \
248 : HASH_REMOVE, NULL); \
249 : if (hentry == NULL) \
250 : elog(WARNING, "failed to delete relcache entry for OID %u", \
251 : (RELATION)->rd_id); \
252 : } while(0)
253 :
254 :
255 : /*
256 : * Special cache for opclass-related information
257 : *
258 : * Note: only default support procs get cached, ie, those with
259 : * lefttype = righttype = opcintype.
260 : */
261 : typedef struct opclasscacheent
262 : {
263 : Oid opclassoid; /* lookup key: OID of opclass */
264 : bool valid; /* set true after successful fill-in */
265 : StrategyNumber numSupport; /* max # of support procs (from pg_am) */
266 : Oid opcfamily; /* OID of opclass's family */
267 : Oid opcintype; /* OID of opclass's declared input type */
268 : RegProcedure *supportProcs; /* OIDs of support procedures */
269 : } OpClassCacheEnt;
270 :
271 : static HTAB *OpClassCache = NULL;
272 :
273 :
274 : /* non-export function prototypes */
275 :
276 : static void RelationCloseCleanup(Relation relation);
277 : static void RelationDestroyRelation(Relation relation, bool remember_tupdesc);
278 : static void RelationInvalidateRelation(Relation relation);
279 : static void RelationClearRelation(Relation relation);
280 : static void RelationRebuildRelation(Relation relation);
281 :
282 : static void RelationReloadIndexInfo(Relation relation);
283 : static void RelationReloadNailed(Relation relation);
284 : static void RelationFlushRelation(Relation relation);
285 : static void RememberToFreeTupleDescAtEOX(TupleDesc td);
286 : #ifdef USE_ASSERT_CHECKING
287 : static void AssertPendingSyncConsistency(Relation relation);
288 : #endif
289 : static void AtEOXact_cleanup(Relation relation, bool isCommit);
290 : static void AtEOSubXact_cleanup(Relation relation, bool isCommit,
291 : SubTransactionId mySubid, SubTransactionId parentSubid);
292 : static bool load_relcache_init_file(bool shared);
293 : static void write_relcache_init_file(bool shared);
294 : static void write_item(const void *data, Size len, FILE *fp);
295 :
296 : static void formrdesc(const char *relationName, Oid relationReltype,
297 : bool isshared, int natts, const FormData_pg_attribute *attrs);
298 :
299 : static HeapTuple ScanPgRelation(Oid targetRelId, bool indexOK, bool force_non_historic);
300 : static Relation AllocateRelationDesc(Form_pg_class relp);
301 : static void RelationParseRelOptions(Relation relation, HeapTuple tuple);
302 : static void RelationBuildTupleDesc(Relation relation);
303 : static Relation RelationBuildDesc(Oid targetRelId, bool insertIt);
304 : static void RelationInitPhysicalAddr(Relation relation);
305 : static void load_critical_index(Oid indexoid, Oid heapoid);
306 : static TupleDesc GetPgClassDescriptor(void);
307 : static TupleDesc GetPgIndexDescriptor(void);
308 : static void AttrDefaultFetch(Relation relation, int ndef);
309 : static int AttrDefaultCmp(const void *a, const void *b);
310 : static void CheckConstraintFetch(Relation relation);
311 : static int CheckConstraintCmp(const void *a, const void *b);
312 : static void InitIndexAmRoutine(Relation relation);
313 : static void IndexSupportInitialize(oidvector *indclass,
314 : RegProcedure *indexSupport,
315 : Oid *opFamily,
316 : Oid *opcInType,
317 : StrategyNumber maxSupportNumber,
318 : AttrNumber maxAttributeNumber);
319 : static OpClassCacheEnt *LookupOpclassInfo(Oid operatorClassOid,
320 : StrategyNumber numSupport);
321 : static void RelationCacheInitFileRemoveInDir(const char *tblspcpath);
322 : static void unlink_initfile(const char *initfilename, int elevel);
323 :
324 :
325 : /*
326 : * ScanPgRelation
327 : *
328 : * This is used by RelationBuildDesc to find a pg_class
329 : * tuple matching targetRelId. The caller must hold at least
330 : * AccessShareLock on the target relid to prevent concurrent-update
331 : * scenarios; it isn't guaranteed that all scans used to build the
332 : * relcache entry will use the same snapshot. If, for example,
333 : * an attribute were to be added after scanning pg_class and before
334 : * scanning pg_attribute, relnatts wouldn't match.
335 : *
336 : * NB: the returned tuple has been copied into palloc'd storage
337 : * and must eventually be freed with heap_freetuple.
338 : */
339 : static HeapTuple
340 1480152 : ScanPgRelation(Oid targetRelId, bool indexOK, bool force_non_historic)
341 : {
342 : HeapTuple pg_class_tuple;
343 : Relation pg_class_desc;
344 : SysScanDesc pg_class_scan;
345 : ScanKeyData key[1];
346 1480152 : Snapshot snapshot = NULL;
347 :
348 : /*
349 : * If something goes wrong during backend startup, we might find ourselves
350 : * trying to read pg_class before we've selected a database. That ain't
351 : * gonna work, so bail out with a useful error message. If this happens,
352 : * it probably means a relcache entry that needs to be nailed isn't.
353 : */
354 1480152 : if (!OidIsValid(MyDatabaseId))
355 0 : elog(FATAL, "cannot read pg_class without having selected a database");
356 :
357 : /*
358 : * form a scan key
359 : */
360 1480152 : ScanKeyInit(&key[0],
361 : Anum_pg_class_oid,
362 : BTEqualStrategyNumber, F_OIDEQ,
363 : ObjectIdGetDatum(targetRelId));
364 :
365 : /*
366 : * Open pg_class and fetch a tuple. Force heap scan if we haven't yet
367 : * built the critical relcache entries (this includes initdb and startup
368 : * without a pg_internal.init file). The caller can also force a heap
369 : * scan by setting indexOK == false.
370 : */
371 1480152 : pg_class_desc = table_open(RelationRelationId, AccessShareLock);
372 :
373 : /*
374 : * The caller might need a tuple that's newer than the one the historic
375 : * snapshot; currently the only case requiring to do so is looking up the
376 : * relfilenumber of non mapped system relations during decoding. That
377 : * snapshot can't change in the midst of a relcache build, so there's no
378 : * need to register the snapshot.
379 : */
380 1480152 : if (force_non_historic)
381 2736 : snapshot = GetNonHistoricCatalogSnapshot(RelationRelationId);
382 :
383 1480152 : pg_class_scan = systable_beginscan(pg_class_desc, ClassOidIndexId,
384 1480152 : indexOK && criticalRelcachesBuilt,
385 : snapshot,
386 : 1, key);
387 :
388 1480146 : pg_class_tuple = systable_getnext(pg_class_scan);
389 :
390 : /*
391 : * Must copy tuple before releasing buffer.
392 : */
393 1480140 : if (HeapTupleIsValid(pg_class_tuple))
394 1480094 : pg_class_tuple = heap_copytuple(pg_class_tuple);
395 :
396 : /* all done */
397 1480140 : systable_endscan(pg_class_scan);
398 1480140 : table_close(pg_class_desc, AccessShareLock);
399 :
400 1480140 : return pg_class_tuple;
401 : }
402 :
403 : /*
404 : * AllocateRelationDesc
405 : *
406 : * This is used to allocate memory for a new relation descriptor
407 : * and initialize the rd_rel field from the given pg_class tuple.
408 : */
409 : static Relation
410 1340380 : AllocateRelationDesc(Form_pg_class relp)
411 : {
412 : Relation relation;
413 : MemoryContext oldcxt;
414 : Form_pg_class relationForm;
415 :
416 : /* Relcache entries must live in CacheMemoryContext */
417 1340380 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
418 :
419 : /*
420 : * allocate and zero space for new relation descriptor
421 : */
422 1340380 : relation = (Relation) palloc0(sizeof(RelationData));
423 :
424 : /* make sure relation is marked as having no open file yet */
425 1340380 : relation->rd_smgr = NULL;
426 :
427 : /*
428 : * Copy the relation tuple form
429 : *
430 : * We only allocate space for the fixed fields, ie, CLASS_TUPLE_SIZE. The
431 : * variable-length fields (relacl, reloptions) are NOT stored in the
432 : * relcache --- there'd be little point in it, since we don't copy the
433 : * tuple's nulls bitmap and hence wouldn't know if the values are valid.
434 : * Bottom line is that relacl *cannot* be retrieved from the relcache. Get
435 : * it from the syscache if you need it. The same goes for the original
436 : * form of reloptions (however, we do store the parsed form of reloptions
437 : * in rd_options).
438 : */
439 1340380 : relationForm = (Form_pg_class) palloc(CLASS_TUPLE_SIZE);
440 :
441 1340380 : memcpy(relationForm, relp, CLASS_TUPLE_SIZE);
442 :
443 : /* initialize relation tuple form */
444 1340380 : relation->rd_rel = relationForm;
445 :
446 : /* and allocate attribute tuple form storage */
447 1340380 : relation->rd_att = CreateTemplateTupleDesc(relationForm->relnatts);
448 : /* which we mark as a reference-counted tupdesc */
449 1340380 : relation->rd_att->tdrefcount = 1;
450 :
451 1340380 : MemoryContextSwitchTo(oldcxt);
452 :
453 1340380 : return relation;
454 : }
455 :
456 : /*
457 : * RelationParseRelOptions
458 : * Convert pg_class.reloptions into pre-parsed rd_options
459 : *
460 : * tuple is the real pg_class tuple (not rd_rel!) for relation
461 : *
462 : * Note: rd_rel and (if an index) rd_indam must be valid already
463 : */
464 : static void
465 1468440 : RelationParseRelOptions(Relation relation, HeapTuple tuple)
466 : {
467 : bytea *options;
468 : amoptions_function amoptsfn;
469 :
470 1468440 : relation->rd_options = NULL;
471 :
472 : /*
473 : * Look up any AM-specific parse function; fall out if relkind should not
474 : * have options.
475 : */
476 1468440 : switch (relation->rd_rel->relkind)
477 : {
478 825112 : case RELKIND_RELATION:
479 : case RELKIND_TOASTVALUE:
480 : case RELKIND_VIEW:
481 : case RELKIND_MATVIEW:
482 : case RELKIND_PARTITIONED_TABLE:
483 825112 : amoptsfn = NULL;
484 825112 : break;
485 627458 : case RELKIND_INDEX:
486 : case RELKIND_PARTITIONED_INDEX:
487 627458 : amoptsfn = relation->rd_indam->amoptions;
488 627458 : break;
489 15870 : default:
490 15870 : return;
491 : }
492 :
493 : /*
494 : * Fetch reloptions from tuple; have to use a hardwired descriptor because
495 : * we might not have any other for pg_class yet (consider executing this
496 : * code for pg_class itself)
497 : */
498 1452570 : options = extractRelOptions(tuple, GetPgClassDescriptor(), amoptsfn);
499 :
500 : /*
501 : * Copy parsed data into CacheMemoryContext. To guard against the
502 : * possibility of leaks in the reloptions code, we want to do the actual
503 : * parsing in the caller's memory context and copy the results into
504 : * CacheMemoryContext after the fact.
505 : */
506 1452570 : if (options)
507 : {
508 31712 : relation->rd_options = MemoryContextAlloc(CacheMemoryContext,
509 15856 : VARSIZE(options));
510 15856 : memcpy(relation->rd_options, options, VARSIZE(options));
511 15856 : pfree(options);
512 : }
513 : }
514 :
515 : /*
516 : * RelationBuildTupleDesc
517 : *
518 : * Form the relation's tuple descriptor from information in
519 : * the pg_attribute, pg_attrdef & pg_constraint system catalogs.
520 : */
521 : static void
522 1340380 : RelationBuildTupleDesc(Relation relation)
523 : {
524 : HeapTuple pg_attribute_tuple;
525 : Relation pg_attribute_desc;
526 : SysScanDesc pg_attribute_scan;
527 : ScanKeyData skey[2];
528 : int need;
529 : TupleConstr *constr;
530 1340380 : AttrMissing *attrmiss = NULL;
531 1340380 : int ndef = 0;
532 :
533 : /* fill rd_att's type ID fields (compare heap.c's AddNewRelationTuple) */
534 1340380 : relation->rd_att->tdtypeid =
535 1340380 : relation->rd_rel->reltype ? relation->rd_rel->reltype : RECORDOID;
536 1340380 : relation->rd_att->tdtypmod = -1; /* just to be sure */
537 :
538 1340380 : constr = (TupleConstr *) MemoryContextAllocZero(CacheMemoryContext,
539 : sizeof(TupleConstr));
540 :
541 : /*
542 : * Form a scan key that selects only user attributes (attnum > 0).
543 : * (Eliminating system attribute rows at the index level is lots faster
544 : * than fetching them.)
545 : */
546 1340380 : ScanKeyInit(&skey[0],
547 : Anum_pg_attribute_attrelid,
548 : BTEqualStrategyNumber, F_OIDEQ,
549 : ObjectIdGetDatum(RelationGetRelid(relation)));
550 1340380 : ScanKeyInit(&skey[1],
551 : Anum_pg_attribute_attnum,
552 : BTGreaterStrategyNumber, F_INT2GT,
553 : Int16GetDatum(0));
554 :
555 : /*
556 : * Open pg_attribute and begin a scan. Force heap scan if we haven't yet
557 : * built the critical relcache entries (this includes initdb and startup
558 : * without a pg_internal.init file).
559 : */
560 1340380 : pg_attribute_desc = table_open(AttributeRelationId, AccessShareLock);
561 1340380 : pg_attribute_scan = systable_beginscan(pg_attribute_desc,
562 : AttributeRelidNumIndexId,
563 : criticalRelcachesBuilt,
564 : NULL,
565 : 2, skey);
566 :
567 : /*
568 : * add attribute data to relation->rd_att
569 : */
570 1340380 : need = RelationGetNumberOfAttributes(relation);
571 :
572 4711412 : while (HeapTupleIsValid(pg_attribute_tuple = systable_getnext(pg_attribute_scan)))
573 : {
574 : Form_pg_attribute attp;
575 : int attnum;
576 :
577 4702390 : attp = (Form_pg_attribute) GETSTRUCT(pg_attribute_tuple);
578 :
579 4702390 : attnum = attp->attnum;
580 4702390 : if (attnum <= 0 || attnum > RelationGetNumberOfAttributes(relation))
581 0 : elog(ERROR, "invalid attribute number %d for relation \"%s\"",
582 : attp->attnum, RelationGetRelationName(relation));
583 :
584 4702390 : memcpy(TupleDescAttr(relation->rd_att, attnum - 1),
585 : attp,
586 : ATTRIBUTE_FIXED_PART_SIZE);
587 :
588 : /* Update constraint/default info */
589 4702390 : if (attp->attnotnull)
590 1983412 : constr->has_not_null = true;
591 4702390 : if (attp->attgenerated == ATTRIBUTE_GENERATED_STORED)
592 8336 : constr->has_generated_stored = true;
593 4702390 : if (attp->atthasdef)
594 38426 : ndef++;
595 :
596 : /* If the column has a "missing" value, put it in the attrmiss array */
597 4702390 : if (attp->atthasmissing)
598 : {
599 : Datum missingval;
600 : bool missingNull;
601 :
602 : /* Do we have a missing value? */
603 7160 : missingval = heap_getattr(pg_attribute_tuple,
604 : Anum_pg_attribute_attmissingval,
605 : pg_attribute_desc->rd_att,
606 : &missingNull);
607 7160 : if (!missingNull)
608 : {
609 : /* Yes, fetch from the array */
610 : MemoryContext oldcxt;
611 : bool is_null;
612 7160 : int one = 1;
613 : Datum missval;
614 :
615 7160 : if (attrmiss == NULL)
616 : attrmiss = (AttrMissing *)
617 3344 : MemoryContextAllocZero(CacheMemoryContext,
618 3344 : relation->rd_rel->relnatts *
619 : sizeof(AttrMissing));
620 :
621 7160 : missval = array_get_element(missingval,
622 : 1,
623 : &one,
624 : -1,
625 7160 : attp->attlen,
626 7160 : attp->attbyval,
627 7160 : attp->attalign,
628 : &is_null);
629 : Assert(!is_null);
630 7160 : if (attp->attbyval)
631 : {
632 : /* for copy by val just copy the datum direct */
633 4454 : attrmiss[attnum - 1].am_value = missval;
634 : }
635 : else
636 : {
637 : /* otherwise copy in the correct context */
638 2706 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
639 5412 : attrmiss[attnum - 1].am_value = datumCopy(missval,
640 2706 : attp->attbyval,
641 2706 : attp->attlen);
642 2706 : MemoryContextSwitchTo(oldcxt);
643 : }
644 7160 : attrmiss[attnum - 1].am_present = true;
645 : }
646 : }
647 4702390 : need--;
648 4702390 : if (need == 0)
649 1331358 : break;
650 : }
651 :
652 : /*
653 : * end the scan and close the attribute relation
654 : */
655 1340378 : systable_endscan(pg_attribute_scan);
656 1340378 : table_close(pg_attribute_desc, AccessShareLock);
657 :
658 1340378 : if (need != 0)
659 0 : elog(ERROR, "pg_attribute catalog is missing %d attribute(s) for relation OID %u",
660 : need, RelationGetRelid(relation));
661 :
662 : /*
663 : * The attcacheoff values we read from pg_attribute should all be -1
664 : * ("unknown"). Verify this if assert checking is on. They will be
665 : * computed when and if needed during tuple access.
666 : */
667 : #ifdef USE_ASSERT_CHECKING
668 : {
669 : int i;
670 :
671 : for (i = 0; i < RelationGetNumberOfAttributes(relation); i++)
672 : Assert(TupleDescAttr(relation->rd_att, i)->attcacheoff == -1);
673 : }
674 : #endif
675 :
676 : /*
677 : * However, we can easily set the attcacheoff value for the first
678 : * attribute: it must be zero. This eliminates the need for special cases
679 : * for attnum=1 that used to exist in fastgetattr() and index_getattr().
680 : */
681 1340378 : if (RelationGetNumberOfAttributes(relation) > 0)
682 1331358 : TupleDescAttr(relation->rd_att, 0)->attcacheoff = 0;
683 :
684 : /*
685 : * Set up constraint/default info
686 : */
687 1340378 : if (constr->has_not_null ||
688 925340 : constr->has_generated_stored ||
689 917524 : ndef > 0 ||
690 917500 : attrmiss ||
691 917500 : relation->rd_rel->relchecks > 0)
692 : {
693 427442 : relation->rd_att->constr = constr;
694 :
695 427442 : if (ndef > 0) /* DEFAULTs */
696 27504 : AttrDefaultFetch(relation, ndef);
697 : else
698 399938 : constr->num_defval = 0;
699 :
700 427442 : constr->missing = attrmiss;
701 :
702 427442 : if (relation->rd_rel->relchecks > 0) /* CHECKs */
703 10708 : CheckConstraintFetch(relation);
704 : else
705 416734 : constr->num_check = 0;
706 : }
707 : else
708 : {
709 912936 : pfree(constr);
710 912936 : relation->rd_att->constr = NULL;
711 : }
712 1340378 : }
713 :
714 : /*
715 : * RelationBuildRuleLock
716 : *
717 : * Form the relation's rewrite rules from information in
718 : * the pg_rewrite system catalog.
719 : *
720 : * Note: The rule parsetrees are potentially very complex node structures.
721 : * To allow these trees to be freed when the relcache entry is flushed,
722 : * we make a private memory context to hold the RuleLock information for
723 : * each relcache entry that has associated rules. The context is used
724 : * just for rule info, not for any other subsidiary data of the relcache
725 : * entry, because that keeps the update logic in RelationRebuildRelation()
726 : * manageable. The other subsidiary data structures are simple enough
727 : * to be easy to free explicitly, anyway.
728 : *
729 : * Note: The relation's reloptions must have been extracted first.
730 : */
731 : static void
732 35010 : RelationBuildRuleLock(Relation relation)
733 : {
734 : MemoryContext rulescxt;
735 : MemoryContext oldcxt;
736 : HeapTuple rewrite_tuple;
737 : Relation rewrite_desc;
738 : TupleDesc rewrite_tupdesc;
739 : SysScanDesc rewrite_scan;
740 : ScanKeyData key;
741 : RuleLock *rulelock;
742 : int numlocks;
743 : RewriteRule **rules;
744 : int maxlocks;
745 :
746 : /*
747 : * Make the private context. Assume it'll not contain much data.
748 : */
749 35010 : rulescxt = AllocSetContextCreate(CacheMemoryContext,
750 : "relation rules",
751 : ALLOCSET_SMALL_SIZES);
752 35010 : relation->rd_rulescxt = rulescxt;
753 35010 : MemoryContextCopyAndSetIdentifier(rulescxt,
754 : RelationGetRelationName(relation));
755 :
756 : /*
757 : * allocate an array to hold the rewrite rules (the array is extended if
758 : * necessary)
759 : */
760 35010 : maxlocks = 4;
761 : rules = (RewriteRule **)
762 35010 : MemoryContextAlloc(rulescxt, sizeof(RewriteRule *) * maxlocks);
763 35010 : numlocks = 0;
764 :
765 : /*
766 : * form a scan key
767 : */
768 35010 : ScanKeyInit(&key,
769 : Anum_pg_rewrite_ev_class,
770 : BTEqualStrategyNumber, F_OIDEQ,
771 : ObjectIdGetDatum(RelationGetRelid(relation)));
772 :
773 : /*
774 : * open pg_rewrite and begin a scan
775 : *
776 : * Note: since we scan the rules using RewriteRelRulenameIndexId, we will
777 : * be reading the rules in name order, except possibly during
778 : * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
779 : * ensures that rules will be fired in name order.
780 : */
781 35010 : rewrite_desc = table_open(RewriteRelationId, AccessShareLock);
782 35010 : rewrite_tupdesc = RelationGetDescr(rewrite_desc);
783 35010 : rewrite_scan = systable_beginscan(rewrite_desc,
784 : RewriteRelRulenameIndexId,
785 : true, NULL,
786 : 1, &key);
787 :
788 69386 : while (HeapTupleIsValid(rewrite_tuple = systable_getnext(rewrite_scan)))
789 : {
790 34376 : Form_pg_rewrite rewrite_form = (Form_pg_rewrite) GETSTRUCT(rewrite_tuple);
791 : bool isnull;
792 : Datum rule_datum;
793 : char *rule_str;
794 : RewriteRule *rule;
795 : Oid check_as_user;
796 :
797 34376 : rule = (RewriteRule *) MemoryContextAlloc(rulescxt,
798 : sizeof(RewriteRule));
799 :
800 34376 : rule->ruleId = rewrite_form->oid;
801 :
802 34376 : rule->event = rewrite_form->ev_type - '0';
803 34376 : rule->enabled = rewrite_form->ev_enabled;
804 34376 : rule->isInstead = rewrite_form->is_instead;
805 :
806 : /*
807 : * Must use heap_getattr to fetch ev_action and ev_qual. Also, the
808 : * rule strings are often large enough to be toasted. To avoid
809 : * leaking memory in the caller's context, do the detoasting here so
810 : * we can free the detoasted version.
811 : */
812 34376 : rule_datum = heap_getattr(rewrite_tuple,
813 : Anum_pg_rewrite_ev_action,
814 : rewrite_tupdesc,
815 : &isnull);
816 : Assert(!isnull);
817 34376 : rule_str = TextDatumGetCString(rule_datum);
818 34376 : oldcxt = MemoryContextSwitchTo(rulescxt);
819 34376 : rule->actions = (List *) stringToNode(rule_str);
820 34376 : MemoryContextSwitchTo(oldcxt);
821 34376 : pfree(rule_str);
822 :
823 34376 : rule_datum = heap_getattr(rewrite_tuple,
824 : Anum_pg_rewrite_ev_qual,
825 : rewrite_tupdesc,
826 : &isnull);
827 : Assert(!isnull);
828 34376 : rule_str = TextDatumGetCString(rule_datum);
829 34376 : oldcxt = MemoryContextSwitchTo(rulescxt);
830 34376 : rule->qual = (Node *) stringToNode(rule_str);
831 34376 : MemoryContextSwitchTo(oldcxt);
832 34376 : pfree(rule_str);
833 :
834 : /*
835 : * If this is a SELECT rule defining a view, and the view has
836 : * "security_invoker" set, we must perform all permissions checks on
837 : * relations referred to by the rule as the invoking user.
838 : *
839 : * In all other cases (including non-SELECT rules on security invoker
840 : * views), perform the permissions checks as the relation owner.
841 : */
842 34376 : if (rule->event == CMD_SELECT &&
843 31304 : relation->rd_rel->relkind == RELKIND_VIEW &&
844 27452 : RelationHasSecurityInvoker(relation))
845 168 : check_as_user = InvalidOid;
846 : else
847 34208 : check_as_user = relation->rd_rel->relowner;
848 :
849 : /*
850 : * Scan through the rule's actions and set the checkAsUser field on
851 : * all RTEPermissionInfos. We have to look at the qual as well, in
852 : * case it contains sublinks.
853 : *
854 : * The reason for doing this when the rule is loaded, rather than when
855 : * it is stored, is that otherwise ALTER TABLE OWNER would have to
856 : * grovel through stored rules to update checkAsUser fields. Scanning
857 : * the rule tree during load is relatively cheap (compared to
858 : * constructing it in the first place), so we do it here.
859 : */
860 34376 : setRuleCheckAsUser((Node *) rule->actions, check_as_user);
861 34376 : setRuleCheckAsUser(rule->qual, check_as_user);
862 :
863 34376 : if (numlocks >= maxlocks)
864 : {
865 32 : maxlocks *= 2;
866 : rules = (RewriteRule **)
867 32 : repalloc(rules, sizeof(RewriteRule *) * maxlocks);
868 : }
869 34376 : rules[numlocks++] = rule;
870 : }
871 :
872 : /*
873 : * end the scan and close the attribute relation
874 : */
875 35010 : systable_endscan(rewrite_scan);
876 35010 : table_close(rewrite_desc, AccessShareLock);
877 :
878 : /*
879 : * there might not be any rules (if relhasrules is out-of-date)
880 : */
881 35010 : if (numlocks == 0)
882 : {
883 2798 : relation->rd_rules = NULL;
884 2798 : relation->rd_rulescxt = NULL;
885 2798 : MemoryContextDelete(rulescxt);
886 2798 : return;
887 : }
888 :
889 : /*
890 : * form a RuleLock and insert into relation
891 : */
892 32212 : rulelock = (RuleLock *) MemoryContextAlloc(rulescxt, sizeof(RuleLock));
893 32212 : rulelock->numLocks = numlocks;
894 32212 : rulelock->rules = rules;
895 :
896 32212 : relation->rd_rules = rulelock;
897 : }
898 :
899 : /*
900 : * equalRuleLocks
901 : *
902 : * Determine whether two RuleLocks are equivalent
903 : *
904 : * Probably this should be in the rules code someplace...
905 : */
906 : static bool
907 384528 : equalRuleLocks(RuleLock *rlock1, RuleLock *rlock2)
908 : {
909 : int i;
910 :
911 : /*
912 : * As of 7.3 we assume the rule ordering is repeatable, because
913 : * RelationBuildRuleLock should read 'em in a consistent order. So just
914 : * compare corresponding slots.
915 : */
916 384528 : if (rlock1 != NULL)
917 : {
918 2476 : if (rlock2 == NULL)
919 52 : return false;
920 2424 : if (rlock1->numLocks != rlock2->numLocks)
921 6 : return false;
922 4586 : for (i = 0; i < rlock1->numLocks; i++)
923 : {
924 2454 : RewriteRule *rule1 = rlock1->rules[i];
925 2454 : RewriteRule *rule2 = rlock2->rules[i];
926 :
927 2454 : if (rule1->ruleId != rule2->ruleId)
928 0 : return false;
929 2454 : if (rule1->event != rule2->event)
930 0 : return false;
931 2454 : if (rule1->enabled != rule2->enabled)
932 46 : return false;
933 2408 : if (rule1->isInstead != rule2->isInstead)
934 0 : return false;
935 2408 : if (!equal(rule1->qual, rule2->qual))
936 0 : return false;
937 2408 : if (!equal(rule1->actions, rule2->actions))
938 240 : return false;
939 : }
940 : }
941 382052 : else if (rlock2 != NULL)
942 15308 : return false;
943 368876 : return true;
944 : }
945 :
946 : /*
947 : * equalPolicy
948 : *
949 : * Determine whether two policies are equivalent
950 : */
951 : static bool
952 204 : equalPolicy(RowSecurityPolicy *policy1, RowSecurityPolicy *policy2)
953 : {
954 : int i;
955 : Oid *r1,
956 : *r2;
957 :
958 204 : if (policy1 != NULL)
959 : {
960 204 : if (policy2 == NULL)
961 0 : return false;
962 :
963 204 : if (policy1->polcmd != policy2->polcmd)
964 0 : return false;
965 204 : if (policy1->hassublinks != policy2->hassublinks)
966 0 : return false;
967 204 : if (strcmp(policy1->policy_name, policy2->policy_name) != 0)
968 0 : return false;
969 204 : if (ARR_DIMS(policy1->roles)[0] != ARR_DIMS(policy2->roles)[0])
970 0 : return false;
971 :
972 204 : r1 = (Oid *) ARR_DATA_PTR(policy1->roles);
973 204 : r2 = (Oid *) ARR_DATA_PTR(policy2->roles);
974 :
975 408 : for (i = 0; i < ARR_DIMS(policy1->roles)[0]; i++)
976 : {
977 204 : if (r1[i] != r2[i])
978 0 : return false;
979 : }
980 :
981 204 : if (!equal(policy1->qual, policy2->qual))
982 0 : return false;
983 204 : if (!equal(policy1->with_check_qual, policy2->with_check_qual))
984 0 : return false;
985 : }
986 0 : else if (policy2 != NULL)
987 0 : return false;
988 :
989 204 : return true;
990 : }
991 :
992 : /*
993 : * equalRSDesc
994 : *
995 : * Determine whether two RowSecurityDesc's are equivalent
996 : */
997 : static bool
998 384528 : equalRSDesc(RowSecurityDesc *rsdesc1, RowSecurityDesc *rsdesc2)
999 : {
1000 : ListCell *lc,
1001 : *rc;
1002 :
1003 384528 : if (rsdesc1 == NULL && rsdesc2 == NULL)
1004 384076 : return true;
1005 :
1006 452 : if ((rsdesc1 != NULL && rsdesc2 == NULL) ||
1007 284 : (rsdesc1 == NULL && rsdesc2 != NULL))
1008 294 : return false;
1009 :
1010 158 : if (list_length(rsdesc1->policies) != list_length(rsdesc2->policies))
1011 6 : return false;
1012 :
1013 : /* RelationBuildRowSecurity should build policies in order */
1014 356 : forboth(lc, rsdesc1->policies, rc, rsdesc2->policies)
1015 : {
1016 204 : RowSecurityPolicy *l = (RowSecurityPolicy *) lfirst(lc);
1017 204 : RowSecurityPolicy *r = (RowSecurityPolicy *) lfirst(rc);
1018 :
1019 204 : if (!equalPolicy(l, r))
1020 0 : return false;
1021 : }
1022 :
1023 152 : return true;
1024 : }
1025 :
1026 : /*
1027 : * RelationBuildDesc
1028 : *
1029 : * Build a relation descriptor. The caller must hold at least
1030 : * AccessShareLock on the target relid.
1031 : *
1032 : * The new descriptor is inserted into the hash table if insertIt is true.
1033 : *
1034 : * Returns NULL if no pg_class row could be found for the given relid
1035 : * (suggesting we are trying to access a just-deleted relation).
1036 : * Any other error is reported via elog.
1037 : */
1038 : static Relation
1039 1340412 : RelationBuildDesc(Oid targetRelId, bool insertIt)
1040 : {
1041 : int in_progress_offset;
1042 : Relation relation;
1043 : Oid relid;
1044 : HeapTuple pg_class_tuple;
1045 : Form_pg_class relp;
1046 :
1047 : /*
1048 : * This function and its subroutines can allocate a good deal of transient
1049 : * data in CurrentMemoryContext. Traditionally we've just leaked that
1050 : * data, reasoning that the caller's context is at worst of transaction
1051 : * scope, and relcache loads shouldn't happen so often that it's essential
1052 : * to recover transient data before end of statement/transaction. However
1053 : * that's definitely not true when debug_discard_caches is active, and
1054 : * perhaps it's not true in other cases.
1055 : *
1056 : * When debug_discard_caches is active or when forced to by
1057 : * RECOVER_RELATION_BUILD_MEMORY=1, arrange to allocate the junk in a
1058 : * temporary context that we'll free before returning. Make it a child of
1059 : * caller's context so that it will get cleaned up appropriately if we
1060 : * error out partway through.
1061 : */
1062 : #ifdef MAYBE_RECOVER_RELATION_BUILD_MEMORY
1063 : MemoryContext tmpcxt = NULL;
1064 : MemoryContext oldcxt = NULL;
1065 :
1066 : if (RECOVER_RELATION_BUILD_MEMORY || debug_discard_caches > 0)
1067 : {
1068 : tmpcxt = AllocSetContextCreate(CurrentMemoryContext,
1069 : "RelationBuildDesc workspace",
1070 : ALLOCSET_DEFAULT_SIZES);
1071 : oldcxt = MemoryContextSwitchTo(tmpcxt);
1072 : }
1073 : #endif
1074 :
1075 : /* Register to catch invalidation messages */
1076 1340412 : if (in_progress_list_len >= in_progress_list_maxlen)
1077 : {
1078 : int allocsize;
1079 :
1080 44 : allocsize = in_progress_list_maxlen * 2;
1081 44 : in_progress_list = repalloc(in_progress_list,
1082 : allocsize * sizeof(*in_progress_list));
1083 44 : in_progress_list_maxlen = allocsize;
1084 : }
1085 1340412 : in_progress_offset = in_progress_list_len++;
1086 1340412 : in_progress_list[in_progress_offset].reloid = targetRelId;
1087 1340426 : retry:
1088 1340426 : in_progress_list[in_progress_offset].invalidated = false;
1089 :
1090 : /*
1091 : * find the tuple in pg_class corresponding to the given relation id
1092 : */
1093 1340426 : pg_class_tuple = ScanPgRelation(targetRelId, true, false);
1094 :
1095 : /*
1096 : * if no such tuple exists, return NULL
1097 : */
1098 1340426 : if (!HeapTupleIsValid(pg_class_tuple))
1099 : {
1100 : #ifdef MAYBE_RECOVER_RELATION_BUILD_MEMORY
1101 : if (tmpcxt)
1102 : {
1103 : /* Return to caller's context, and blow away the temporary context */
1104 : MemoryContextSwitchTo(oldcxt);
1105 : MemoryContextDelete(tmpcxt);
1106 : }
1107 : #endif
1108 : Assert(in_progress_offset + 1 == in_progress_list_len);
1109 46 : in_progress_list_len--;
1110 46 : return NULL;
1111 : }
1112 :
1113 : /*
1114 : * get information from the pg_class_tuple
1115 : */
1116 1340380 : relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
1117 1340380 : relid = relp->oid;
1118 : Assert(relid == targetRelId);
1119 :
1120 : /*
1121 : * allocate storage for the relation descriptor, and copy pg_class_tuple
1122 : * to relation->rd_rel.
1123 : */
1124 1340380 : relation = AllocateRelationDesc(relp);
1125 :
1126 : /*
1127 : * initialize the relation's relation id (relation->rd_id)
1128 : */
1129 1340380 : RelationGetRelid(relation) = relid;
1130 :
1131 : /*
1132 : * Normal relations are not nailed into the cache. Since we don't flush
1133 : * new relations, it won't be new. It could be temp though.
1134 : */
1135 1340380 : relation->rd_refcnt = 0;
1136 1340380 : relation->rd_isnailed = false;
1137 1340380 : relation->rd_createSubid = InvalidSubTransactionId;
1138 1340380 : relation->rd_newRelfilelocatorSubid = InvalidSubTransactionId;
1139 1340380 : relation->rd_firstRelfilelocatorSubid = InvalidSubTransactionId;
1140 1340380 : relation->rd_droppedSubid = InvalidSubTransactionId;
1141 1340380 : switch (relation->rd_rel->relpersistence)
1142 : {
1143 1312860 : case RELPERSISTENCE_UNLOGGED:
1144 : case RELPERSISTENCE_PERMANENT:
1145 1312860 : relation->rd_backend = INVALID_PROC_NUMBER;
1146 1312860 : relation->rd_islocaltemp = false;
1147 1312860 : break;
1148 27520 : case RELPERSISTENCE_TEMP:
1149 27520 : if (isTempOrTempToastNamespace(relation->rd_rel->relnamespace))
1150 : {
1151 27484 : relation->rd_backend = ProcNumberForTempRelations();
1152 27484 : relation->rd_islocaltemp = true;
1153 : }
1154 : else
1155 : {
1156 : /*
1157 : * If it's a temp table, but not one of ours, we have to use
1158 : * the slow, grotty method to figure out the owning backend.
1159 : *
1160 : * Note: it's possible that rd_backend gets set to
1161 : * MyProcNumber here, in case we are looking at a pg_class
1162 : * entry left over from a crashed backend that coincidentally
1163 : * had the same ProcNumber we're using. We should *not*
1164 : * consider such a table to be "ours"; this is why we need the
1165 : * separate rd_islocaltemp flag. The pg_class entry will get
1166 : * flushed if/when we clean out the corresponding temp table
1167 : * namespace in preparation for using it.
1168 : */
1169 36 : relation->rd_backend =
1170 36 : GetTempNamespaceProcNumber(relation->rd_rel->relnamespace);
1171 : Assert(relation->rd_backend != INVALID_PROC_NUMBER);
1172 36 : relation->rd_islocaltemp = false;
1173 : }
1174 27520 : break;
1175 0 : default:
1176 0 : elog(ERROR, "invalid relpersistence: %c",
1177 : relation->rd_rel->relpersistence);
1178 : break;
1179 : }
1180 :
1181 : /*
1182 : * initialize the tuple descriptor (relation->rd_att).
1183 : */
1184 1340380 : RelationBuildTupleDesc(relation);
1185 :
1186 : /* foreign key data is not loaded till asked for */
1187 1340378 : relation->rd_fkeylist = NIL;
1188 1340378 : relation->rd_fkeyvalid = false;
1189 :
1190 : /* partitioning data is not loaded till asked for */
1191 1340378 : relation->rd_partkey = NULL;
1192 1340378 : relation->rd_partkeycxt = NULL;
1193 1340378 : relation->rd_partdesc = NULL;
1194 1340378 : relation->rd_partdesc_nodetached = NULL;
1195 1340378 : relation->rd_partdesc_nodetached_xmin = InvalidTransactionId;
1196 1340378 : relation->rd_pdcxt = NULL;
1197 1340378 : relation->rd_pddcxt = NULL;
1198 1340378 : relation->rd_partcheck = NIL;
1199 1340378 : relation->rd_partcheckvalid = false;
1200 1340378 : relation->rd_partcheckcxt = NULL;
1201 :
1202 : /*
1203 : * initialize access method information
1204 : */
1205 1340378 : if (relation->rd_rel->relkind == RELKIND_INDEX ||
1206 826706 : relation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
1207 519570 : RelationInitIndexAccessInfo(relation);
1208 820808 : else if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind) ||
1209 114570 : relation->rd_rel->relkind == RELKIND_SEQUENCE)
1210 712050 : RelationInitTableAccessMethod(relation);
1211 : else if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1212 : {
1213 : /*
1214 : * Do nothing: access methods are a setting that partitions can
1215 : * inherit.
1216 : */
1217 : }
1218 : else
1219 : Assert(relation->rd_rel->relam == InvalidOid);
1220 :
1221 : /* extract reloptions if any */
1222 1340368 : RelationParseRelOptions(relation, pg_class_tuple);
1223 :
1224 : /*
1225 : * Fetch rules and triggers that affect this relation.
1226 : *
1227 : * Note that RelationBuildRuleLock() relies on this being done after
1228 : * extracting the relation's reloptions.
1229 : */
1230 1340368 : if (relation->rd_rel->relhasrules)
1231 35010 : RelationBuildRuleLock(relation);
1232 : else
1233 : {
1234 1305358 : relation->rd_rules = NULL;
1235 1305358 : relation->rd_rulescxt = NULL;
1236 : }
1237 :
1238 1340368 : if (relation->rd_rel->relhastriggers)
1239 58356 : RelationBuildTriggers(relation);
1240 : else
1241 1282012 : relation->trigdesc = NULL;
1242 :
1243 1340368 : if (relation->rd_rel->relrowsecurity)
1244 1942 : RelationBuildRowSecurity(relation);
1245 : else
1246 1338426 : relation->rd_rsdesc = NULL;
1247 :
1248 : /*
1249 : * initialize the relation lock manager information
1250 : */
1251 1340368 : RelationInitLockInfo(relation); /* see lmgr.c */
1252 :
1253 : /*
1254 : * initialize physical addressing information for the relation
1255 : */
1256 1340368 : RelationInitPhysicalAddr(relation);
1257 :
1258 : /* make sure relation is marked as having no open file yet */
1259 1340368 : relation->rd_smgr = NULL;
1260 :
1261 : /*
1262 : * now we can free the memory allocated for pg_class_tuple
1263 : */
1264 1340368 : heap_freetuple(pg_class_tuple);
1265 :
1266 : /*
1267 : * If an invalidation arrived mid-build, start over. Between here and the
1268 : * end of this function, don't add code that does or reasonably could read
1269 : * system catalogs. That range must be free from invalidation processing
1270 : * for the !insertIt case. For the insertIt case, RelationCacheInsert()
1271 : * will enroll this relation in ordinary relcache invalidation processing,
1272 : */
1273 1340368 : if (in_progress_list[in_progress_offset].invalidated)
1274 : {
1275 14 : RelationDestroyRelation(relation, false);
1276 14 : goto retry;
1277 : }
1278 : Assert(in_progress_offset + 1 == in_progress_list_len);
1279 1340354 : in_progress_list_len--;
1280 :
1281 : /*
1282 : * Insert newly created relation into relcache hash table, if requested.
1283 : *
1284 : * There is one scenario in which we might find a hashtable entry already
1285 : * present, even though our caller failed to find it: if the relation is a
1286 : * system catalog or index that's used during relcache load, we might have
1287 : * recursively created the same relcache entry during the preceding steps.
1288 : * So allow RelationCacheInsert to delete any already-present relcache
1289 : * entry for the same OID. The already-present entry should have refcount
1290 : * zero (else somebody forgot to close it); in the event that it doesn't,
1291 : * we'll elog a WARNING and leak the already-present entry.
1292 : */
1293 1340354 : if (insertIt)
1294 955826 : RelationCacheInsert(relation, true);
1295 :
1296 : /* It's fully valid */
1297 1340354 : relation->rd_isvalid = true;
1298 :
1299 : #ifdef MAYBE_RECOVER_RELATION_BUILD_MEMORY
1300 : if (tmpcxt)
1301 : {
1302 : /* Return to caller's context, and blow away the temporary context */
1303 : MemoryContextSwitchTo(oldcxt);
1304 : MemoryContextDelete(tmpcxt);
1305 : }
1306 : #endif
1307 :
1308 1340354 : return relation;
1309 : }
1310 :
1311 : /*
1312 : * Initialize the physical addressing info (RelFileLocator) for a relcache entry
1313 : *
1314 : * Note: at the physical level, relations in the pg_global tablespace must
1315 : * be treated as shared, even if relisshared isn't set. Hence we do not
1316 : * look at relisshared here.
1317 : */
1318 : static void
1319 5054062 : RelationInitPhysicalAddr(Relation relation)
1320 : {
1321 5054062 : RelFileNumber oldnumber = relation->rd_locator.relNumber;
1322 :
1323 : /* these relations kinds never have storage */
1324 5054062 : if (!RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
1325 143284 : return;
1326 :
1327 4910778 : if (relation->rd_rel->reltablespace)
1328 779152 : relation->rd_locator.spcOid = relation->rd_rel->reltablespace;
1329 : else
1330 4131626 : relation->rd_locator.spcOid = MyDatabaseTableSpace;
1331 4910778 : if (relation->rd_locator.spcOid == GLOBALTABLESPACE_OID)
1332 775790 : relation->rd_locator.dbOid = InvalidOid;
1333 : else
1334 4134988 : relation->rd_locator.dbOid = MyDatabaseId;
1335 :
1336 4910778 : if (relation->rd_rel->relfilenode)
1337 : {
1338 : /*
1339 : * Even if we are using a decoding snapshot that doesn't represent the
1340 : * current state of the catalog we need to make sure the filenode
1341 : * points to the current file since the older file will be gone (or
1342 : * truncated). The new file will still contain older rows so lookups
1343 : * in them will work correctly. This wouldn't work correctly if
1344 : * rewrites were allowed to change the schema in an incompatible way,
1345 : * but those are prevented both on catalog tables and on user tables
1346 : * declared as additional catalog tables.
1347 : */
1348 3636570 : if (HistoricSnapshotActive()
1349 4194 : && RelationIsAccessibleInLogicalDecoding(relation)
1350 2736 : && IsTransactionState())
1351 : {
1352 : HeapTuple phys_tuple;
1353 : Form_pg_class physrel;
1354 :
1355 2736 : phys_tuple = ScanPgRelation(RelationGetRelid(relation),
1356 2736 : RelationGetRelid(relation) != ClassOidIndexId,
1357 : true);
1358 2736 : if (!HeapTupleIsValid(phys_tuple))
1359 0 : elog(ERROR, "could not find pg_class entry for %u",
1360 : RelationGetRelid(relation));
1361 2736 : physrel = (Form_pg_class) GETSTRUCT(phys_tuple);
1362 :
1363 2736 : relation->rd_rel->reltablespace = physrel->reltablespace;
1364 2736 : relation->rd_rel->relfilenode = physrel->relfilenode;
1365 2736 : heap_freetuple(phys_tuple);
1366 : }
1367 :
1368 3636570 : relation->rd_locator.relNumber = relation->rd_rel->relfilenode;
1369 : }
1370 : else
1371 : {
1372 : /* Consult the relation mapper */
1373 1274208 : relation->rd_locator.relNumber =
1374 1274208 : RelationMapOidToFilenumber(relation->rd_id,
1375 1274208 : relation->rd_rel->relisshared);
1376 1274208 : if (!RelFileNumberIsValid(relation->rd_locator.relNumber))
1377 0 : elog(ERROR, "could not find relation mapping for relation \"%s\", OID %u",
1378 : RelationGetRelationName(relation), relation->rd_id);
1379 : }
1380 :
1381 : /*
1382 : * For RelationNeedsWAL() to answer correctly on parallel workers, restore
1383 : * rd_firstRelfilelocatorSubid. No subtransactions start or end while in
1384 : * parallel mode, so the specific SubTransactionId does not matter.
1385 : */
1386 4910778 : if (IsParallelWorker() && oldnumber != relation->rd_locator.relNumber)
1387 : {
1388 57072 : if (RelFileLocatorSkippingWAL(relation->rd_locator))
1389 304 : relation->rd_firstRelfilelocatorSubid = TopSubTransactionId;
1390 : else
1391 56768 : relation->rd_firstRelfilelocatorSubid = InvalidSubTransactionId;
1392 : }
1393 : }
1394 :
1395 : /*
1396 : * Fill in the IndexAmRoutine for an index relation.
1397 : *
1398 : * relation's rd_amhandler and rd_indexcxt must be valid already.
1399 : */
1400 : static void
1401 2564572 : InitIndexAmRoutine(Relation relation)
1402 : {
1403 : IndexAmRoutine *cached,
1404 : *tmp;
1405 :
1406 : /*
1407 : * Call the amhandler in current, short-lived memory context, just in case
1408 : * it leaks anything (it probably won't, but let's be paranoid).
1409 : */
1410 2564572 : tmp = GetIndexAmRoutine(relation->rd_amhandler);
1411 :
1412 : /* OK, now transfer the data into relation's rd_indexcxt. */
1413 2564572 : cached = (IndexAmRoutine *) MemoryContextAlloc(relation->rd_indexcxt,
1414 : sizeof(IndexAmRoutine));
1415 2564572 : memcpy(cached, tmp, sizeof(IndexAmRoutine));
1416 2564572 : relation->rd_indam = cached;
1417 :
1418 2564572 : pfree(tmp);
1419 2564572 : }
1420 :
1421 : /*
1422 : * Initialize index-access-method support data for an index relation
1423 : */
1424 : void
1425 533970 : RelationInitIndexAccessInfo(Relation relation)
1426 : {
1427 : HeapTuple tuple;
1428 : Form_pg_am aform;
1429 : Datum indcollDatum;
1430 : Datum indclassDatum;
1431 : Datum indoptionDatum;
1432 : bool isnull;
1433 : oidvector *indcoll;
1434 : oidvector *indclass;
1435 : int2vector *indoption;
1436 : MemoryContext indexcxt;
1437 : MemoryContext oldcontext;
1438 : int indnatts;
1439 : int indnkeyatts;
1440 : uint16 amsupport;
1441 :
1442 : /*
1443 : * Make a copy of the pg_index entry for the index. Since pg_index
1444 : * contains variable-length and possibly-null fields, we have to do this
1445 : * honestly rather than just treating it as a Form_pg_index struct.
1446 : */
1447 533970 : tuple = SearchSysCache1(INDEXRELID,
1448 : ObjectIdGetDatum(RelationGetRelid(relation)));
1449 533970 : if (!HeapTupleIsValid(tuple))
1450 0 : elog(ERROR, "cache lookup failed for index %u",
1451 : RelationGetRelid(relation));
1452 533970 : oldcontext = MemoryContextSwitchTo(CacheMemoryContext);
1453 533970 : relation->rd_indextuple = heap_copytuple(tuple);
1454 533970 : relation->rd_index = (Form_pg_index) GETSTRUCT(relation->rd_indextuple);
1455 533970 : MemoryContextSwitchTo(oldcontext);
1456 533970 : ReleaseSysCache(tuple);
1457 :
1458 : /*
1459 : * Look up the index's access method, save the OID of its handler function
1460 : */
1461 : Assert(relation->rd_rel->relam != InvalidOid);
1462 533970 : tuple = SearchSysCache1(AMOID, ObjectIdGetDatum(relation->rd_rel->relam));
1463 533968 : if (!HeapTupleIsValid(tuple))
1464 0 : elog(ERROR, "cache lookup failed for access method %u",
1465 : relation->rd_rel->relam);
1466 533968 : aform = (Form_pg_am) GETSTRUCT(tuple);
1467 533968 : relation->rd_amhandler = aform->amhandler;
1468 533968 : ReleaseSysCache(tuple);
1469 :
1470 533968 : indnatts = RelationGetNumberOfAttributes(relation);
1471 533968 : if (indnatts != IndexRelationGetNumberOfAttributes(relation))
1472 0 : elog(ERROR, "relnatts disagrees with indnatts for index %u",
1473 : RelationGetRelid(relation));
1474 533968 : indnkeyatts = IndexRelationGetNumberOfKeyAttributes(relation);
1475 :
1476 : /*
1477 : * Make the private context to hold index access info. The reason we need
1478 : * a context, and not just a couple of pallocs, is so that we won't leak
1479 : * any subsidiary info attached to fmgr lookup records.
1480 : */
1481 533968 : indexcxt = AllocSetContextCreate(CacheMemoryContext,
1482 : "index info",
1483 : ALLOCSET_SMALL_SIZES);
1484 533968 : relation->rd_indexcxt = indexcxt;
1485 533968 : MemoryContextCopyAndSetIdentifier(indexcxt,
1486 : RelationGetRelationName(relation));
1487 :
1488 : /*
1489 : * Now we can fetch the index AM's API struct
1490 : */
1491 533968 : InitIndexAmRoutine(relation);
1492 :
1493 : /*
1494 : * Allocate arrays to hold data. Opclasses are not used for included
1495 : * columns, so allocate them for indnkeyatts only.
1496 : */
1497 533968 : relation->rd_opfamily = (Oid *)
1498 533968 : MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1499 533968 : relation->rd_opcintype = (Oid *)
1500 533968 : MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1501 :
1502 533968 : amsupport = relation->rd_indam->amsupport;
1503 533968 : if (amsupport > 0)
1504 : {
1505 533968 : int nsupport = indnatts * amsupport;
1506 :
1507 533968 : relation->rd_support = (RegProcedure *)
1508 533968 : MemoryContextAllocZero(indexcxt, nsupport * sizeof(RegProcedure));
1509 533968 : relation->rd_supportinfo = (FmgrInfo *)
1510 533968 : MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
1511 : }
1512 : else
1513 : {
1514 0 : relation->rd_support = NULL;
1515 0 : relation->rd_supportinfo = NULL;
1516 : }
1517 :
1518 533968 : relation->rd_indcollation = (Oid *)
1519 533968 : MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1520 :
1521 533968 : relation->rd_indoption = (int16 *)
1522 533968 : MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(int16));
1523 :
1524 : /*
1525 : * indcollation cannot be referenced directly through the C struct,
1526 : * because it comes after the variable-width indkey field. Must extract
1527 : * the datum the hard way...
1528 : */
1529 533968 : indcollDatum = fastgetattr(relation->rd_indextuple,
1530 : Anum_pg_index_indcollation,
1531 : GetPgIndexDescriptor(),
1532 : &isnull);
1533 : Assert(!isnull);
1534 533968 : indcoll = (oidvector *) DatumGetPointer(indcollDatum);
1535 533968 : memcpy(relation->rd_indcollation, indcoll->values, indnkeyatts * sizeof(Oid));
1536 :
1537 : /*
1538 : * indclass cannot be referenced directly through the C struct, because it
1539 : * comes after the variable-width indkey field. Must extract the datum
1540 : * the hard way...
1541 : */
1542 533968 : indclassDatum = fastgetattr(relation->rd_indextuple,
1543 : Anum_pg_index_indclass,
1544 : GetPgIndexDescriptor(),
1545 : &isnull);
1546 : Assert(!isnull);
1547 533968 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
1548 :
1549 : /*
1550 : * Fill the support procedure OID array, as well as the info about
1551 : * opfamilies and opclass input types. (aminfo and supportinfo are left
1552 : * as zeroes, and are filled on-the-fly when used)
1553 : */
1554 533968 : IndexSupportInitialize(indclass, relation->rd_support,
1555 : relation->rd_opfamily, relation->rd_opcintype,
1556 : amsupport, indnkeyatts);
1557 :
1558 : /*
1559 : * Similarly extract indoption and copy it to the cache entry
1560 : */
1561 533966 : indoptionDatum = fastgetattr(relation->rd_indextuple,
1562 : Anum_pg_index_indoption,
1563 : GetPgIndexDescriptor(),
1564 : &isnull);
1565 : Assert(!isnull);
1566 533966 : indoption = (int2vector *) DatumGetPointer(indoptionDatum);
1567 533966 : memcpy(relation->rd_indoption, indoption->values, indnkeyatts * sizeof(int16));
1568 :
1569 533966 : (void) RelationGetIndexAttOptions(relation, false);
1570 :
1571 : /*
1572 : * expressions, predicate, exclusion caches will be filled later
1573 : */
1574 533960 : relation->rd_indexprs = NIL;
1575 533960 : relation->rd_indpred = NIL;
1576 533960 : relation->rd_exclops = NULL;
1577 533960 : relation->rd_exclprocs = NULL;
1578 533960 : relation->rd_exclstrats = NULL;
1579 533960 : relation->rd_amcache = NULL;
1580 533960 : }
1581 :
1582 : /*
1583 : * IndexSupportInitialize
1584 : * Initializes an index's cached opclass information,
1585 : * given the index's pg_index.indclass entry.
1586 : *
1587 : * Data is returned into *indexSupport, *opFamily, and *opcInType,
1588 : * which are arrays allocated by the caller.
1589 : *
1590 : * The caller also passes maxSupportNumber and maxAttributeNumber, since these
1591 : * indicate the size of the arrays it has allocated --- but in practice these
1592 : * numbers must always match those obtainable from the system catalog entries
1593 : * for the index and access method.
1594 : */
1595 : static void
1596 533968 : IndexSupportInitialize(oidvector *indclass,
1597 : RegProcedure *indexSupport,
1598 : Oid *opFamily,
1599 : Oid *opcInType,
1600 : StrategyNumber maxSupportNumber,
1601 : AttrNumber maxAttributeNumber)
1602 : {
1603 : int attIndex;
1604 :
1605 1435986 : for (attIndex = 0; attIndex < maxAttributeNumber; attIndex++)
1606 : {
1607 : OpClassCacheEnt *opcentry;
1608 :
1609 902020 : if (!OidIsValid(indclass->values[attIndex]))
1610 0 : elog(ERROR, "bogus pg_index tuple");
1611 :
1612 : /* look up the info for this opclass, using a cache */
1613 902020 : opcentry = LookupOpclassInfo(indclass->values[attIndex],
1614 : maxSupportNumber);
1615 :
1616 : /* copy cached data into relcache entry */
1617 902018 : opFamily[attIndex] = opcentry->opcfamily;
1618 902018 : opcInType[attIndex] = opcentry->opcintype;
1619 902018 : if (maxSupportNumber > 0)
1620 902018 : memcpy(&indexSupport[attIndex * maxSupportNumber],
1621 902018 : opcentry->supportProcs,
1622 : maxSupportNumber * sizeof(RegProcedure));
1623 : }
1624 533966 : }
1625 :
1626 : /*
1627 : * LookupOpclassInfo
1628 : *
1629 : * This routine maintains a per-opclass cache of the information needed
1630 : * by IndexSupportInitialize(). This is more efficient than relying on
1631 : * the catalog cache, because we can load all the info about a particular
1632 : * opclass in a single indexscan of pg_amproc.
1633 : *
1634 : * The information from pg_am about expected range of support function
1635 : * numbers is passed in, rather than being looked up, mainly because the
1636 : * caller will have it already.
1637 : *
1638 : * Note there is no provision for flushing the cache. This is OK at the
1639 : * moment because there is no way to ALTER any interesting properties of an
1640 : * existing opclass --- all you can do is drop it, which will result in
1641 : * a useless but harmless dead entry in the cache. To support altering
1642 : * opclass membership (not the same as opfamily membership!), we'd need to
1643 : * be able to flush this cache as well as the contents of relcache entries
1644 : * for indexes.
1645 : */
1646 : static OpClassCacheEnt *
1647 902020 : LookupOpclassInfo(Oid operatorClassOid,
1648 : StrategyNumber numSupport)
1649 : {
1650 : OpClassCacheEnt *opcentry;
1651 : bool found;
1652 : Relation rel;
1653 : SysScanDesc scan;
1654 : ScanKeyData skey[3];
1655 : HeapTuple htup;
1656 : bool indexOK;
1657 :
1658 902020 : if (OpClassCache == NULL)
1659 : {
1660 : /* First time through: initialize the opclass cache */
1661 : HASHCTL ctl;
1662 :
1663 : /* Also make sure CacheMemoryContext exists */
1664 26030 : if (!CacheMemoryContext)
1665 0 : CreateCacheMemoryContext();
1666 :
1667 26030 : ctl.keysize = sizeof(Oid);
1668 26030 : ctl.entrysize = sizeof(OpClassCacheEnt);
1669 26030 : OpClassCache = hash_create("Operator class cache", 64,
1670 : &ctl, HASH_ELEM | HASH_BLOBS);
1671 : }
1672 :
1673 902020 : opcentry = (OpClassCacheEnt *) hash_search(OpClassCache,
1674 : &operatorClassOid,
1675 : HASH_ENTER, &found);
1676 :
1677 902020 : if (!found)
1678 : {
1679 : /* Initialize new entry */
1680 73486 : opcentry->valid = false; /* until known OK */
1681 73486 : opcentry->numSupport = numSupport;
1682 73486 : opcentry->supportProcs = NULL; /* filled below */
1683 : }
1684 : else
1685 : {
1686 : Assert(numSupport == opcentry->numSupport);
1687 : }
1688 :
1689 : /*
1690 : * When aggressively testing cache-flush hazards, we disable the operator
1691 : * class cache and force reloading of the info on each call. This models
1692 : * no real-world behavior, since the cache entries are never invalidated
1693 : * otherwise. However it can be helpful for detecting bugs in the cache
1694 : * loading logic itself, such as reliance on a non-nailed index. Given
1695 : * the limited use-case and the fact that this adds a great deal of
1696 : * expense, we enable it only for high values of debug_discard_caches.
1697 : */
1698 : #ifdef DISCARD_CACHES_ENABLED
1699 : if (debug_discard_caches > 2)
1700 : opcentry->valid = false;
1701 : #endif
1702 :
1703 902020 : if (opcentry->valid)
1704 828534 : return opcentry;
1705 :
1706 : /*
1707 : * Need to fill in new entry. First allocate space, unless we already did
1708 : * so in some previous attempt.
1709 : */
1710 73486 : if (opcentry->supportProcs == NULL && numSupport > 0)
1711 73486 : opcentry->supportProcs = (RegProcedure *)
1712 73486 : MemoryContextAllocZero(CacheMemoryContext,
1713 : numSupport * sizeof(RegProcedure));
1714 :
1715 : /*
1716 : * To avoid infinite recursion during startup, force heap scans if we're
1717 : * looking up info for the opclasses used by the indexes we would like to
1718 : * reference here.
1719 : */
1720 81912 : indexOK = criticalRelcachesBuilt ||
1721 8426 : (operatorClassOid != OID_BTREE_OPS_OID &&
1722 5796 : operatorClassOid != INT2_BTREE_OPS_OID);
1723 :
1724 : /*
1725 : * We have to fetch the pg_opclass row to determine its opfamily and
1726 : * opcintype, which are needed to look up related operators and functions.
1727 : * It'd be convenient to use the syscache here, but that probably doesn't
1728 : * work while bootstrapping.
1729 : */
1730 73486 : ScanKeyInit(&skey[0],
1731 : Anum_pg_opclass_oid,
1732 : BTEqualStrategyNumber, F_OIDEQ,
1733 : ObjectIdGetDatum(operatorClassOid));
1734 73486 : rel = table_open(OperatorClassRelationId, AccessShareLock);
1735 73486 : scan = systable_beginscan(rel, OpclassOidIndexId, indexOK,
1736 : NULL, 1, skey);
1737 :
1738 73486 : if (HeapTupleIsValid(htup = systable_getnext(scan)))
1739 : {
1740 73486 : Form_pg_opclass opclassform = (Form_pg_opclass) GETSTRUCT(htup);
1741 :
1742 73486 : opcentry->opcfamily = opclassform->opcfamily;
1743 73486 : opcentry->opcintype = opclassform->opcintype;
1744 : }
1745 : else
1746 0 : elog(ERROR, "could not find tuple for opclass %u", operatorClassOid);
1747 :
1748 73486 : systable_endscan(scan);
1749 73486 : table_close(rel, AccessShareLock);
1750 :
1751 : /*
1752 : * Scan pg_amproc to obtain support procs for the opclass. We only fetch
1753 : * the default ones (those with lefttype = righttype = opcintype).
1754 : */
1755 73486 : if (numSupport > 0)
1756 : {
1757 73486 : ScanKeyInit(&skey[0],
1758 : Anum_pg_amproc_amprocfamily,
1759 : BTEqualStrategyNumber, F_OIDEQ,
1760 : ObjectIdGetDatum(opcentry->opcfamily));
1761 73486 : ScanKeyInit(&skey[1],
1762 : Anum_pg_amproc_amproclefttype,
1763 : BTEqualStrategyNumber, F_OIDEQ,
1764 : ObjectIdGetDatum(opcentry->opcintype));
1765 73486 : ScanKeyInit(&skey[2],
1766 : Anum_pg_amproc_amprocrighttype,
1767 : BTEqualStrategyNumber, F_OIDEQ,
1768 : ObjectIdGetDatum(opcentry->opcintype));
1769 73486 : rel = table_open(AccessMethodProcedureRelationId, AccessShareLock);
1770 73486 : scan = systable_beginscan(rel, AccessMethodProcedureIndexId, indexOK,
1771 : NULL, 3, skey);
1772 :
1773 304140 : while (HeapTupleIsValid(htup = systable_getnext(scan)))
1774 : {
1775 230654 : Form_pg_amproc amprocform = (Form_pg_amproc) GETSTRUCT(htup);
1776 :
1777 230654 : if (amprocform->amprocnum <= 0 ||
1778 230654 : (StrategyNumber) amprocform->amprocnum > numSupport)
1779 0 : elog(ERROR, "invalid amproc number %d for opclass %u",
1780 : amprocform->amprocnum, operatorClassOid);
1781 :
1782 230654 : opcentry->supportProcs[amprocform->amprocnum - 1] =
1783 230654 : amprocform->amproc;
1784 : }
1785 :
1786 73484 : systable_endscan(scan);
1787 73484 : table_close(rel, AccessShareLock);
1788 : }
1789 :
1790 73484 : opcentry->valid = true;
1791 73484 : return opcentry;
1792 : }
1793 :
1794 : /*
1795 : * Fill in the TableAmRoutine for a relation
1796 : *
1797 : * relation's rd_amhandler must be valid already.
1798 : */
1799 : static void
1800 1973528 : InitTableAmRoutine(Relation relation)
1801 : {
1802 1973528 : relation->rd_tableam = GetTableAmRoutine(relation->rd_amhandler);
1803 1973528 : }
1804 :
1805 : /*
1806 : * Initialize table access method support for a table like relation
1807 : */
1808 : void
1809 1973528 : RelationInitTableAccessMethod(Relation relation)
1810 : {
1811 : HeapTuple tuple;
1812 : Form_pg_am aform;
1813 :
1814 1973528 : if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
1815 : {
1816 : /*
1817 : * Sequences are currently accessed like heap tables, but it doesn't
1818 : * seem prudent to show that in the catalog. So just overwrite it
1819 : * here.
1820 : */
1821 : Assert(relation->rd_rel->relam == InvalidOid);
1822 7566 : relation->rd_amhandler = F_HEAP_TABLEAM_HANDLER;
1823 : }
1824 1965962 : else if (IsCatalogRelation(relation))
1825 : {
1826 : /*
1827 : * Avoid doing a syscache lookup for catalog tables.
1828 : */
1829 : Assert(relation->rd_rel->relam == HEAP_TABLE_AM_OID);
1830 1546004 : relation->rd_amhandler = F_HEAP_TABLEAM_HANDLER;
1831 : }
1832 : else
1833 : {
1834 : /*
1835 : * Look up the table access method, save the OID of its handler
1836 : * function.
1837 : */
1838 : Assert(relation->rd_rel->relam != InvalidOid);
1839 419958 : tuple = SearchSysCache1(AMOID,
1840 419958 : ObjectIdGetDatum(relation->rd_rel->relam));
1841 419958 : if (!HeapTupleIsValid(tuple))
1842 0 : elog(ERROR, "cache lookup failed for access method %u",
1843 : relation->rd_rel->relam);
1844 419958 : aform = (Form_pg_am) GETSTRUCT(tuple);
1845 419958 : relation->rd_amhandler = aform->amhandler;
1846 419958 : ReleaseSysCache(tuple);
1847 : }
1848 :
1849 : /*
1850 : * Now we can fetch the table AM's API struct
1851 : */
1852 1973528 : InitTableAmRoutine(relation);
1853 1973528 : }
1854 :
1855 : /*
1856 : * formrdesc
1857 : *
1858 : * This is a special cut-down version of RelationBuildDesc(),
1859 : * used while initializing the relcache.
1860 : * The relation descriptor is built just from the supplied parameters,
1861 : * without actually looking at any system table entries. We cheat
1862 : * quite a lot since we only need to work for a few basic system
1863 : * catalogs.
1864 : *
1865 : * The catalogs this is used for can't have constraints (except attnotnull),
1866 : * default values, rules, or triggers, since we don't cope with any of that.
1867 : * (Well, actually, this only matters for properties that need to be valid
1868 : * during bootstrap or before RelationCacheInitializePhase3 runs, and none of
1869 : * these properties matter then...)
1870 : *
1871 : * NOTE: we assume we are already switched into CacheMemoryContext.
1872 : */
1873 : static void
1874 29270 : formrdesc(const char *relationName, Oid relationReltype,
1875 : bool isshared,
1876 : int natts, const FormData_pg_attribute *attrs)
1877 : {
1878 : Relation relation;
1879 : int i;
1880 : bool has_not_null;
1881 :
1882 : /*
1883 : * allocate new relation desc, clear all fields of reldesc
1884 : */
1885 29270 : relation = (Relation) palloc0(sizeof(RelationData));
1886 :
1887 : /* make sure relation is marked as having no open file yet */
1888 29270 : relation->rd_smgr = NULL;
1889 :
1890 : /*
1891 : * initialize reference count: 1 because it is nailed in cache
1892 : */
1893 29270 : relation->rd_refcnt = 1;
1894 :
1895 : /*
1896 : * all entries built with this routine are nailed-in-cache; none are for
1897 : * new or temp relations.
1898 : */
1899 29270 : relation->rd_isnailed = true;
1900 29270 : relation->rd_createSubid = InvalidSubTransactionId;
1901 29270 : relation->rd_newRelfilelocatorSubid = InvalidSubTransactionId;
1902 29270 : relation->rd_firstRelfilelocatorSubid = InvalidSubTransactionId;
1903 29270 : relation->rd_droppedSubid = InvalidSubTransactionId;
1904 29270 : relation->rd_backend = INVALID_PROC_NUMBER;
1905 29270 : relation->rd_islocaltemp = false;
1906 :
1907 : /*
1908 : * initialize relation tuple form
1909 : *
1910 : * The data we insert here is pretty incomplete/bogus, but it'll serve to
1911 : * get us launched. RelationCacheInitializePhase3() will read the real
1912 : * data from pg_class and replace what we've done here. Note in
1913 : * particular that relowner is left as zero; this cues
1914 : * RelationCacheInitializePhase3 that the real data isn't there yet.
1915 : */
1916 29270 : relation->rd_rel = (Form_pg_class) palloc0(CLASS_TUPLE_SIZE);
1917 :
1918 29270 : namestrcpy(&relation->rd_rel->relname, relationName);
1919 29270 : relation->rd_rel->relnamespace = PG_CATALOG_NAMESPACE;
1920 29270 : relation->rd_rel->reltype = relationReltype;
1921 :
1922 : /*
1923 : * It's important to distinguish between shared and non-shared relations,
1924 : * even at bootstrap time, to make sure we know where they are stored.
1925 : */
1926 29270 : relation->rd_rel->relisshared = isshared;
1927 29270 : if (isshared)
1928 18750 : relation->rd_rel->reltablespace = GLOBALTABLESPACE_OID;
1929 :
1930 : /* formrdesc is used only for permanent relations */
1931 29270 : relation->rd_rel->relpersistence = RELPERSISTENCE_PERMANENT;
1932 :
1933 : /* ... and they're always populated, too */
1934 29270 : relation->rd_rel->relispopulated = true;
1935 :
1936 29270 : relation->rd_rel->relreplident = REPLICA_IDENTITY_NOTHING;
1937 29270 : relation->rd_rel->relpages = 0;
1938 29270 : relation->rd_rel->reltuples = -1;
1939 29270 : relation->rd_rel->relallvisible = 0;
1940 29270 : relation->rd_rel->relkind = RELKIND_RELATION;
1941 29270 : relation->rd_rel->relnatts = (int16) natts;
1942 :
1943 : /*
1944 : * initialize attribute tuple form
1945 : *
1946 : * Unlike the case with the relation tuple, this data had better be right
1947 : * because it will never be replaced. The data comes from
1948 : * src/include/catalog/ headers via genbki.pl.
1949 : */
1950 29270 : relation->rd_att = CreateTemplateTupleDesc(natts);
1951 29270 : relation->rd_att->tdrefcount = 1; /* mark as refcounted */
1952 :
1953 29270 : relation->rd_att->tdtypeid = relationReltype;
1954 29270 : relation->rd_att->tdtypmod = -1; /* just to be sure */
1955 :
1956 : /*
1957 : * initialize tuple desc info
1958 : */
1959 29270 : has_not_null = false;
1960 568750 : for (i = 0; i < natts; i++)
1961 : {
1962 539480 : memcpy(TupleDescAttr(relation->rd_att, i),
1963 539480 : &attrs[i],
1964 : ATTRIBUTE_FIXED_PART_SIZE);
1965 539480 : has_not_null |= attrs[i].attnotnull;
1966 : /* make sure attcacheoff is valid */
1967 539480 : TupleDescAttr(relation->rd_att, i)->attcacheoff = -1;
1968 : }
1969 :
1970 : /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
1971 29270 : TupleDescAttr(relation->rd_att, 0)->attcacheoff = 0;
1972 :
1973 : /* mark not-null status */
1974 29270 : if (has_not_null)
1975 : {
1976 29270 : TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
1977 :
1978 29270 : constr->has_not_null = true;
1979 29270 : relation->rd_att->constr = constr;
1980 : }
1981 :
1982 : /*
1983 : * initialize relation id from info in att array (my, this is ugly)
1984 : */
1985 29270 : RelationGetRelid(relation) = TupleDescAttr(relation->rd_att, 0)->attrelid;
1986 :
1987 : /*
1988 : * All relations made with formrdesc are mapped. This is necessarily so
1989 : * because there is no other way to know what filenumber they currently
1990 : * have. In bootstrap mode, add them to the initial relation mapper data,
1991 : * specifying that the initial filenumber is the same as the OID.
1992 : */
1993 29270 : relation->rd_rel->relfilenode = InvalidRelFileNumber;
1994 29270 : if (IsBootstrapProcessingMode())
1995 360 : RelationMapUpdateMap(RelationGetRelid(relation),
1996 : RelationGetRelid(relation),
1997 : isshared, true);
1998 :
1999 : /*
2000 : * initialize the relation lock manager information
2001 : */
2002 29270 : RelationInitLockInfo(relation); /* see lmgr.c */
2003 :
2004 : /*
2005 : * initialize physical addressing information for the relation
2006 : */
2007 29270 : RelationInitPhysicalAddr(relation);
2008 :
2009 : /*
2010 : * initialize the table am handler
2011 : */
2012 29270 : relation->rd_rel->relam = HEAP_TABLE_AM_OID;
2013 29270 : relation->rd_tableam = GetHeapamTableAmRoutine();
2014 :
2015 : /*
2016 : * initialize the rel-has-index flag, using hardwired knowledge
2017 : */
2018 29270 : if (IsBootstrapProcessingMode())
2019 : {
2020 : /* In bootstrap mode, we have no indexes */
2021 360 : relation->rd_rel->relhasindex = false;
2022 : }
2023 : else
2024 : {
2025 : /* Otherwise, all the rels formrdesc is used for have indexes */
2026 28910 : relation->rd_rel->relhasindex = true;
2027 : }
2028 :
2029 : /*
2030 : * add new reldesc to relcache
2031 : */
2032 29270 : RelationCacheInsert(relation, false);
2033 :
2034 : /* It's fully valid */
2035 29270 : relation->rd_isvalid = true;
2036 29270 : }
2037 :
2038 :
2039 : /* ----------------------------------------------------------------
2040 : * Relation Descriptor Lookup Interface
2041 : * ----------------------------------------------------------------
2042 : */
2043 :
2044 : /*
2045 : * RelationIdGetRelation
2046 : *
2047 : * Lookup a reldesc by OID; make one if not already in cache.
2048 : *
2049 : * Returns NULL if no pg_class row could be found for the given relid
2050 : * (suggesting we are trying to access a just-deleted relation).
2051 : * Any other error is reported via elog.
2052 : *
2053 : * NB: caller should already have at least AccessShareLock on the
2054 : * relation ID, else there are nasty race conditions.
2055 : *
2056 : * NB: relation ref count is incremented, or set to 1 if new entry.
2057 : * Caller should eventually decrement count. (Usually,
2058 : * that happens by calling RelationClose().)
2059 : */
2060 : Relation
2061 36052918 : RelationIdGetRelation(Oid relationId)
2062 : {
2063 : Relation rd;
2064 :
2065 : /* Make sure we're in an xact, even if this ends up being a cache hit */
2066 : Assert(IsTransactionState());
2067 :
2068 : /*
2069 : * first try to find reldesc in the cache
2070 : */
2071 36052918 : RelationIdCacheLookup(relationId, rd);
2072 :
2073 36052918 : if (RelationIsValid(rd))
2074 : {
2075 : /* return NULL for dropped relations */
2076 35126844 : if (rd->rd_droppedSubid != InvalidSubTransactionId)
2077 : {
2078 : Assert(!rd->rd_isvalid);
2079 4 : return NULL;
2080 : }
2081 :
2082 35126840 : RelationIncrementReferenceCount(rd);
2083 : /* revalidate cache entry if necessary */
2084 35126840 : if (!rd->rd_isvalid)
2085 : {
2086 156034 : RelationRebuildRelation(rd);
2087 :
2088 : /*
2089 : * Normally entries need to be valid here, but before the relcache
2090 : * has been initialized, not enough infrastructure exists to
2091 : * perform pg_class lookups. The structure of such entries doesn't
2092 : * change, but we still want to update the rd_rel entry. So
2093 : * rd_isvalid = false is left in place for a later lookup.
2094 : */
2095 : Assert(rd->rd_isvalid ||
2096 : (rd->rd_isnailed && !criticalRelcachesBuilt));
2097 : }
2098 35126828 : return rd;
2099 : }
2100 :
2101 : /*
2102 : * no reldesc in the cache, so have RelationBuildDesc() build one and add
2103 : * it.
2104 : */
2105 926074 : rd = RelationBuildDesc(relationId, true);
2106 926072 : if (RelationIsValid(rd))
2107 926026 : RelationIncrementReferenceCount(rd);
2108 926072 : return rd;
2109 : }
2110 :
2111 : /* ----------------------------------------------------------------
2112 : * cache invalidation support routines
2113 : * ----------------------------------------------------------------
2114 : */
2115 :
2116 : /* ResourceOwner callbacks to track relcache references */
2117 : static void ResOwnerReleaseRelation(Datum res);
2118 : static char *ResOwnerPrintRelCache(Datum res);
2119 :
2120 : static const ResourceOwnerDesc relref_resowner_desc =
2121 : {
2122 : .name = "relcache reference",
2123 : .release_phase = RESOURCE_RELEASE_BEFORE_LOCKS,
2124 : .release_priority = RELEASE_PRIO_RELCACHE_REFS,
2125 : .ReleaseResource = ResOwnerReleaseRelation,
2126 : .DebugPrint = ResOwnerPrintRelCache
2127 : };
2128 :
2129 : /* Convenience wrappers over ResourceOwnerRemember/Forget */
2130 : static inline void
2131 52902022 : ResourceOwnerRememberRelationRef(ResourceOwner owner, Relation rel)
2132 : {
2133 52902022 : ResourceOwnerRemember(owner, PointerGetDatum(rel), &relref_resowner_desc);
2134 52902022 : }
2135 : static inline void
2136 52864598 : ResourceOwnerForgetRelationRef(ResourceOwner owner, Relation rel)
2137 : {
2138 52864598 : ResourceOwnerForget(owner, PointerGetDatum(rel), &relref_resowner_desc);
2139 52864598 : }
2140 :
2141 : /*
2142 : * RelationIncrementReferenceCount
2143 : * Increments relation reference count.
2144 : *
2145 : * Note: bootstrap mode has its own weird ideas about relation refcount
2146 : * behavior; we ought to fix it someday, but for now, just disable
2147 : * reference count ownership tracking in bootstrap mode.
2148 : */
2149 : void
2150 53411872 : RelationIncrementReferenceCount(Relation rel)
2151 : {
2152 53411872 : ResourceOwnerEnlarge(CurrentResourceOwner);
2153 53411872 : rel->rd_refcnt += 1;
2154 53411872 : if (!IsBootstrapProcessingMode())
2155 52902022 : ResourceOwnerRememberRelationRef(CurrentResourceOwner, rel);
2156 53411872 : }
2157 :
2158 : /*
2159 : * RelationDecrementReferenceCount
2160 : * Decrements relation reference count.
2161 : */
2162 : void
2163 53374448 : RelationDecrementReferenceCount(Relation rel)
2164 : {
2165 : Assert(rel->rd_refcnt > 0);
2166 53374448 : rel->rd_refcnt -= 1;
2167 53374448 : if (!IsBootstrapProcessingMode())
2168 52864598 : ResourceOwnerForgetRelationRef(CurrentResourceOwner, rel);
2169 53374448 : }
2170 :
2171 : /*
2172 : * RelationClose - close an open relation
2173 : *
2174 : * Actually, we just decrement the refcount.
2175 : *
2176 : * NOTE: if compiled with -DRELCACHE_FORCE_RELEASE then relcache entries
2177 : * will be freed as soon as their refcount goes to zero. In combination
2178 : * with aset.c's CLOBBER_FREED_MEMORY option, this provides a good test
2179 : * to catch references to already-released relcache entries. It slows
2180 : * things down quite a bit, however.
2181 : */
2182 : void
2183 36146992 : RelationClose(Relation relation)
2184 : {
2185 : /* Note: no locking manipulations needed */
2186 36146992 : RelationDecrementReferenceCount(relation);
2187 :
2188 36146992 : RelationCloseCleanup(relation);
2189 36146992 : }
2190 :
2191 : static void
2192 36184416 : RelationCloseCleanup(Relation relation)
2193 : {
2194 : /*
2195 : * If the relation is no longer open in this session, we can clean up any
2196 : * stale partition descriptors it has. This is unlikely, so check to see
2197 : * if there are child contexts before expending a call to mcxt.c.
2198 : */
2199 36184416 : if (RelationHasReferenceCountZero(relation))
2200 : {
2201 21026958 : if (relation->rd_pdcxt != NULL &&
2202 87158 : relation->rd_pdcxt->firstchild != NULL)
2203 3772 : MemoryContextDeleteChildren(relation->rd_pdcxt);
2204 :
2205 21026958 : if (relation->rd_pddcxt != NULL &&
2206 94 : relation->rd_pddcxt->firstchild != NULL)
2207 0 : MemoryContextDeleteChildren(relation->rd_pddcxt);
2208 : }
2209 :
2210 : #ifdef RELCACHE_FORCE_RELEASE
2211 : if (RelationHasReferenceCountZero(relation) &&
2212 : relation->rd_createSubid == InvalidSubTransactionId &&
2213 : relation->rd_firstRelfilelocatorSubid == InvalidSubTransactionId)
2214 : RelationClearRelation(relation);
2215 : #endif
2216 36184416 : }
2217 :
2218 : /*
2219 : * RelationReloadIndexInfo - reload minimal information for an open index
2220 : *
2221 : * This function is used only for indexes. A relcache inval on an index
2222 : * can mean that its pg_class or pg_index row changed. There are only
2223 : * very limited changes that are allowed to an existing index's schema,
2224 : * so we can update the relcache entry without a complete rebuild; which
2225 : * is fortunate because we can't rebuild an index entry that is "nailed"
2226 : * and/or in active use. We support full replacement of the pg_class row,
2227 : * as well as updates of a few simple fields of the pg_index row.
2228 : *
2229 : * We assume that at the time we are called, we have at least AccessShareLock
2230 : * on the target index.
2231 : *
2232 : * If the target index is an index on pg_class or pg_index, we'd better have
2233 : * previously gotten at least AccessShareLock on its underlying catalog,
2234 : * else we are at risk of deadlock against someone trying to exclusive-lock
2235 : * the heap and index in that order. This is ensured in current usage by
2236 : * only applying this to indexes being opened or having positive refcount.
2237 : */
2238 : static void
2239 107908 : RelationReloadIndexInfo(Relation relation)
2240 : {
2241 : bool indexOK;
2242 : HeapTuple pg_class_tuple;
2243 : Form_pg_class relp;
2244 :
2245 : /* Should be called only for invalidated, live indexes */
2246 : Assert((relation->rd_rel->relkind == RELKIND_INDEX ||
2247 : relation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX) &&
2248 : !relation->rd_isvalid &&
2249 : relation->rd_droppedSubid == InvalidSubTransactionId);
2250 :
2251 : /*
2252 : * If it's a shared index, we might be called before backend startup has
2253 : * finished selecting a database, in which case we have no way to read
2254 : * pg_class yet. However, a shared index can never have any significant
2255 : * schema updates, so it's okay to mostly ignore the invalidation signal.
2256 : * Its physical relfilenumber might've changed, but that's all. Update
2257 : * the physical relfilenumber, mark it valid and return without doing
2258 : * anything more.
2259 : */
2260 107908 : if (relation->rd_rel->relisshared && !criticalRelcachesBuilt)
2261 : {
2262 4 : RelationInitPhysicalAddr(relation);
2263 4 : relation->rd_isvalid = true;
2264 4 : return;
2265 : }
2266 :
2267 : /*
2268 : * Read the pg_class row
2269 : *
2270 : * Don't try to use an indexscan of pg_class_oid_index to reload the info
2271 : * for pg_class_oid_index ...
2272 : */
2273 107904 : indexOK = (RelationGetRelid(relation) != ClassOidIndexId);
2274 107904 : pg_class_tuple = ScanPgRelation(RelationGetRelid(relation), indexOK, false);
2275 107898 : if (!HeapTupleIsValid(pg_class_tuple))
2276 0 : elog(ERROR, "could not find pg_class tuple for index %u",
2277 : RelationGetRelid(relation));
2278 107898 : relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
2279 107898 : memcpy(relation->rd_rel, relp, CLASS_TUPLE_SIZE);
2280 : /* Reload reloptions in case they changed */
2281 107898 : if (relation->rd_options)
2282 1018 : pfree(relation->rd_options);
2283 107898 : RelationParseRelOptions(relation, pg_class_tuple);
2284 : /* done with pg_class tuple */
2285 107898 : heap_freetuple(pg_class_tuple);
2286 : /* We must recalculate physical address in case it changed */
2287 107898 : RelationInitPhysicalAddr(relation);
2288 :
2289 : /*
2290 : * For a non-system index, there are fields of the pg_index row that are
2291 : * allowed to change, so re-read that row and update the relcache entry.
2292 : * Most of the info derived from pg_index (such as support function lookup
2293 : * info) cannot change, and indeed the whole point of this routine is to
2294 : * update the relcache entry without clobbering that data; so wholesale
2295 : * replacement is not appropriate.
2296 : */
2297 107898 : if (!IsSystemRelation(relation))
2298 : {
2299 : HeapTuple tuple;
2300 : Form_pg_index index;
2301 :
2302 39504 : tuple = SearchSysCache1(INDEXRELID,
2303 : ObjectIdGetDatum(RelationGetRelid(relation)));
2304 39504 : if (!HeapTupleIsValid(tuple))
2305 0 : elog(ERROR, "cache lookup failed for index %u",
2306 : RelationGetRelid(relation));
2307 39504 : index = (Form_pg_index) GETSTRUCT(tuple);
2308 :
2309 : /*
2310 : * Basically, let's just copy all the bool fields. There are one or
2311 : * two of these that can't actually change in the current code, but
2312 : * it's not worth it to track exactly which ones they are. None of
2313 : * the array fields are allowed to change, though.
2314 : */
2315 39504 : relation->rd_index->indisunique = index->indisunique;
2316 39504 : relation->rd_index->indnullsnotdistinct = index->indnullsnotdistinct;
2317 39504 : relation->rd_index->indisprimary = index->indisprimary;
2318 39504 : relation->rd_index->indisexclusion = index->indisexclusion;
2319 39504 : relation->rd_index->indimmediate = index->indimmediate;
2320 39504 : relation->rd_index->indisclustered = index->indisclustered;
2321 39504 : relation->rd_index->indisvalid = index->indisvalid;
2322 39504 : relation->rd_index->indcheckxmin = index->indcheckxmin;
2323 39504 : relation->rd_index->indisready = index->indisready;
2324 39504 : relation->rd_index->indislive = index->indislive;
2325 39504 : relation->rd_index->indisreplident = index->indisreplident;
2326 :
2327 : /* Copy xmin too, as that is needed to make sense of indcheckxmin */
2328 39504 : HeapTupleHeaderSetXmin(relation->rd_indextuple->t_data,
2329 : HeapTupleHeaderGetXmin(tuple->t_data));
2330 :
2331 39504 : ReleaseSysCache(tuple);
2332 : }
2333 :
2334 : /* Okay, now it's valid again */
2335 107898 : relation->rd_isvalid = true;
2336 : }
2337 :
2338 : /*
2339 : * RelationReloadNailed - reload minimal information for nailed relations.
2340 : *
2341 : * The structure of a nailed relation can never change (which is good, because
2342 : * we rely on knowing their structure to be able to read catalog content). But
2343 : * some parts, e.g. pg_class.relfrozenxid, are still important to have
2344 : * accurate content for. Therefore those need to be reloaded after the arrival
2345 : * of invalidations.
2346 : */
2347 : static void
2348 142008 : RelationReloadNailed(Relation relation)
2349 : {
2350 : /* Should be called only for invalidated, nailed relations */
2351 : Assert(!relation->rd_isvalid);
2352 : Assert(relation->rd_isnailed);
2353 : /* nailed indexes are handled by RelationReloadIndexInfo() */
2354 : Assert(relation->rd_rel->relkind == RELKIND_RELATION);
2355 : /* can only reread catalog contents in a transaction */
2356 : Assert(IsTransactionState());
2357 :
2358 : /*
2359 : * Redo RelationInitPhysicalAddr in case it is a mapped relation whose
2360 : * mapping changed.
2361 : */
2362 142008 : RelationInitPhysicalAddr(relation);
2363 :
2364 : /*
2365 : * Reload a non-index entry. We can't easily do so if relcaches aren't
2366 : * yet built, but that's fine because at that stage the attributes that
2367 : * need to be current (like relfrozenxid) aren't yet accessed. To ensure
2368 : * the entry will later be revalidated, we leave it in invalid state, but
2369 : * allow use (cf. RelationIdGetRelation()).
2370 : */
2371 142008 : if (criticalRelcachesBuilt)
2372 : {
2373 : HeapTuple pg_class_tuple;
2374 : Form_pg_class relp;
2375 :
2376 : /*
2377 : * NB: Mark the entry as valid before starting to scan, to avoid
2378 : * self-recursion when re-building pg_class.
2379 : */
2380 29086 : relation->rd_isvalid = true;
2381 :
2382 29086 : pg_class_tuple = ScanPgRelation(RelationGetRelid(relation),
2383 : true, false);
2384 29080 : relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
2385 29080 : memcpy(relation->rd_rel, relp, CLASS_TUPLE_SIZE);
2386 29080 : heap_freetuple(pg_class_tuple);
2387 :
2388 : /*
2389 : * Again mark as valid, to protect against concurrently arriving
2390 : * invalidations.
2391 : */
2392 29080 : relation->rd_isvalid = true;
2393 : }
2394 142002 : }
2395 :
2396 : /*
2397 : * RelationDestroyRelation
2398 : *
2399 : * Physically delete a relation cache entry and all subsidiary data.
2400 : * Caller must already have unhooked the entry from the hash table.
2401 : */
2402 : static void
2403 1141374 : RelationDestroyRelation(Relation relation, bool remember_tupdesc)
2404 : {
2405 : Assert(RelationHasReferenceCountZero(relation));
2406 :
2407 : /*
2408 : * Make sure smgr and lower levels close the relation's files, if they
2409 : * weren't closed already. (This was probably done by caller, but let's
2410 : * just be real sure.)
2411 : */
2412 1141374 : RelationCloseSmgr(relation);
2413 :
2414 : /* break mutual link with stats entry */
2415 1141374 : pgstat_unlink_relation(relation);
2416 :
2417 : /*
2418 : * Free all the subsidiary data structures of the relcache entry, then the
2419 : * entry itself.
2420 : */
2421 1141374 : if (relation->rd_rel)
2422 1141374 : pfree(relation->rd_rel);
2423 : /* can't use DecrTupleDescRefCount here */
2424 : Assert(relation->rd_att->tdrefcount > 0);
2425 1141374 : if (--relation->rd_att->tdrefcount == 0)
2426 : {
2427 : /*
2428 : * If we Rebuilt a relcache entry during a transaction then its
2429 : * possible we did that because the TupDesc changed as the result of
2430 : * an ALTER TABLE that ran at less than AccessExclusiveLock. It's
2431 : * possible someone copied that TupDesc, in which case the copy would
2432 : * point to free'd memory. So if we rebuild an entry we keep the
2433 : * TupDesc around until end of transaction, to be safe.
2434 : */
2435 1138534 : if (remember_tupdesc)
2436 17194 : RememberToFreeTupleDescAtEOX(relation->rd_att);
2437 : else
2438 1121340 : FreeTupleDesc(relation->rd_att);
2439 : }
2440 1141374 : FreeTriggerDesc(relation->trigdesc);
2441 1141374 : list_free_deep(relation->rd_fkeylist);
2442 1141374 : list_free(relation->rd_indexlist);
2443 1141374 : list_free(relation->rd_statlist);
2444 1141374 : bms_free(relation->rd_keyattr);
2445 1141374 : bms_free(relation->rd_pkattr);
2446 1141374 : bms_free(relation->rd_idattr);
2447 1141374 : bms_free(relation->rd_hotblockingattr);
2448 1141374 : bms_free(relation->rd_summarizedattr);
2449 1141374 : if (relation->rd_pubdesc)
2450 6464 : pfree(relation->rd_pubdesc);
2451 1141374 : if (relation->rd_options)
2452 9658 : pfree(relation->rd_options);
2453 1141374 : if (relation->rd_indextuple)
2454 323802 : pfree(relation->rd_indextuple);
2455 1141374 : if (relation->rd_amcache)
2456 0 : pfree(relation->rd_amcache);
2457 1141374 : if (relation->rd_fdwroutine)
2458 278 : pfree(relation->rd_fdwroutine);
2459 1141374 : if (relation->rd_indexcxt)
2460 323802 : MemoryContextDelete(relation->rd_indexcxt);
2461 1141374 : if (relation->rd_rulescxt)
2462 23340 : MemoryContextDelete(relation->rd_rulescxt);
2463 1141374 : if (relation->rd_rsdesc)
2464 1778 : MemoryContextDelete(relation->rd_rsdesc->rscxt);
2465 1141374 : if (relation->rd_partkeycxt)
2466 15458 : MemoryContextDelete(relation->rd_partkeycxt);
2467 1141374 : if (relation->rd_pdcxt)
2468 14946 : MemoryContextDelete(relation->rd_pdcxt);
2469 1141374 : if (relation->rd_pddcxt)
2470 60 : MemoryContextDelete(relation->rd_pddcxt);
2471 1141374 : if (relation->rd_partcheckcxt)
2472 2842 : MemoryContextDelete(relation->rd_partcheckcxt);
2473 1141374 : pfree(relation);
2474 1141374 : }
2475 :
2476 : /*
2477 : * RelationInvalidateRelation - mark a relation cache entry as invalid
2478 : *
2479 : * An entry that's marked as invalid will be reloaded on next access.
2480 : */
2481 : static void
2482 1510138 : RelationInvalidateRelation(Relation relation)
2483 : {
2484 : /*
2485 : * Make sure smgr and lower levels close the relation's files, if they
2486 : * weren't closed already. If the relation is not getting deleted, the
2487 : * next smgr access should reopen the files automatically. This ensures
2488 : * that the low-level file access state is updated after, say, a vacuum
2489 : * truncation.
2490 : */
2491 1510138 : RelationCloseSmgr(relation);
2492 :
2493 : /* Free AM cached data, if any */
2494 1510138 : if (relation->rd_amcache)
2495 64882 : pfree(relation->rd_amcache);
2496 1510138 : relation->rd_amcache = NULL;
2497 :
2498 1510138 : relation->rd_isvalid = false;
2499 1510138 : }
2500 :
2501 : /*
2502 : * RelationClearRelation - physically blow away a relation cache entry
2503 : *
2504 : * The caller must ensure that the entry is no longer needed, i.e. its
2505 : * reference count is zero. Also, the rel or its storage must not be created
2506 : * in the current transaction (rd_createSubid and rd_firstRelfilelocatorSubid
2507 : * must not be set).
2508 : */
2509 : static void
2510 756832 : RelationClearRelation(Relation relation)
2511 : {
2512 : Assert(RelationHasReferenceCountZero(relation));
2513 : Assert(!relation->rd_isnailed);
2514 :
2515 : /*
2516 : * Relations created in the same transaction must never be removed, see
2517 : * RelationFlushRelation.
2518 : */
2519 : Assert(relation->rd_createSubid == InvalidSubTransactionId);
2520 : Assert(relation->rd_firstRelfilelocatorSubid == InvalidSubTransactionId);
2521 : Assert(relation->rd_droppedSubid == InvalidSubTransactionId);
2522 :
2523 : /* first mark it as invalid */
2524 756832 : RelationInvalidateRelation(relation);
2525 :
2526 : /* Remove it from the hash table */
2527 756832 : RelationCacheDelete(relation);
2528 :
2529 : /* And release storage */
2530 756832 : RelationDestroyRelation(relation, false);
2531 756832 : }
2532 :
2533 : /*
2534 : * RelationRebuildRelation - rebuild a relation cache entry in place
2535 : *
2536 : * Reset and rebuild a relation cache entry from scratch (that is, from
2537 : * catalog entries). This is used when we are notified of a change to an open
2538 : * relation (one with refcount > 0). The entry is reconstructed without
2539 : * moving the physical RelationData record, so that the refcount holder's
2540 : * pointer is still valid.
2541 : *
2542 : * NB: when rebuilding, we'd better hold some lock on the relation, else the
2543 : * catalog data we need to read could be changing under us. Also, a rel to be
2544 : * rebuilt had better have refcnt > 0. This is because a sinval reset could
2545 : * happen while we're accessing the catalogs, and the rel would get blown away
2546 : * underneath us by RelationCacheInvalidate if it has zero refcnt.
2547 : */
2548 : static void
2549 634450 : RelationRebuildRelation(Relation relation)
2550 : {
2551 : Assert(!RelationHasReferenceCountZero(relation));
2552 : /* rebuilding requires access to the catalogs */
2553 : Assert(IsTransactionState());
2554 : /* there is no reason to ever rebuild a dropped relation */
2555 : Assert(relation->rd_droppedSubid == InvalidSubTransactionId);
2556 :
2557 : /* Close and mark it as invalid until we've finished the rebuild */
2558 634450 : RelationInvalidateRelation(relation);
2559 :
2560 : /*
2561 : * Indexes only have a limited number of possible schema changes, and we
2562 : * don't want to use the full-blown procedure because it's a headache for
2563 : * indexes that reload itself depends on.
2564 : *
2565 : * As an exception, use the full procedure if the index access info hasn't
2566 : * been initialized yet. Index creation relies on that: it first builds
2567 : * the relcache entry with RelationBuildLocalRelation(), creates the
2568 : * pg_index tuple only after that, and then relies on
2569 : * CommandCounterIncrement to load the pg_index contents.
2570 : */
2571 634450 : if ((relation->rd_rel->relkind == RELKIND_INDEX ||
2572 501084 : relation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX) &&
2573 138476 : relation->rd_indexcxt != NULL)
2574 : {
2575 107908 : RelationReloadIndexInfo(relation);
2576 107902 : return;
2577 : }
2578 : /* Nailed relations are handled separately. */
2579 526542 : else if (relation->rd_isnailed)
2580 : {
2581 142008 : RelationReloadNailed(relation);
2582 142002 : return;
2583 : }
2584 : else
2585 : {
2586 : /*
2587 : * Our strategy for rebuilding an open relcache entry is to build a
2588 : * new entry from scratch, swap its contents with the old entry, and
2589 : * finally delete the new entry (along with any infrastructure swapped
2590 : * over from the old entry). This is to avoid trouble in case an
2591 : * error causes us to lose control partway through. The old entry
2592 : * will still be marked !rd_isvalid, so we'll try to rebuild it again
2593 : * on next access. Meanwhile it's not any less valid than it was
2594 : * before, so any code that might expect to continue accessing it
2595 : * isn't hurt by the rebuild failure. (Consider for example a
2596 : * subtransaction that ALTERs a table and then gets canceled partway
2597 : * through the cache entry rebuild. The outer transaction should
2598 : * still see the not-modified cache entry as valid.) The worst
2599 : * consequence of an error is leaking the necessarily-unreferenced new
2600 : * entry, and this shouldn't happen often enough for that to be a big
2601 : * problem.
2602 : *
2603 : * When rebuilding an open relcache entry, we must preserve ref count,
2604 : * rd_*Subid, and rd_toastoid state. Also attempt to preserve the
2605 : * pg_class entry (rd_rel), tupledesc, rewrite-rule, partition key,
2606 : * and partition descriptor substructures in place, because various
2607 : * places assume that these structures won't move while they are
2608 : * working with an open relcache entry. (Note: the refcount
2609 : * mechanism for tupledescs might someday allow us to remove this hack
2610 : * for the tupledesc.)
2611 : *
2612 : * Note that this process does not touch CurrentResourceOwner; which
2613 : * is good because whatever ref counts the entry may have do not
2614 : * necessarily belong to that resource owner.
2615 : */
2616 : Relation newrel;
2617 384534 : Oid save_relid = RelationGetRelid(relation);
2618 : bool keep_tupdesc;
2619 : bool keep_rules;
2620 : bool keep_policies;
2621 : bool keep_partkey;
2622 :
2623 : /* Build temporary entry, but don't link it into hashtable */
2624 384534 : newrel = RelationBuildDesc(save_relid, false);
2625 :
2626 : /*
2627 : * Between here and the end of the swap, don't add code that does or
2628 : * reasonably could read system catalogs. That range must be free
2629 : * from invalidation processing. See RelationBuildDesc() manipulation
2630 : * of in_progress_list.
2631 : */
2632 :
2633 384528 : if (newrel == NULL)
2634 : {
2635 : /*
2636 : * We can validly get here, if we're using a historic snapshot in
2637 : * which a relation, accessed from outside logical decoding, is
2638 : * still invisible. In that case it's fine to just mark the
2639 : * relation as invalid and return - it'll fully get reloaded by
2640 : * the cache reset at the end of logical decoding (or at the next
2641 : * access). During normal processing we don't want to ignore this
2642 : * case as it shouldn't happen there, as explained below.
2643 : */
2644 0 : if (HistoricSnapshotActive())
2645 0 : return;
2646 :
2647 : /*
2648 : * This shouldn't happen as dropping a relation is intended to be
2649 : * impossible if still referenced (cf. CheckTableNotInUse()). But
2650 : * if we get here anyway, we can't just delete the relcache entry,
2651 : * as it possibly could get accessed later (as e.g. the error
2652 : * might get trapped and handled via a subtransaction rollback).
2653 : */
2654 0 : elog(ERROR, "relation %u deleted while still in use", save_relid);
2655 : }
2656 :
2657 : /*
2658 : * If we were to, again, have cases of the relkind of a relcache entry
2659 : * changing, we would need to ensure that pgstats does not get
2660 : * confused.
2661 : */
2662 : Assert(relation->rd_rel->relkind == newrel->rd_rel->relkind);
2663 :
2664 384528 : keep_tupdesc = equalTupleDescs(relation->rd_att, newrel->rd_att);
2665 384528 : keep_rules = equalRuleLocks(relation->rd_rules, newrel->rd_rules);
2666 384528 : keep_policies = equalRSDesc(relation->rd_rsdesc, newrel->rd_rsdesc);
2667 : /* partkey is immutable once set up, so we can always keep it */
2668 384528 : keep_partkey = (relation->rd_partkey != NULL);
2669 :
2670 : /*
2671 : * Perform swapping of the relcache entry contents. Within this
2672 : * process the old entry is momentarily invalid, so there *must* be no
2673 : * possibility of CHECK_FOR_INTERRUPTS within this sequence. Do it in
2674 : * all-in-line code for safety.
2675 : *
2676 : * Since the vast majority of fields should be swapped, our method is
2677 : * to swap the whole structures and then re-swap those few fields we
2678 : * didn't want swapped.
2679 : */
2680 : #define SWAPFIELD(fldtype, fldname) \
2681 : do { \
2682 : fldtype _tmp = newrel->fldname; \
2683 : newrel->fldname = relation->fldname; \
2684 : relation->fldname = _tmp; \
2685 : } while (0)
2686 :
2687 : /* swap all Relation struct fields */
2688 : {
2689 : RelationData tmpstruct;
2690 :
2691 384528 : memcpy(&tmpstruct, newrel, sizeof(RelationData));
2692 384528 : memcpy(newrel, relation, sizeof(RelationData));
2693 384528 : memcpy(relation, &tmpstruct, sizeof(RelationData));
2694 : }
2695 :
2696 : /* rd_smgr must not be swapped, due to back-links from smgr level */
2697 384528 : SWAPFIELD(SMgrRelation, rd_smgr);
2698 : /* rd_refcnt must be preserved */
2699 384528 : SWAPFIELD(int, rd_refcnt);
2700 : /* isnailed shouldn't change */
2701 : Assert(newrel->rd_isnailed == relation->rd_isnailed);
2702 : /* creation sub-XIDs must be preserved */
2703 384528 : SWAPFIELD(SubTransactionId, rd_createSubid);
2704 384528 : SWAPFIELD(SubTransactionId, rd_newRelfilelocatorSubid);
2705 384528 : SWAPFIELD(SubTransactionId, rd_firstRelfilelocatorSubid);
2706 384528 : SWAPFIELD(SubTransactionId, rd_droppedSubid);
2707 : /* un-swap rd_rel pointers, swap contents instead */
2708 384528 : SWAPFIELD(Form_pg_class, rd_rel);
2709 : /* ... but actually, we don't have to update newrel->rd_rel */
2710 384528 : memcpy(relation->rd_rel, newrel->rd_rel, CLASS_TUPLE_SIZE);
2711 : /* preserve old tupledesc, rules, policies if no logical change */
2712 384528 : if (keep_tupdesc)
2713 367128 : SWAPFIELD(TupleDesc, rd_att);
2714 384528 : if (keep_rules)
2715 : {
2716 368876 : SWAPFIELD(RuleLock *, rd_rules);
2717 368876 : SWAPFIELD(MemoryContext, rd_rulescxt);
2718 : }
2719 384528 : if (keep_policies)
2720 384228 : SWAPFIELD(RowSecurityDesc *, rd_rsdesc);
2721 : /* toast OID override must be preserved */
2722 384528 : SWAPFIELD(Oid, rd_toastoid);
2723 : /* pgstat_info / enabled must be preserved */
2724 384528 : SWAPFIELD(struct PgStat_TableStatus *, pgstat_info);
2725 384528 : SWAPFIELD(bool, pgstat_enabled);
2726 : /* preserve old partition key if we have one */
2727 384528 : if (keep_partkey)
2728 : {
2729 13474 : SWAPFIELD(PartitionKey, rd_partkey);
2730 13474 : SWAPFIELD(MemoryContext, rd_partkeycxt);
2731 : }
2732 384528 : if (newrel->rd_pdcxt != NULL || newrel->rd_pddcxt != NULL)
2733 : {
2734 : /*
2735 : * We are rebuilding a partitioned relation with a non-zero
2736 : * reference count, so we must keep the old partition descriptor
2737 : * around, in case there's a PartitionDirectory with a pointer to
2738 : * it. This means we can't free the old rd_pdcxt yet. (This is
2739 : * necessary because RelationGetPartitionDesc hands out direct
2740 : * pointers to the relcache's data structure, unlike our usual
2741 : * practice which is to hand out copies. We'd have the same
2742 : * problem with rd_partkey, except that we always preserve that
2743 : * once created.)
2744 : *
2745 : * To ensure that it's not leaked completely, re-attach it to the
2746 : * new reldesc, or make it a child of the new reldesc's rd_pdcxt
2747 : * in the unlikely event that there is one already. (Compare hack
2748 : * in RelationBuildPartitionDesc.) RelationClose will clean up
2749 : * any such contexts once the reference count reaches zero.
2750 : *
2751 : * In the case where the reference count is zero, this code is not
2752 : * reached, which should be OK because in that case there should
2753 : * be no PartitionDirectory with a pointer to the old entry.
2754 : *
2755 : * Note that newrel and relation have already been swapped, so the
2756 : * "old" partition descriptor is actually the one hanging off of
2757 : * newrel.
2758 : */
2759 10140 : relation->rd_partdesc = NULL; /* ensure rd_partdesc is invalid */
2760 10140 : relation->rd_partdesc_nodetached = NULL;
2761 10140 : relation->rd_partdesc_nodetached_xmin = InvalidTransactionId;
2762 10140 : if (relation->rd_pdcxt != NULL) /* probably never happens */
2763 0 : MemoryContextSetParent(newrel->rd_pdcxt, relation->rd_pdcxt);
2764 : else
2765 10140 : relation->rd_pdcxt = newrel->rd_pdcxt;
2766 10140 : if (relation->rd_pddcxt != NULL)
2767 0 : MemoryContextSetParent(newrel->rd_pddcxt, relation->rd_pddcxt);
2768 : else
2769 10140 : relation->rd_pddcxt = newrel->rd_pddcxt;
2770 : /* drop newrel's pointers so we don't destroy it below */
2771 10140 : newrel->rd_partdesc = NULL;
2772 10140 : newrel->rd_partdesc_nodetached = NULL;
2773 10140 : newrel->rd_partdesc_nodetached_xmin = InvalidTransactionId;
2774 10140 : newrel->rd_pdcxt = NULL;
2775 10140 : newrel->rd_pddcxt = NULL;
2776 : }
2777 :
2778 : #undef SWAPFIELD
2779 :
2780 : /* And now we can throw away the temporary entry */
2781 384528 : RelationDestroyRelation(newrel, !keep_tupdesc);
2782 : }
2783 : }
2784 :
2785 : /*
2786 : * RelationFlushRelation
2787 : *
2788 : * Rebuild the relation if it is open (refcount > 0), else blow it away.
2789 : * This is used when we receive a cache invalidation event for the rel.
2790 : */
2791 : static void
2792 796210 : RelationFlushRelation(Relation relation)
2793 : {
2794 796210 : if (relation->rd_createSubid != InvalidSubTransactionId ||
2795 487710 : relation->rd_firstRelfilelocatorSubid != InvalidSubTransactionId)
2796 : {
2797 : /*
2798 : * New relcache entries are always rebuilt, not flushed; else we'd
2799 : * forget the "new" status of the relation. Ditto for the
2800 : * new-relfilenumber status.
2801 : */
2802 325396 : if (IsTransactionState() && relation->rd_droppedSubid == InvalidSubTransactionId)
2803 : {
2804 : /*
2805 : * The rel could have zero refcnt here, so temporarily increment
2806 : * the refcnt to ensure it's safe to rebuild it. We can assume
2807 : * that the current transaction has some lock on the rel already.
2808 : */
2809 323576 : RelationIncrementReferenceCount(relation);
2810 323576 : RelationRebuildRelation(relation);
2811 323570 : RelationDecrementReferenceCount(relation);
2812 : }
2813 : else
2814 1820 : RelationInvalidateRelation(relation);
2815 : }
2816 : else
2817 : {
2818 : /*
2819 : * Pre-existing rels can be dropped from the relcache if not open.
2820 : *
2821 : * If the entry is in use, rebuild it if possible. If we're not
2822 : * inside a valid transaction, we can't do any catalog access so it's
2823 : * not possible to rebuild yet. Just mark it as invalid in that case,
2824 : * so that the rebuild will occur when the entry is next opened.
2825 : *
2826 : * Note: it's possible that we come here during subtransaction abort,
2827 : * and the reason for wanting to rebuild is that the rel is open in
2828 : * the outer transaction. In that case it might seem unsafe to not
2829 : * rebuild immediately, since whatever code has the rel already open
2830 : * will keep on using the relcache entry as-is. However, in such a
2831 : * case the outer transaction should be holding a lock that's
2832 : * sufficient to prevent any significant change in the rel's schema,
2833 : * so the existing entry contents should be good enough for its
2834 : * purposes; at worst we might be behind on statistics updates or the
2835 : * like. (See also CheckTableNotInUse() and its callers.)
2836 : */
2837 470814 : if (RelationHasReferenceCountZero(relation))
2838 296118 : RelationClearRelation(relation);
2839 174696 : else if (!IsTransactionState())
2840 18264 : RelationInvalidateRelation(relation);
2841 156432 : else if (relation->rd_isnailed && relation->rd_refcnt == 1)
2842 : {
2843 : /*
2844 : * A nailed relation with refcnt == 1 is unused. We cannot clear
2845 : * it, but there's also no need no need to rebuild it immediately.
2846 : */
2847 1770 : RelationInvalidateRelation(relation);
2848 : }
2849 : else
2850 154662 : RelationRebuildRelation(relation);
2851 : }
2852 796204 : }
2853 :
2854 : /*
2855 : * RelationForgetRelation - caller reports that it dropped the relation
2856 : */
2857 : void
2858 68092 : RelationForgetRelation(Oid rid)
2859 : {
2860 : Relation relation;
2861 :
2862 68092 : RelationIdCacheLookup(rid, relation);
2863 :
2864 68092 : if (!PointerIsValid(relation))
2865 0 : return; /* not in cache, nothing to do */
2866 :
2867 68092 : if (!RelationHasReferenceCountZero(relation))
2868 0 : elog(ERROR, "relation %u is still open", rid);
2869 :
2870 : Assert(relation->rd_droppedSubid == InvalidSubTransactionId);
2871 68092 : if (relation->rd_createSubid != InvalidSubTransactionId ||
2872 66550 : relation->rd_firstRelfilelocatorSubid != InvalidSubTransactionId)
2873 : {
2874 : /*
2875 : * In the event of subtransaction rollback, we must not forget
2876 : * rd_*Subid. Mark the entry "dropped" and invalidate it, instead of
2877 : * destroying it right away. (If we're in a top transaction, we could
2878 : * opt to destroy the entry.)
2879 : */
2880 1570 : relation->rd_droppedSubid = GetCurrentSubTransactionId();
2881 1570 : RelationInvalidateRelation(relation);
2882 : }
2883 : else
2884 66522 : RelationClearRelation(relation);
2885 : }
2886 :
2887 : /*
2888 : * RelationCacheInvalidateEntry
2889 : *
2890 : * This routine is invoked for SI cache flush messages.
2891 : *
2892 : * Any relcache entry matching the relid must be flushed. (Note: caller has
2893 : * already determined that the relid belongs to our database or is a shared
2894 : * relation.)
2895 : *
2896 : * We used to skip local relations, on the grounds that they could
2897 : * not be targets of cross-backend SI update messages; but it seems
2898 : * safer to process them, so that our *own* SI update messages will
2899 : * have the same effects during CommandCounterIncrement for both
2900 : * local and nonlocal relations.
2901 : */
2902 : void
2903 2538440 : RelationCacheInvalidateEntry(Oid relationId)
2904 : {
2905 : Relation relation;
2906 :
2907 2538440 : RelationIdCacheLookup(relationId, relation);
2908 :
2909 2538440 : if (PointerIsValid(relation))
2910 : {
2911 796210 : relcacheInvalsReceived++;
2912 796210 : RelationFlushRelation(relation);
2913 : }
2914 : else
2915 : {
2916 : int i;
2917 :
2918 1773624 : for (i = 0; i < in_progress_list_len; i++)
2919 31394 : if (in_progress_list[i].reloid == relationId)
2920 14 : in_progress_list[i].invalidated = true;
2921 : }
2922 2538434 : }
2923 :
2924 : /*
2925 : * RelationCacheInvalidate
2926 : * Blow away cached relation descriptors that have zero reference counts,
2927 : * and rebuild those with positive reference counts. Also reset the smgr
2928 : * relation cache and re-read relation mapping data.
2929 : *
2930 : * Apart from debug_discard_caches, this is currently used only to recover
2931 : * from SI message buffer overflow, so we do not touch relations having
2932 : * new-in-transaction relfilenumbers; they cannot be targets of cross-backend
2933 : * SI updates (and our own updates now go through a separate linked list
2934 : * that isn't limited by the SI message buffer size).
2935 : *
2936 : * We do this in two phases: the first pass deletes deletable items, and
2937 : * the second one rebuilds the rebuildable items. This is essential for
2938 : * safety, because hash_seq_search only copes with concurrent deletion of
2939 : * the element it is currently visiting. If a second SI overflow were to
2940 : * occur while we are walking the table, resulting in recursive entry to
2941 : * this routine, we could crash because the inner invocation blows away
2942 : * the entry next to be visited by the outer scan. But this way is OK,
2943 : * because (a) during the first pass we won't process any more SI messages,
2944 : * so hash_seq_search will complete safely; (b) during the second pass we
2945 : * only hold onto pointers to nondeletable entries.
2946 : *
2947 : * The two-phase approach also makes it easy to update relfilenumbers for
2948 : * mapped relations before we do anything else, and to ensure that the
2949 : * second pass processes nailed-in-cache items before other nondeletable
2950 : * items. This should ensure that system catalogs are up to date before
2951 : * we attempt to use them to reload information about other open relations.
2952 : *
2953 : * After those two phases of work having immediate effects, we normally
2954 : * signal any RelationBuildDesc() on the stack to start over. However, we
2955 : * don't do this if called as part of debug_discard_caches. Otherwise,
2956 : * RelationBuildDesc() would become an infinite loop.
2957 : */
2958 : void
2959 4442 : RelationCacheInvalidate(bool debug_discard)
2960 : {
2961 : HASH_SEQ_STATUS status;
2962 : RelIdCacheEnt *idhentry;
2963 : Relation relation;
2964 4442 : List *rebuildFirstList = NIL;
2965 4442 : List *rebuildList = NIL;
2966 : ListCell *l;
2967 : int i;
2968 :
2969 : /*
2970 : * Reload relation mapping data before starting to reconstruct cache.
2971 : */
2972 4442 : RelationMapInvalidateAll();
2973 :
2974 : /* Phase 1 */
2975 4442 : hash_seq_init(&status, RelationIdCache);
2976 :
2977 489018 : while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
2978 : {
2979 484576 : relation = idhentry->reldesc;
2980 :
2981 : /*
2982 : * Ignore new relations; no other backend will manipulate them before
2983 : * we commit. Likewise, before replacing a relation's relfilelocator,
2984 : * we shall have acquired AccessExclusiveLock and drained any
2985 : * applicable pending invalidations.
2986 : */
2987 484576 : if (relation->rd_createSubid != InvalidSubTransactionId ||
2988 484490 : relation->rd_firstRelfilelocatorSubid != InvalidSubTransactionId)
2989 102 : continue;
2990 :
2991 484474 : relcacheInvalsReceived++;
2992 :
2993 484474 : if (RelationHasReferenceCountZero(relation))
2994 : {
2995 : /* Delete this entry immediately */
2996 388864 : RelationClearRelation(relation);
2997 : }
2998 : else
2999 : {
3000 : /*
3001 : * If it's a mapped relation, immediately update its rd_locator in
3002 : * case its relfilenumber changed. We must do this during phase 1
3003 : * in case the relation is consulted during rebuild of other
3004 : * relcache entries in phase 2. It's safe since consulting the
3005 : * map doesn't involve any access to relcache entries.
3006 : */
3007 95610 : if (RelationIsMapped(relation))
3008 : {
3009 73946 : RelationCloseSmgr(relation);
3010 73946 : RelationInitPhysicalAddr(relation);
3011 : }
3012 :
3013 : /*
3014 : * Add this entry to list of stuff to rebuild in second pass.
3015 : * pg_class goes to the front of rebuildFirstList while
3016 : * pg_class_oid_index goes to the back of rebuildFirstList, so
3017 : * they are done first and second respectively. Other nailed
3018 : * relations go to the front of rebuildList, so they'll be done
3019 : * next in no particular order; and everything else goes to the
3020 : * back of rebuildList.
3021 : */
3022 95610 : if (RelationGetRelid(relation) == RelationRelationId)
3023 4310 : rebuildFirstList = lcons(relation, rebuildFirstList);
3024 91300 : else if (RelationGetRelid(relation) == ClassOidIndexId)
3025 4308 : rebuildFirstList = lappend(rebuildFirstList, relation);
3026 86992 : else if (relation->rd_isnailed)
3027 86860 : rebuildList = lcons(relation, rebuildList);
3028 : else
3029 132 : rebuildList = lappend(rebuildList, relation);
3030 : }
3031 : }
3032 :
3033 : /*
3034 : * We cannot destroy the SMgrRelations as there might still be references
3035 : * to them, but close the underlying file descriptors.
3036 : */
3037 4442 : smgrreleaseall();
3038 :
3039 : /*
3040 : * Phase 2: rebuild (or invalidate) the items found to need rebuild in
3041 : * phase 1
3042 : */
3043 13060 : foreach(l, rebuildFirstList)
3044 : {
3045 8618 : relation = (Relation) lfirst(l);
3046 8618 : if (!IsTransactionState() || (relation->rd_isnailed && relation->rd_refcnt == 1))
3047 8618 : RelationInvalidateRelation(relation);
3048 : else
3049 0 : RelationRebuildRelation(relation);
3050 : }
3051 4442 : list_free(rebuildFirstList);
3052 91434 : foreach(l, rebuildList)
3053 : {
3054 86992 : relation = (Relation) lfirst(l);
3055 86992 : if (!IsTransactionState() || (relation->rd_isnailed && relation->rd_refcnt == 1))
3056 86814 : RelationInvalidateRelation(relation);
3057 : else
3058 178 : RelationRebuildRelation(relation);
3059 : }
3060 4442 : list_free(rebuildList);
3061 :
3062 4442 : if (!debug_discard)
3063 : /* Any RelationBuildDesc() on the stack must start over. */
3064 4448 : for (i = 0; i < in_progress_list_len; i++)
3065 6 : in_progress_list[i].invalidated = true;
3066 4442 : }
3067 :
3068 : static void
3069 17194 : RememberToFreeTupleDescAtEOX(TupleDesc td)
3070 : {
3071 17194 : if (EOXactTupleDescArray == NULL)
3072 : {
3073 : MemoryContext oldcxt;
3074 :
3075 10134 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3076 :
3077 10134 : EOXactTupleDescArray = (TupleDesc *) palloc(16 * sizeof(TupleDesc));
3078 10134 : EOXactTupleDescArrayLen = 16;
3079 10134 : NextEOXactTupleDescNum = 0;
3080 10134 : MemoryContextSwitchTo(oldcxt);
3081 : }
3082 7060 : else if (NextEOXactTupleDescNum >= EOXactTupleDescArrayLen)
3083 : {
3084 54 : int32 newlen = EOXactTupleDescArrayLen * 2;
3085 :
3086 : Assert(EOXactTupleDescArrayLen > 0);
3087 :
3088 54 : EOXactTupleDescArray = (TupleDesc *) repalloc(EOXactTupleDescArray,
3089 : newlen * sizeof(TupleDesc));
3090 54 : EOXactTupleDescArrayLen = newlen;
3091 : }
3092 :
3093 17194 : EOXactTupleDescArray[NextEOXactTupleDescNum++] = td;
3094 17194 : }
3095 :
3096 : #ifdef USE_ASSERT_CHECKING
3097 : static void
3098 : AssertPendingSyncConsistency(Relation relation)
3099 : {
3100 : bool relcache_verdict =
3101 : RelationIsPermanent(relation) &&
3102 : ((relation->rd_createSubid != InvalidSubTransactionId &&
3103 : RELKIND_HAS_STORAGE(relation->rd_rel->relkind)) ||
3104 : relation->rd_firstRelfilelocatorSubid != InvalidSubTransactionId);
3105 :
3106 : Assert(relcache_verdict == RelFileLocatorSkippingWAL(relation->rd_locator));
3107 :
3108 : if (relation->rd_droppedSubid != InvalidSubTransactionId)
3109 : Assert(!relation->rd_isvalid &&
3110 : (relation->rd_createSubid != InvalidSubTransactionId ||
3111 : relation->rd_firstRelfilelocatorSubid != InvalidSubTransactionId));
3112 : }
3113 :
3114 : /*
3115 : * AssertPendingSyncs_RelationCache
3116 : *
3117 : * Assert that relcache.c and storage.c agree on whether to skip WAL.
3118 : */
3119 : void
3120 : AssertPendingSyncs_RelationCache(void)
3121 : {
3122 : HASH_SEQ_STATUS status;
3123 : LOCALLOCK *locallock;
3124 : Relation *rels;
3125 : int maxrels;
3126 : int nrels;
3127 : RelIdCacheEnt *idhentry;
3128 : int i;
3129 :
3130 : /*
3131 : * Open every relation that this transaction has locked. If, for some
3132 : * relation, storage.c is skipping WAL and relcache.c is not skipping WAL,
3133 : * a CommandCounterIncrement() typically yields a local invalidation
3134 : * message that destroys the relcache entry. By recreating such entries
3135 : * here, we detect the problem.
3136 : */
3137 : PushActiveSnapshot(GetTransactionSnapshot());
3138 : maxrels = 1;
3139 : rels = palloc(maxrels * sizeof(*rels));
3140 : nrels = 0;
3141 : hash_seq_init(&status, GetLockMethodLocalHash());
3142 : while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
3143 : {
3144 : Oid relid;
3145 : Relation r;
3146 :
3147 : if (locallock->nLocks <= 0)
3148 : continue;
3149 : if ((LockTagType) locallock->tag.lock.locktag_type !=
3150 : LOCKTAG_RELATION)
3151 : continue;
3152 : relid = ObjectIdGetDatum(locallock->tag.lock.locktag_field2);
3153 : r = RelationIdGetRelation(relid);
3154 : if (!RelationIsValid(r))
3155 : continue;
3156 : if (nrels >= maxrels)
3157 : {
3158 : maxrels *= 2;
3159 : rels = repalloc(rels, maxrels * sizeof(*rels));
3160 : }
3161 : rels[nrels++] = r;
3162 : }
3163 :
3164 : hash_seq_init(&status, RelationIdCache);
3165 : while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3166 : AssertPendingSyncConsistency(idhentry->reldesc);
3167 :
3168 : for (i = 0; i < nrels; i++)
3169 : RelationClose(rels[i]);
3170 : PopActiveSnapshot();
3171 : }
3172 : #endif
3173 :
3174 : /*
3175 : * AtEOXact_RelationCache
3176 : *
3177 : * Clean up the relcache at main-transaction commit or abort.
3178 : *
3179 : * Note: this must be called *before* processing invalidation messages.
3180 : * In the case of abort, we don't want to try to rebuild any invalidated
3181 : * cache entries (since we can't safely do database accesses). Therefore
3182 : * we must reset refcnts before handling pending invalidations.
3183 : *
3184 : * As of PostgreSQL 8.1, relcache refcnts should get released by the
3185 : * ResourceOwner mechanism. This routine just does a debugging
3186 : * cross-check that no pins remain. However, we also need to do special
3187 : * cleanup when the current transaction created any relations or made use
3188 : * of forced index lists.
3189 : */
3190 : void
3191 746658 : AtEOXact_RelationCache(bool isCommit)
3192 : {
3193 : HASH_SEQ_STATUS status;
3194 : RelIdCacheEnt *idhentry;
3195 : int i;
3196 :
3197 : /*
3198 : * Forget in_progress_list. This is relevant when we're aborting due to
3199 : * an error during RelationBuildDesc().
3200 : */
3201 : Assert(in_progress_list_len == 0 || !isCommit);
3202 746658 : in_progress_list_len = 0;
3203 :
3204 : /*
3205 : * Unless the eoxact_list[] overflowed, we only need to examine the rels
3206 : * listed in it. Otherwise fall back on a hash_seq_search scan.
3207 : *
3208 : * For simplicity, eoxact_list[] entries are not deleted till end of
3209 : * top-level transaction, even though we could remove them at
3210 : * subtransaction end in some cases, or remove relations from the list if
3211 : * they are cleared for other reasons. Therefore we should expect the
3212 : * case that list entries are not found in the hashtable; if not, there's
3213 : * nothing to do for them.
3214 : */
3215 746658 : if (eoxact_list_overflowed)
3216 : {
3217 140 : hash_seq_init(&status, RelationIdCache);
3218 37948 : while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3219 : {
3220 37808 : AtEOXact_cleanup(idhentry->reldesc, isCommit);
3221 : }
3222 : }
3223 : else
3224 : {
3225 858512 : for (i = 0; i < eoxact_list_len; i++)
3226 : {
3227 111994 : idhentry = (RelIdCacheEnt *) hash_search(RelationIdCache,
3228 111994 : &eoxact_list[i],
3229 : HASH_FIND,
3230 : NULL);
3231 111994 : if (idhentry != NULL)
3232 109880 : AtEOXact_cleanup(idhentry->reldesc, isCommit);
3233 : }
3234 : }
3235 :
3236 746658 : if (EOXactTupleDescArrayLen > 0)
3237 : {
3238 : Assert(EOXactTupleDescArray != NULL);
3239 27328 : for (i = 0; i < NextEOXactTupleDescNum; i++)
3240 17194 : FreeTupleDesc(EOXactTupleDescArray[i]);
3241 10134 : pfree(EOXactTupleDescArray);
3242 10134 : EOXactTupleDescArray = NULL;
3243 : }
3244 :
3245 : /* Now we're out of the transaction and can clear the lists */
3246 746658 : eoxact_list_len = 0;
3247 746658 : eoxact_list_overflowed = false;
3248 746658 : NextEOXactTupleDescNum = 0;
3249 746658 : EOXactTupleDescArrayLen = 0;
3250 746658 : }
3251 :
3252 : /*
3253 : * AtEOXact_cleanup
3254 : *
3255 : * Clean up a single rel at main-transaction commit or abort
3256 : *
3257 : * NB: this processing must be idempotent, because EOXactListAdd() doesn't
3258 : * bother to prevent duplicate entries in eoxact_list[].
3259 : */
3260 : static void
3261 147688 : AtEOXact_cleanup(Relation relation, bool isCommit)
3262 : {
3263 147688 : bool clear_relcache = false;
3264 :
3265 : /*
3266 : * The relcache entry's ref count should be back to its normal
3267 : * not-in-a-transaction state: 0 unless it's nailed in cache.
3268 : *
3269 : * In bootstrap mode, this is NOT true, so don't check it --- the
3270 : * bootstrap code expects relations to stay open across start/commit
3271 : * transaction calls. (That seems bogus, but it's not worth fixing.)
3272 : *
3273 : * Note: ideally this check would be applied to every relcache entry, not
3274 : * just those that have eoxact work to do. But it's not worth forcing a
3275 : * scan of the whole relcache just for this. (Moreover, doing so would
3276 : * mean that assert-enabled testing never tests the hash_search code path
3277 : * above, which seems a bad idea.)
3278 : */
3279 : #ifdef USE_ASSERT_CHECKING
3280 : if (!IsBootstrapProcessingMode())
3281 : {
3282 : int expected_refcnt;
3283 :
3284 : expected_refcnt = relation->rd_isnailed ? 1 : 0;
3285 : Assert(relation->rd_refcnt == expected_refcnt);
3286 : }
3287 : #endif
3288 :
3289 : /*
3290 : * Is the relation live after this transaction ends?
3291 : *
3292 : * During commit, clear the relcache entry if it is preserved after
3293 : * relation drop, in order not to orphan the entry. During rollback,
3294 : * clear the relcache entry if the relation is created in the current
3295 : * transaction since it isn't interesting any longer once we are out of
3296 : * the transaction.
3297 : */
3298 147688 : clear_relcache =
3299 : (isCommit ?
3300 147688 : relation->rd_droppedSubid != InvalidSubTransactionId :
3301 4348 : relation->rd_createSubid != InvalidSubTransactionId);
3302 :
3303 : /*
3304 : * Since we are now out of the transaction, reset the subids to zero. That
3305 : * also lets RelationClearRelation() drop the relcache entry.
3306 : */
3307 147688 : relation->rd_createSubid = InvalidSubTransactionId;
3308 147688 : relation->rd_newRelfilelocatorSubid = InvalidSubTransactionId;
3309 147688 : relation->rd_firstRelfilelocatorSubid = InvalidSubTransactionId;
3310 147688 : relation->rd_droppedSubid = InvalidSubTransactionId;
3311 :
3312 147688 : if (clear_relcache)
3313 : {
3314 5204 : if (RelationHasReferenceCountZero(relation))
3315 : {
3316 5204 : RelationClearRelation(relation);
3317 5204 : return;
3318 : }
3319 : else
3320 : {
3321 : /*
3322 : * Hmm, somewhere there's a (leaked?) reference to the relation.
3323 : * We daren't remove the entry for fear of dereferencing a
3324 : * dangling pointer later. Bleat, and mark it as not belonging to
3325 : * the current transaction. Hopefully it'll get cleaned up
3326 : * eventually. This must be just a WARNING to avoid
3327 : * error-during-error-recovery loops.
3328 : */
3329 0 : elog(WARNING, "cannot remove relcache entry for \"%s\" because it has nonzero refcount",
3330 : RelationGetRelationName(relation));
3331 : }
3332 : }
3333 : }
3334 :
3335 : /*
3336 : * AtEOSubXact_RelationCache
3337 : *
3338 : * Clean up the relcache at sub-transaction commit or abort.
3339 : *
3340 : * Note: this must be called *before* processing invalidation messages.
3341 : */
3342 : void
3343 20016 : AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid,
3344 : SubTransactionId parentSubid)
3345 : {
3346 : HASH_SEQ_STATUS status;
3347 : RelIdCacheEnt *idhentry;
3348 : int i;
3349 :
3350 : /*
3351 : * Forget in_progress_list. This is relevant when we're aborting due to
3352 : * an error during RelationBuildDesc(). We don't commit subtransactions
3353 : * during RelationBuildDesc().
3354 : */
3355 : Assert(in_progress_list_len == 0 || !isCommit);
3356 20016 : in_progress_list_len = 0;
3357 :
3358 : /*
3359 : * Unless the eoxact_list[] overflowed, we only need to examine the rels
3360 : * listed in it. Otherwise fall back on a hash_seq_search scan. Same
3361 : * logic as in AtEOXact_RelationCache.
3362 : */
3363 20016 : if (eoxact_list_overflowed)
3364 : {
3365 0 : hash_seq_init(&status, RelationIdCache);
3366 0 : while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3367 : {
3368 0 : AtEOSubXact_cleanup(idhentry->reldesc, isCommit,
3369 : mySubid, parentSubid);
3370 : }
3371 : }
3372 : else
3373 : {
3374 29530 : for (i = 0; i < eoxact_list_len; i++)
3375 : {
3376 9514 : idhentry = (RelIdCacheEnt *) hash_search(RelationIdCache,
3377 9514 : &eoxact_list[i],
3378 : HASH_FIND,
3379 : NULL);
3380 9514 : if (idhentry != NULL)
3381 8570 : AtEOSubXact_cleanup(idhentry->reldesc, isCommit,
3382 : mySubid, parentSubid);
3383 : }
3384 : }
3385 :
3386 : /* Don't reset the list; we still need more cleanup later */
3387 20016 : }
3388 :
3389 : /*
3390 : * AtEOSubXact_cleanup
3391 : *
3392 : * Clean up a single rel at subtransaction commit or abort
3393 : *
3394 : * NB: this processing must be idempotent, because EOXactListAdd() doesn't
3395 : * bother to prevent duplicate entries in eoxact_list[].
3396 : */
3397 : static void
3398 8570 : AtEOSubXact_cleanup(Relation relation, bool isCommit,
3399 : SubTransactionId mySubid, SubTransactionId parentSubid)
3400 : {
3401 : /*
3402 : * Is it a relation created in the current subtransaction?
3403 : *
3404 : * During subcommit, mark it as belonging to the parent, instead, as long
3405 : * as it has not been dropped. Otherwise simply delete the relcache entry.
3406 : * --- it isn't interesting any longer.
3407 : */
3408 8570 : if (relation->rd_createSubid == mySubid)
3409 : {
3410 : /*
3411 : * Valid rd_droppedSubid means the corresponding relation is dropped
3412 : * but the relcache entry is preserved for at-commit pending sync. We
3413 : * need to drop it explicitly here not to make the entry orphan.
3414 : */
3415 : Assert(relation->rd_droppedSubid == mySubid ||
3416 : relation->rd_droppedSubid == InvalidSubTransactionId);
3417 198 : if (isCommit && relation->rd_droppedSubid == InvalidSubTransactionId)
3418 74 : relation->rd_createSubid = parentSubid;
3419 124 : else if (RelationHasReferenceCountZero(relation))
3420 : {
3421 : /* allow the entry to be removed */
3422 124 : relation->rd_createSubid = InvalidSubTransactionId;
3423 124 : relation->rd_newRelfilelocatorSubid = InvalidSubTransactionId;
3424 124 : relation->rd_firstRelfilelocatorSubid = InvalidSubTransactionId;
3425 124 : relation->rd_droppedSubid = InvalidSubTransactionId;
3426 124 : RelationClearRelation(relation);
3427 124 : return;
3428 : }
3429 : else
3430 : {
3431 : /*
3432 : * Hmm, somewhere there's a (leaked?) reference to the relation.
3433 : * We daren't remove the entry for fear of dereferencing a
3434 : * dangling pointer later. Bleat, and transfer it to the parent
3435 : * subtransaction so we can try again later. This must be just a
3436 : * WARNING to avoid error-during-error-recovery loops.
3437 : */
3438 0 : relation->rd_createSubid = parentSubid;
3439 0 : elog(WARNING, "cannot remove relcache entry for \"%s\" because it has nonzero refcount",
3440 : RelationGetRelationName(relation));
3441 : }
3442 : }
3443 :
3444 : /*
3445 : * Likewise, update or drop any new-relfilenumber-in-subtransaction record
3446 : * or drop record.
3447 : */
3448 8446 : if (relation->rd_newRelfilelocatorSubid == mySubid)
3449 : {
3450 140 : if (isCommit)
3451 72 : relation->rd_newRelfilelocatorSubid = parentSubid;
3452 : else
3453 68 : relation->rd_newRelfilelocatorSubid = InvalidSubTransactionId;
3454 : }
3455 :
3456 8446 : if (relation->rd_firstRelfilelocatorSubid == mySubid)
3457 : {
3458 96 : if (isCommit)
3459 32 : relation->rd_firstRelfilelocatorSubid = parentSubid;
3460 : else
3461 64 : relation->rd_firstRelfilelocatorSubid = InvalidSubTransactionId;
3462 : }
3463 :
3464 8446 : if (relation->rd_droppedSubid == mySubid)
3465 : {
3466 20 : if (isCommit)
3467 2 : relation->rd_droppedSubid = parentSubid;
3468 : else
3469 18 : relation->rd_droppedSubid = InvalidSubTransactionId;
3470 : }
3471 : }
3472 :
3473 :
3474 : /*
3475 : * RelationBuildLocalRelation
3476 : * Build a relcache entry for an about-to-be-created relation,
3477 : * and enter it into the relcache.
3478 : */
3479 : Relation
3480 126158 : RelationBuildLocalRelation(const char *relname,
3481 : Oid relnamespace,
3482 : TupleDesc tupDesc,
3483 : Oid relid,
3484 : Oid accessmtd,
3485 : RelFileNumber relfilenumber,
3486 : Oid reltablespace,
3487 : bool shared_relation,
3488 : bool mapped_relation,
3489 : char relpersistence,
3490 : char relkind)
3491 : {
3492 : Relation rel;
3493 : MemoryContext oldcxt;
3494 126158 : int natts = tupDesc->natts;
3495 : int i;
3496 : bool has_not_null;
3497 : bool nailit;
3498 :
3499 : Assert(natts >= 0);
3500 :
3501 : /*
3502 : * check for creation of a rel that must be nailed in cache.
3503 : *
3504 : * XXX this list had better match the relations specially handled in
3505 : * RelationCacheInitializePhase2/3.
3506 : */
3507 126158 : switch (relid)
3508 : {
3509 630 : case DatabaseRelationId:
3510 : case AuthIdRelationId:
3511 : case AuthMemRelationId:
3512 : case RelationRelationId:
3513 : case AttributeRelationId:
3514 : case ProcedureRelationId:
3515 : case TypeRelationId:
3516 630 : nailit = true;
3517 630 : break;
3518 125528 : default:
3519 125528 : nailit = false;
3520 125528 : break;
3521 : }
3522 :
3523 : /*
3524 : * check that hardwired list of shared rels matches what's in the
3525 : * bootstrap .bki file. If you get a failure here during initdb, you
3526 : * probably need to fix IsSharedRelation() to match whatever you've done
3527 : * to the set of shared relations.
3528 : */
3529 126158 : if (shared_relation != IsSharedRelation(relid))
3530 0 : elog(ERROR, "shared_relation flag for \"%s\" does not match IsSharedRelation(%u)",
3531 : relname, relid);
3532 :
3533 : /* Shared relations had better be mapped, too */
3534 : Assert(mapped_relation || !shared_relation);
3535 :
3536 : /*
3537 : * switch to the cache context to create the relcache entry.
3538 : */
3539 126158 : if (!CacheMemoryContext)
3540 0 : CreateCacheMemoryContext();
3541 :
3542 126158 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
3543 :
3544 : /*
3545 : * allocate a new relation descriptor and fill in basic state fields.
3546 : */
3547 126158 : rel = (Relation) palloc0(sizeof(RelationData));
3548 :
3549 : /* make sure relation is marked as having no open file yet */
3550 126158 : rel->rd_smgr = NULL;
3551 :
3552 : /* mark it nailed if appropriate */
3553 126158 : rel->rd_isnailed = nailit;
3554 :
3555 126158 : rel->rd_refcnt = nailit ? 1 : 0;
3556 :
3557 : /* it's being created in this transaction */
3558 126158 : rel->rd_createSubid = GetCurrentSubTransactionId();
3559 126158 : rel->rd_newRelfilelocatorSubid = InvalidSubTransactionId;
3560 126158 : rel->rd_firstRelfilelocatorSubid = InvalidSubTransactionId;
3561 126158 : rel->rd_droppedSubid = InvalidSubTransactionId;
3562 :
3563 : /*
3564 : * create a new tuple descriptor from the one passed in. We do this
3565 : * partly to copy it into the cache context, and partly because the new
3566 : * relation can't have any defaults or constraints yet; they have to be
3567 : * added in later steps, because they require additions to multiple system
3568 : * catalogs. We can copy attnotnull constraints here, however.
3569 : */
3570 126158 : rel->rd_att = CreateTupleDescCopy(tupDesc);
3571 126158 : rel->rd_att->tdrefcount = 1; /* mark as refcounted */
3572 126158 : has_not_null = false;
3573 539216 : for (i = 0; i < natts; i++)
3574 : {
3575 413058 : Form_pg_attribute satt = TupleDescAttr(tupDesc, i);
3576 413058 : Form_pg_attribute datt = TupleDescAttr(rel->rd_att, i);
3577 :
3578 413058 : datt->attidentity = satt->attidentity;
3579 413058 : datt->attgenerated = satt->attgenerated;
3580 413058 : datt->attnotnull = satt->attnotnull;
3581 413058 : has_not_null |= satt->attnotnull;
3582 : }
3583 :
3584 126158 : if (has_not_null)
3585 : {
3586 18904 : TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
3587 :
3588 18904 : constr->has_not_null = true;
3589 18904 : rel->rd_att->constr = constr;
3590 : }
3591 :
3592 : /*
3593 : * initialize relation tuple form (caller may add/override data later)
3594 : */
3595 126158 : rel->rd_rel = (Form_pg_class) palloc0(CLASS_TUPLE_SIZE);
3596 :
3597 126158 : namestrcpy(&rel->rd_rel->relname, relname);
3598 126158 : rel->rd_rel->relnamespace = relnamespace;
3599 :
3600 126158 : rel->rd_rel->relkind = relkind;
3601 126158 : rel->rd_rel->relnatts = natts;
3602 126158 : rel->rd_rel->reltype = InvalidOid;
3603 : /* needed when bootstrapping: */
3604 126158 : rel->rd_rel->relowner = BOOTSTRAP_SUPERUSERID;
3605 :
3606 : /* set up persistence and relcache fields dependent on it */
3607 126158 : rel->rd_rel->relpersistence = relpersistence;
3608 126158 : switch (relpersistence)
3609 : {
3610 120188 : case RELPERSISTENCE_UNLOGGED:
3611 : case RELPERSISTENCE_PERMANENT:
3612 120188 : rel->rd_backend = INVALID_PROC_NUMBER;
3613 120188 : rel->rd_islocaltemp = false;
3614 120188 : break;
3615 5970 : case RELPERSISTENCE_TEMP:
3616 : Assert(isTempOrTempToastNamespace(relnamespace));
3617 5970 : rel->rd_backend = ProcNumberForTempRelations();
3618 5970 : rel->rd_islocaltemp = true;
3619 5970 : break;
3620 0 : default:
3621 0 : elog(ERROR, "invalid relpersistence: %c", relpersistence);
3622 : break;
3623 : }
3624 :
3625 : /* if it's a materialized view, it's not populated initially */
3626 126158 : if (relkind == RELKIND_MATVIEW)
3627 448 : rel->rd_rel->relispopulated = false;
3628 : else
3629 125710 : rel->rd_rel->relispopulated = true;
3630 :
3631 : /* set replica identity -- system catalogs and non-tables don't have one */
3632 126158 : if (!IsCatalogNamespace(relnamespace) &&
3633 69464 : (relkind == RELKIND_RELATION ||
3634 69016 : relkind == RELKIND_MATVIEW ||
3635 : relkind == RELKIND_PARTITIONED_TABLE))
3636 38054 : rel->rd_rel->relreplident = REPLICA_IDENTITY_DEFAULT;
3637 : else
3638 88104 : rel->rd_rel->relreplident = REPLICA_IDENTITY_NOTHING;
3639 :
3640 : /*
3641 : * Insert relation physical and logical identifiers (OIDs) into the right
3642 : * places. For a mapped relation, we set relfilenumber to zero and rely
3643 : * on RelationInitPhysicalAddr to consult the map.
3644 : */
3645 126158 : rel->rd_rel->relisshared = shared_relation;
3646 :
3647 126158 : RelationGetRelid(rel) = relid;
3648 :
3649 539216 : for (i = 0; i < natts; i++)
3650 413058 : TupleDescAttr(rel->rd_att, i)->attrelid = relid;
3651 :
3652 126158 : rel->rd_rel->reltablespace = reltablespace;
3653 :
3654 126158 : if (mapped_relation)
3655 : {
3656 6018 : rel->rd_rel->relfilenode = InvalidRelFileNumber;
3657 : /* Add it to the active mapping information */
3658 6018 : RelationMapUpdateMap(relid, relfilenumber, shared_relation, true);
3659 : }
3660 : else
3661 120140 : rel->rd_rel->relfilenode = relfilenumber;
3662 :
3663 126158 : RelationInitLockInfo(rel); /* see lmgr.c */
3664 :
3665 126158 : RelationInitPhysicalAddr(rel);
3666 :
3667 126158 : rel->rd_rel->relam = accessmtd;
3668 :
3669 : /*
3670 : * RelationInitTableAccessMethod will do syscache lookups, so we mustn't
3671 : * run it in CacheMemoryContext. Fortunately, the remaining steps don't
3672 : * require a long-lived current context.
3673 : */
3674 126158 : MemoryContextSwitchTo(oldcxt);
3675 :
3676 126158 : if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_SEQUENCE)
3677 57672 : RelationInitTableAccessMethod(rel);
3678 :
3679 : /*
3680 : * Leave index access method uninitialized, because the pg_index row has
3681 : * not been inserted at this stage of index creation yet. The cache
3682 : * invalidation after pg_index row has been inserted will initialize it.
3683 : */
3684 :
3685 : /*
3686 : * Okay to insert into the relcache hash table.
3687 : *
3688 : * Ordinarily, there should certainly not be an existing hash entry for
3689 : * the same OID; but during bootstrap, when we create a "real" relcache
3690 : * entry for one of the bootstrap relations, we'll be overwriting the
3691 : * phony one created with formrdesc. So allow that to happen for nailed
3692 : * rels.
3693 : */
3694 126158 : RelationCacheInsert(rel, nailit);
3695 :
3696 : /*
3697 : * Flag relation as needing eoxact cleanup (to clear rd_createSubid). We
3698 : * can't do this before storing relid in it.
3699 : */
3700 126158 : EOXactListAdd(rel);
3701 :
3702 : /* It's fully valid */
3703 126158 : rel->rd_isvalid = true;
3704 :
3705 : /*
3706 : * Caller expects us to pin the returned entry.
3707 : */
3708 126158 : RelationIncrementReferenceCount(rel);
3709 :
3710 126158 : return rel;
3711 : }
3712 :
3713 :
3714 : /*
3715 : * RelationSetNewRelfilenumber
3716 : *
3717 : * Assign a new relfilenumber (physical file name), and possibly a new
3718 : * persistence setting, to the relation.
3719 : *
3720 : * This allows a full rewrite of the relation to be done with transactional
3721 : * safety (since the filenumber assignment can be rolled back). Note however
3722 : * that there is no simple way to access the relation's old data for the
3723 : * remainder of the current transaction. This limits the usefulness to cases
3724 : * such as TRUNCATE or rebuilding an index from scratch.
3725 : *
3726 : * Caller must already hold exclusive lock on the relation.
3727 : */
3728 : void
3729 12938 : RelationSetNewRelfilenumber(Relation relation, char persistence)
3730 : {
3731 : RelFileNumber newrelfilenumber;
3732 : Relation pg_class;
3733 : ItemPointerData otid;
3734 : HeapTuple tuple;
3735 : Form_pg_class classform;
3736 12938 : MultiXactId minmulti = InvalidMultiXactId;
3737 12938 : TransactionId freezeXid = InvalidTransactionId;
3738 : RelFileLocator newrlocator;
3739 :
3740 12938 : if (!IsBinaryUpgrade)
3741 : {
3742 : /* Allocate a new relfilenumber */
3743 12898 : newrelfilenumber = GetNewRelFileNumber(relation->rd_rel->reltablespace,
3744 : NULL, persistence);
3745 : }
3746 40 : else if (relation->rd_rel->relkind == RELKIND_INDEX)
3747 : {
3748 20 : if (!OidIsValid(binary_upgrade_next_index_pg_class_relfilenumber))
3749 0 : ereport(ERROR,
3750 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3751 : errmsg("index relfilenumber value not set when in binary upgrade mode")));
3752 :
3753 20 : newrelfilenumber = binary_upgrade_next_index_pg_class_relfilenumber;
3754 20 : binary_upgrade_next_index_pg_class_relfilenumber = InvalidOid;
3755 : }
3756 20 : else if (relation->rd_rel->relkind == RELKIND_RELATION)
3757 : {
3758 20 : if (!OidIsValid(binary_upgrade_next_heap_pg_class_relfilenumber))
3759 0 : ereport(ERROR,
3760 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3761 : errmsg("heap relfilenumber value not set when in binary upgrade mode")));
3762 :
3763 20 : newrelfilenumber = binary_upgrade_next_heap_pg_class_relfilenumber;
3764 20 : binary_upgrade_next_heap_pg_class_relfilenumber = InvalidOid;
3765 : }
3766 : else
3767 0 : ereport(ERROR,
3768 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3769 : errmsg("unexpected request for new relfilenumber in binary upgrade mode")));
3770 :
3771 : /*
3772 : * Get a writable copy of the pg_class tuple for the given relation.
3773 : */
3774 12938 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
3775 :
3776 12938 : tuple = SearchSysCacheLockedCopy1(RELOID,
3777 : ObjectIdGetDatum(RelationGetRelid(relation)));
3778 12938 : if (!HeapTupleIsValid(tuple))
3779 0 : elog(ERROR, "could not find tuple for relation %u",
3780 : RelationGetRelid(relation));
3781 12938 : otid = tuple->t_self;
3782 12938 : classform = (Form_pg_class) GETSTRUCT(tuple);
3783 :
3784 : /*
3785 : * Schedule unlinking of the old storage at transaction commit, except
3786 : * when performing a binary upgrade, when we must do it immediately.
3787 : */
3788 12938 : if (IsBinaryUpgrade)
3789 : {
3790 : SMgrRelation srel;
3791 :
3792 : /*
3793 : * During a binary upgrade, we use this code path to ensure that
3794 : * pg_largeobject and its index have the same relfilenumbers as in the
3795 : * old cluster. This is necessary because pg_upgrade treats
3796 : * pg_largeobject like a user table, not a system table. It is however
3797 : * possible that a table or index may need to end up with the same
3798 : * relfilenumber in the new cluster as what it had in the old cluster.
3799 : * Hence, we can't wait until commit time to remove the old storage.
3800 : *
3801 : * In general, this function needs to have transactional semantics,
3802 : * and removing the old storage before commit time surely isn't.
3803 : * However, it doesn't really matter, because if a binary upgrade
3804 : * fails at this stage, the new cluster will need to be recreated
3805 : * anyway.
3806 : */
3807 40 : srel = smgropen(relation->rd_locator, relation->rd_backend);
3808 40 : smgrdounlinkall(&srel, 1, false);
3809 40 : smgrclose(srel);
3810 : }
3811 : else
3812 : {
3813 : /* Not a binary upgrade, so just schedule it to happen later. */
3814 12898 : RelationDropStorage(relation);
3815 : }
3816 :
3817 : /*
3818 : * Create storage for the main fork of the new relfilenumber. If it's a
3819 : * table-like object, call into the table AM to do so, which'll also
3820 : * create the table's init fork if needed.
3821 : *
3822 : * NOTE: If relevant for the AM, any conflict in relfilenumber value will
3823 : * be caught here, if GetNewRelFileNumber messes up for any reason.
3824 : */
3825 12938 : newrlocator = relation->rd_locator;
3826 12938 : newrlocator.relNumber = newrelfilenumber;
3827 :
3828 12938 : if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind))
3829 : {
3830 4648 : table_relation_set_new_filelocator(relation, &newrlocator,
3831 : persistence,
3832 : &freezeXid, &minmulti);
3833 : }
3834 8290 : else if (RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
3835 8290 : {
3836 : /* handle these directly, at least for now */
3837 : SMgrRelation srel;
3838 :
3839 8290 : srel = RelationCreateStorage(newrlocator, persistence, true);
3840 8290 : smgrclose(srel);
3841 : }
3842 : else
3843 : {
3844 : /* we shouldn't be called for anything else */
3845 0 : elog(ERROR, "relation \"%s\" does not have storage",
3846 : RelationGetRelationName(relation));
3847 : }
3848 :
3849 : /*
3850 : * If we're dealing with a mapped index, pg_class.relfilenode doesn't
3851 : * change; instead we have to send the update to the relation mapper.
3852 : *
3853 : * For mapped indexes, we don't actually change the pg_class entry at all;
3854 : * this is essential when reindexing pg_class itself. That leaves us with
3855 : * possibly-inaccurate values of relpages etc, but those will be fixed up
3856 : * later.
3857 : */
3858 12938 : if (RelationIsMapped(relation))
3859 : {
3860 : /* This case is only supported for indexes */
3861 : Assert(relation->rd_rel->relkind == RELKIND_INDEX);
3862 :
3863 : /* Since we're not updating pg_class, these had better not change */
3864 : Assert(classform->relfrozenxid == freezeXid);
3865 : Assert(classform->relminmxid == minmulti);
3866 : Assert(classform->relpersistence == persistence);
3867 :
3868 : /*
3869 : * In some code paths it's possible that the tuple update we'd
3870 : * otherwise do here is the only thing that would assign an XID for
3871 : * the current transaction. However, we must have an XID to delete
3872 : * files, so make sure one is assigned.
3873 : */
3874 986 : (void) GetCurrentTransactionId();
3875 :
3876 : /* Do the deed */
3877 986 : RelationMapUpdateMap(RelationGetRelid(relation),
3878 : newrelfilenumber,
3879 986 : relation->rd_rel->relisshared,
3880 : false);
3881 :
3882 : /* Since we're not updating pg_class, must trigger inval manually */
3883 986 : CacheInvalidateRelcache(relation);
3884 : }
3885 : else
3886 : {
3887 : /* Normal case, update the pg_class entry */
3888 11952 : classform->relfilenode = newrelfilenumber;
3889 :
3890 : /* relpages etc. never change for sequences */
3891 11952 : if (relation->rd_rel->relkind != RELKIND_SEQUENCE)
3892 : {
3893 11670 : classform->relpages = 0; /* it's empty until further notice */
3894 11670 : classform->reltuples = -1;
3895 11670 : classform->relallvisible = 0;
3896 : }
3897 11952 : classform->relfrozenxid = freezeXid;
3898 11952 : classform->relminmxid = minmulti;
3899 11952 : classform->relpersistence = persistence;
3900 :
3901 11952 : CatalogTupleUpdate(pg_class, &otid, tuple);
3902 : }
3903 :
3904 12938 : UnlockTuple(pg_class, &otid, InplaceUpdateTupleLock);
3905 12938 : heap_freetuple(tuple);
3906 :
3907 12938 : table_close(pg_class, RowExclusiveLock);
3908 :
3909 : /*
3910 : * Make the pg_class row change or relation map change visible. This will
3911 : * cause the relcache entry to get updated, too.
3912 : */
3913 12938 : CommandCounterIncrement();
3914 :
3915 12938 : RelationAssumeNewRelfilelocator(relation);
3916 12938 : }
3917 :
3918 : /*
3919 : * RelationAssumeNewRelfilelocator
3920 : *
3921 : * Code that modifies pg_class.reltablespace or pg_class.relfilenode must call
3922 : * this. The call shall precede any code that might insert WAL records whose
3923 : * replay would modify bytes in the new RelFileLocator, and the call shall follow
3924 : * any WAL modifying bytes in the prior RelFileLocator. See struct RelationData.
3925 : * Ideally, call this as near as possible to the CommandCounterIncrement()
3926 : * that makes the pg_class change visible (before it or after it); that
3927 : * minimizes the chance of future development adding a forbidden WAL insertion
3928 : * between RelationAssumeNewRelfilelocator() and CommandCounterIncrement().
3929 : */
3930 : void
3931 15402 : RelationAssumeNewRelfilelocator(Relation relation)
3932 : {
3933 15402 : relation->rd_newRelfilelocatorSubid = GetCurrentSubTransactionId();
3934 15402 : if (relation->rd_firstRelfilelocatorSubid == InvalidSubTransactionId)
3935 15308 : relation->rd_firstRelfilelocatorSubid = relation->rd_newRelfilelocatorSubid;
3936 :
3937 : /* Flag relation as needing eoxact cleanup (to clear these fields) */
3938 15402 : EOXactListAdd(relation);
3939 15402 : }
3940 :
3941 :
3942 : /*
3943 : * RelationCacheInitialize
3944 : *
3945 : * This initializes the relation descriptor cache. At the time
3946 : * that this is invoked, we can't do database access yet (mainly
3947 : * because the transaction subsystem is not up); all we are doing
3948 : * is making an empty cache hashtable. This must be done before
3949 : * starting the initialization transaction, because otherwise
3950 : * AtEOXact_RelationCache would crash if that transaction aborts
3951 : * before we can get the relcache set up.
3952 : */
3953 :
3954 : #define INITRELCACHESIZE 400
3955 :
3956 : void
3957 28530 : RelationCacheInitialize(void)
3958 : {
3959 : HASHCTL ctl;
3960 : int allocsize;
3961 :
3962 : /*
3963 : * make sure cache memory context exists
3964 : */
3965 28530 : if (!CacheMemoryContext)
3966 28530 : CreateCacheMemoryContext();
3967 :
3968 : /*
3969 : * create hashtable that indexes the relcache
3970 : */
3971 28530 : ctl.keysize = sizeof(Oid);
3972 28530 : ctl.entrysize = sizeof(RelIdCacheEnt);
3973 28530 : RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
3974 : &ctl, HASH_ELEM | HASH_BLOBS);
3975 :
3976 : /*
3977 : * reserve enough in_progress_list slots for many cases
3978 : */
3979 28530 : allocsize = 4;
3980 28530 : in_progress_list =
3981 28530 : MemoryContextAlloc(CacheMemoryContext,
3982 : allocsize * sizeof(*in_progress_list));
3983 28530 : in_progress_list_maxlen = allocsize;
3984 :
3985 : /*
3986 : * relation mapper needs to be initialized too
3987 : */
3988 28530 : RelationMapInitialize();
3989 28530 : }
3990 :
3991 : /*
3992 : * RelationCacheInitializePhase2
3993 : *
3994 : * This is called to prepare for access to shared catalogs during startup.
3995 : * We must at least set up nailed reldescs for pg_database, pg_authid,
3996 : * pg_auth_members, and pg_shseclabel. Ideally we'd like to have reldescs
3997 : * for their indexes, too. We attempt to load this information from the
3998 : * shared relcache init file. If that's missing or broken, just make
3999 : * phony entries for the catalogs themselves.
4000 : * RelationCacheInitializePhase3 will clean up as needed.
4001 : */
4002 : void
4003 28530 : RelationCacheInitializePhase2(void)
4004 : {
4005 : MemoryContext oldcxt;
4006 :
4007 : /*
4008 : * relation mapper needs initialized too
4009 : */
4010 28530 : RelationMapInitializePhase2();
4011 :
4012 : /*
4013 : * In bootstrap mode, the shared catalogs aren't there yet anyway, so do
4014 : * nothing.
4015 : */
4016 28530 : if (IsBootstrapProcessingMode())
4017 90 : return;
4018 :
4019 : /*
4020 : * switch to cache memory context
4021 : */
4022 28440 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
4023 :
4024 : /*
4025 : * Try to load the shared relcache cache file. If unsuccessful, bootstrap
4026 : * the cache with pre-made descriptors for the critical shared catalogs.
4027 : */
4028 28440 : if (!load_relcache_init_file(true))
4029 : {
4030 3750 : formrdesc("pg_database", DatabaseRelation_Rowtype_Id, true,
4031 : Natts_pg_database, Desc_pg_database);
4032 3750 : formrdesc("pg_authid", AuthIdRelation_Rowtype_Id, true,
4033 : Natts_pg_authid, Desc_pg_authid);
4034 3750 : formrdesc("pg_auth_members", AuthMemRelation_Rowtype_Id, true,
4035 : Natts_pg_auth_members, Desc_pg_auth_members);
4036 3750 : formrdesc("pg_shseclabel", SharedSecLabelRelation_Rowtype_Id, true,
4037 : Natts_pg_shseclabel, Desc_pg_shseclabel);
4038 3750 : formrdesc("pg_subscription", SubscriptionRelation_Rowtype_Id, true,
4039 : Natts_pg_subscription, Desc_pg_subscription);
4040 :
4041 : #define NUM_CRITICAL_SHARED_RELS 5 /* fix if you change list above */
4042 : }
4043 :
4044 28440 : MemoryContextSwitchTo(oldcxt);
4045 : }
4046 :
4047 : /*
4048 : * RelationCacheInitializePhase3
4049 : *
4050 : * This is called as soon as the catcache and transaction system
4051 : * are functional and we have determined MyDatabaseId. At this point
4052 : * we can actually read data from the database's system catalogs.
4053 : * We first try to read pre-computed relcache entries from the local
4054 : * relcache init file. If that's missing or broken, make phony entries
4055 : * for the minimum set of nailed-in-cache relations. Then (unless
4056 : * bootstrapping) make sure we have entries for the critical system
4057 : * indexes. Once we've done all this, we have enough infrastructure to
4058 : * open any system catalog or use any catcache. The last step is to
4059 : * rewrite the cache files if needed.
4060 : */
4061 : void
4062 26032 : RelationCacheInitializePhase3(void)
4063 : {
4064 : HASH_SEQ_STATUS status;
4065 : RelIdCacheEnt *idhentry;
4066 : MemoryContext oldcxt;
4067 26032 : bool needNewCacheFile = !criticalSharedRelcachesBuilt;
4068 :
4069 : /*
4070 : * relation mapper needs initialized too
4071 : */
4072 26032 : RelationMapInitializePhase3();
4073 :
4074 : /*
4075 : * switch to cache memory context
4076 : */
4077 26032 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
4078 :
4079 : /*
4080 : * Try to load the local relcache cache file. If unsuccessful, bootstrap
4081 : * the cache with pre-made descriptors for the critical "nailed-in" system
4082 : * catalogs.
4083 : */
4084 26032 : if (IsBootstrapProcessingMode() ||
4085 25942 : !load_relcache_init_file(false))
4086 : {
4087 2630 : needNewCacheFile = true;
4088 :
4089 2630 : formrdesc("pg_class", RelationRelation_Rowtype_Id, false,
4090 : Natts_pg_class, Desc_pg_class);
4091 2630 : formrdesc("pg_attribute", AttributeRelation_Rowtype_Id, false,
4092 : Natts_pg_attribute, Desc_pg_attribute);
4093 2630 : formrdesc("pg_proc", ProcedureRelation_Rowtype_Id, false,
4094 : Natts_pg_proc, Desc_pg_proc);
4095 2630 : formrdesc("pg_type", TypeRelation_Rowtype_Id, false,
4096 : Natts_pg_type, Desc_pg_type);
4097 :
4098 : #define NUM_CRITICAL_LOCAL_RELS 4 /* fix if you change list above */
4099 : }
4100 :
4101 26032 : MemoryContextSwitchTo(oldcxt);
4102 :
4103 : /* In bootstrap mode, the faked-up formrdesc info is all we'll have */
4104 26032 : if (IsBootstrapProcessingMode())
4105 90 : return;
4106 :
4107 : /*
4108 : * If we didn't get the critical system indexes loaded into relcache, do
4109 : * so now. These are critical because the catcache and/or opclass cache
4110 : * depend on them for fetches done during relcache load. Thus, we have an
4111 : * infinite-recursion problem. We can break the recursion by doing
4112 : * heapscans instead of indexscans at certain key spots. To avoid hobbling
4113 : * performance, we only want to do that until we have the critical indexes
4114 : * loaded into relcache. Thus, the flag criticalRelcachesBuilt is used to
4115 : * decide whether to do heapscan or indexscan at the key spots, and we set
4116 : * it true after we've loaded the critical indexes.
4117 : *
4118 : * The critical indexes are marked as "nailed in cache", partly to make it
4119 : * easy for load_relcache_init_file to count them, but mainly because we
4120 : * cannot flush and rebuild them once we've set criticalRelcachesBuilt to
4121 : * true. (NOTE: perhaps it would be possible to reload them by
4122 : * temporarily setting criticalRelcachesBuilt to false again. For now,
4123 : * though, we just nail 'em in.)
4124 : *
4125 : * RewriteRelRulenameIndexId and TriggerRelidNameIndexId are not critical
4126 : * in the same way as the others, because the critical catalogs don't
4127 : * (currently) have any rules or triggers, and so these indexes can be
4128 : * rebuilt without inducing recursion. However they are used during
4129 : * relcache load when a rel does have rules or triggers, so we choose to
4130 : * nail them for performance reasons.
4131 : */
4132 25942 : if (!criticalRelcachesBuilt)
4133 : {
4134 2540 : load_critical_index(ClassOidIndexId,
4135 : RelationRelationId);
4136 2540 : load_critical_index(AttributeRelidNumIndexId,
4137 : AttributeRelationId);
4138 2538 : load_critical_index(IndexRelidIndexId,
4139 : IndexRelationId);
4140 2538 : load_critical_index(OpclassOidIndexId,
4141 : OperatorClassRelationId);
4142 2538 : load_critical_index(AccessMethodProcedureIndexId,
4143 : AccessMethodProcedureRelationId);
4144 2538 : load_critical_index(RewriteRelRulenameIndexId,
4145 : RewriteRelationId);
4146 2536 : load_critical_index(TriggerRelidNameIndexId,
4147 : TriggerRelationId);
4148 :
4149 : #define NUM_CRITICAL_LOCAL_INDEXES 7 /* fix if you change list above */
4150 :
4151 2536 : criticalRelcachesBuilt = true;
4152 : }
4153 :
4154 : /*
4155 : * Process critical shared indexes too.
4156 : *
4157 : * DatabaseNameIndexId isn't critical for relcache loading, but rather for
4158 : * initial lookup of MyDatabaseId, without which we'll never find any
4159 : * non-shared catalogs at all. Autovacuum calls InitPostgres with a
4160 : * database OID, so it instead depends on DatabaseOidIndexId. We also
4161 : * need to nail up some indexes on pg_authid and pg_auth_members for use
4162 : * during client authentication. SharedSecLabelObjectIndexId isn't
4163 : * critical for the core system, but authentication hooks might be
4164 : * interested in it.
4165 : */
4166 25938 : if (!criticalSharedRelcachesBuilt)
4167 : {
4168 2006 : load_critical_index(DatabaseNameIndexId,
4169 : DatabaseRelationId);
4170 2006 : load_critical_index(DatabaseOidIndexId,
4171 : DatabaseRelationId);
4172 2006 : load_critical_index(AuthIdRolnameIndexId,
4173 : AuthIdRelationId);
4174 2006 : load_critical_index(AuthIdOidIndexId,
4175 : AuthIdRelationId);
4176 2006 : load_critical_index(AuthMemMemRoleIndexId,
4177 : AuthMemRelationId);
4178 2006 : load_critical_index(SharedSecLabelObjectIndexId,
4179 : SharedSecLabelRelationId);
4180 :
4181 : #define NUM_CRITICAL_SHARED_INDEXES 6 /* fix if you change list above */
4182 :
4183 2006 : criticalSharedRelcachesBuilt = true;
4184 : }
4185 :
4186 : /*
4187 : * Now, scan all the relcache entries and update anything that might be
4188 : * wrong in the results from formrdesc or the relcache cache file. If we
4189 : * faked up relcache entries using formrdesc, then read the real pg_class
4190 : * rows and replace the fake entries with them. Also, if any of the
4191 : * relcache entries have rules, triggers, or security policies, load that
4192 : * info the hard way since it isn't recorded in the cache file.
4193 : *
4194 : * Whenever we access the catalogs to read data, there is a possibility of
4195 : * a shared-inval cache flush causing relcache entries to be removed.
4196 : * Since hash_seq_search only guarantees to still work after the *current*
4197 : * entry is removed, it's unsafe to continue the hashtable scan afterward.
4198 : * We handle this by restarting the scan from scratch after each access.
4199 : * This is theoretically O(N^2), but the number of entries that actually
4200 : * need to be fixed is small enough that it doesn't matter.
4201 : */
4202 25938 : hash_seq_init(&status, RelationIdCache);
4203 :
4204 3702928 : while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
4205 : {
4206 3676990 : Relation relation = idhentry->reldesc;
4207 3676990 : bool restart = false;
4208 :
4209 : /*
4210 : * Make sure *this* entry doesn't get flushed while we work with it.
4211 : */
4212 3676990 : RelationIncrementReferenceCount(relation);
4213 :
4214 : /*
4215 : * If it's a faked-up entry, read the real pg_class tuple.
4216 : */
4217 3676990 : if (relation->rd_rel->relowner == InvalidOid)
4218 : {
4219 : HeapTuple htup;
4220 : Form_pg_class relp;
4221 :
4222 20174 : htup = SearchSysCache1(RELOID,
4223 : ObjectIdGetDatum(RelationGetRelid(relation)));
4224 20174 : if (!HeapTupleIsValid(htup))
4225 0 : ereport(FATAL,
4226 : errcode(ERRCODE_UNDEFINED_OBJECT),
4227 : errmsg_internal("cache lookup failed for relation %u",
4228 : RelationGetRelid(relation)));
4229 20174 : relp = (Form_pg_class) GETSTRUCT(htup);
4230 :
4231 : /*
4232 : * Copy tuple to relation->rd_rel. (See notes in
4233 : * AllocateRelationDesc())
4234 : */
4235 20174 : memcpy((char *) relation->rd_rel, (char *) relp, CLASS_TUPLE_SIZE);
4236 :
4237 : /* Update rd_options while we have the tuple */
4238 20174 : if (relation->rd_options)
4239 0 : pfree(relation->rd_options);
4240 20174 : RelationParseRelOptions(relation, htup);
4241 :
4242 : /*
4243 : * Check the values in rd_att were set up correctly. (We cannot
4244 : * just copy them over now: formrdesc must have set up the rd_att
4245 : * data correctly to start with, because it may already have been
4246 : * copied into one or more catcache entries.)
4247 : */
4248 : Assert(relation->rd_att->tdtypeid == relp->reltype);
4249 : Assert(relation->rd_att->tdtypmod == -1);
4250 :
4251 20174 : ReleaseSysCache(htup);
4252 :
4253 : /* relowner had better be OK now, else we'll loop forever */
4254 20174 : if (relation->rd_rel->relowner == InvalidOid)
4255 0 : elog(ERROR, "invalid relowner in pg_class entry for \"%s\"",
4256 : RelationGetRelationName(relation));
4257 :
4258 20174 : restart = true;
4259 : }
4260 :
4261 : /*
4262 : * Fix data that isn't saved in relcache cache file.
4263 : *
4264 : * relhasrules or relhastriggers could possibly be wrong or out of
4265 : * date. If we don't actually find any rules or triggers, clear the
4266 : * local copy of the flag so that we don't get into an infinite loop
4267 : * here. We don't make any attempt to fix the pg_class entry, though.
4268 : */
4269 3676990 : if (relation->rd_rel->relhasrules && relation->rd_rules == NULL)
4270 : {
4271 0 : RelationBuildRuleLock(relation);
4272 0 : if (relation->rd_rules == NULL)
4273 0 : relation->rd_rel->relhasrules = false;
4274 0 : restart = true;
4275 : }
4276 3676990 : if (relation->rd_rel->relhastriggers && relation->trigdesc == NULL)
4277 : {
4278 0 : RelationBuildTriggers(relation);
4279 0 : if (relation->trigdesc == NULL)
4280 0 : relation->rd_rel->relhastriggers = false;
4281 0 : restart = true;
4282 : }
4283 :
4284 : /*
4285 : * Re-load the row security policies if the relation has them, since
4286 : * they are not preserved in the cache. Note that we can never NOT
4287 : * have a policy while relrowsecurity is true,
4288 : * RelationBuildRowSecurity will create a single default-deny policy
4289 : * if there is no policy defined in pg_policy.
4290 : */
4291 3676990 : if (relation->rd_rel->relrowsecurity && relation->rd_rsdesc == NULL)
4292 : {
4293 0 : RelationBuildRowSecurity(relation);
4294 :
4295 : Assert(relation->rd_rsdesc != NULL);
4296 0 : restart = true;
4297 : }
4298 :
4299 : /* Reload tableam data if needed */
4300 3676990 : if (relation->rd_tableam == NULL &&
4301 2253332 : (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind) || relation->rd_rel->relkind == RELKIND_SEQUENCE))
4302 : {
4303 0 : RelationInitTableAccessMethod(relation);
4304 : Assert(relation->rd_tableam != NULL);
4305 :
4306 0 : restart = true;
4307 : }
4308 :
4309 : /* Release hold on the relation */
4310 3676990 : RelationDecrementReferenceCount(relation);
4311 :
4312 : /* Now, restart the hashtable scan if needed */
4313 3676990 : if (restart)
4314 : {
4315 20174 : hash_seq_term(&status);
4316 20174 : hash_seq_init(&status, RelationIdCache);
4317 : }
4318 : }
4319 :
4320 : /*
4321 : * Lastly, write out new relcache cache files if needed. We don't bother
4322 : * to distinguish cases where only one of the two needs an update.
4323 : */
4324 25938 : if (needNewCacheFile)
4325 : {
4326 : /*
4327 : * Force all the catcaches to finish initializing and thereby open the
4328 : * catalogs and indexes they use. This will preload the relcache with
4329 : * entries for all the most important system catalogs and indexes, so
4330 : * that the init files will be most useful for future backends.
4331 : */
4332 2772 : InitCatalogCachePhase2();
4333 :
4334 : /* now write the files */
4335 2770 : write_relcache_init_file(true);
4336 2770 : write_relcache_init_file(false);
4337 : }
4338 : }
4339 :
4340 : /*
4341 : * Load one critical system index into the relcache
4342 : *
4343 : * indexoid is the OID of the target index, heapoid is the OID of the catalog
4344 : * it belongs to.
4345 : */
4346 : static void
4347 29804 : load_critical_index(Oid indexoid, Oid heapoid)
4348 : {
4349 : Relation ird;
4350 :
4351 : /*
4352 : * We must lock the underlying catalog before locking the index to avoid
4353 : * deadlock, since RelationBuildDesc might well need to read the catalog,
4354 : * and if anyone else is exclusive-locking this catalog and index they'll
4355 : * be doing it in that order.
4356 : */
4357 29804 : LockRelationOid(heapoid, AccessShareLock);
4358 29804 : LockRelationOid(indexoid, AccessShareLock);
4359 29804 : ird = RelationBuildDesc(indexoid, true);
4360 29800 : if (ird == NULL)
4361 0 : ereport(PANIC,
4362 : errcode(ERRCODE_DATA_CORRUPTED),
4363 : errmsg_internal("could not open critical system index %u", indexoid));
4364 29800 : ird->rd_isnailed = true;
4365 29800 : ird->rd_refcnt = 1;
4366 29800 : UnlockRelationOid(indexoid, AccessShareLock);
4367 29800 : UnlockRelationOid(heapoid, AccessShareLock);
4368 :
4369 29800 : (void) RelationGetIndexAttOptions(ird, false);
4370 29800 : }
4371 :
4372 : /*
4373 : * GetPgClassDescriptor -- get a predefined tuple descriptor for pg_class
4374 : * GetPgIndexDescriptor -- get a predefined tuple descriptor for pg_index
4375 : *
4376 : * We need this kluge because we have to be able to access non-fixed-width
4377 : * fields of pg_class and pg_index before we have the standard catalog caches
4378 : * available. We use predefined data that's set up in just the same way as
4379 : * the bootstrapped reldescs used by formrdesc(). The resulting tupdesc is
4380 : * not 100% kosher: it does not have the correct rowtype OID in tdtypeid, nor
4381 : * does it have a TupleConstr field. But it's good enough for the purpose of
4382 : * extracting fields.
4383 : */
4384 : static TupleDesc
4385 52062 : BuildHardcodedDescriptor(int natts, const FormData_pg_attribute *attrs)
4386 : {
4387 : TupleDesc result;
4388 : MemoryContext oldcxt;
4389 : int i;
4390 :
4391 52062 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
4392 :
4393 52062 : result = CreateTemplateTupleDesc(natts);
4394 52062 : result->tdtypeid = RECORDOID; /* not right, but we don't care */
4395 52062 : result->tdtypmod = -1;
4396 :
4397 1457748 : for (i = 0; i < natts; i++)
4398 : {
4399 1405686 : memcpy(TupleDescAttr(result, i), &attrs[i], ATTRIBUTE_FIXED_PART_SIZE);
4400 : /* make sure attcacheoff is valid */
4401 1405686 : TupleDescAttr(result, i)->attcacheoff = -1;
4402 : }
4403 :
4404 : /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
4405 52062 : TupleDescAttr(result, 0)->attcacheoff = 0;
4406 :
4407 : /* Note: we don't bother to set up a TupleConstr entry */
4408 :
4409 52062 : MemoryContextSwitchTo(oldcxt);
4410 :
4411 52062 : return result;
4412 : }
4413 :
4414 : static TupleDesc
4415 1452570 : GetPgClassDescriptor(void)
4416 : {
4417 : static TupleDesc pgclassdesc = NULL;
4418 :
4419 : /* Already done? */
4420 1452570 : if (pgclassdesc == NULL)
4421 26032 : pgclassdesc = BuildHardcodedDescriptor(Natts_pg_class,
4422 : Desc_pg_class);
4423 :
4424 1452570 : return pgclassdesc;
4425 : }
4426 :
4427 : static TupleDesc
4428 1652176 : GetPgIndexDescriptor(void)
4429 : {
4430 : static TupleDesc pgindexdesc = NULL;
4431 :
4432 : /* Already done? */
4433 1652176 : if (pgindexdesc == NULL)
4434 26030 : pgindexdesc = BuildHardcodedDescriptor(Natts_pg_index,
4435 : Desc_pg_index);
4436 :
4437 1652176 : return pgindexdesc;
4438 : }
4439 :
4440 : /*
4441 : * Load any default attribute value definitions for the relation.
4442 : *
4443 : * ndef is the number of attributes that were marked atthasdef.
4444 : *
4445 : * Note: we don't make it a hard error to be missing some pg_attrdef records.
4446 : * We can limp along as long as nothing needs to use the default value. Code
4447 : * that fails to find an expected AttrDefault record should throw an error.
4448 : */
4449 : static void
4450 27504 : AttrDefaultFetch(Relation relation, int ndef)
4451 : {
4452 : AttrDefault *attrdef;
4453 : Relation adrel;
4454 : SysScanDesc adscan;
4455 : ScanKeyData skey;
4456 : HeapTuple htup;
4457 27504 : int found = 0;
4458 :
4459 : /* Allocate array with room for as many entries as expected */
4460 : attrdef = (AttrDefault *)
4461 27504 : MemoryContextAllocZero(CacheMemoryContext,
4462 : ndef * sizeof(AttrDefault));
4463 :
4464 : /* Search pg_attrdef for relevant entries */
4465 27504 : ScanKeyInit(&skey,
4466 : Anum_pg_attrdef_adrelid,
4467 : BTEqualStrategyNumber, F_OIDEQ,
4468 : ObjectIdGetDatum(RelationGetRelid(relation)));
4469 :
4470 27504 : adrel = table_open(AttrDefaultRelationId, AccessShareLock);
4471 27504 : adscan = systable_beginscan(adrel, AttrDefaultIndexId, true,
4472 : NULL, 1, &skey);
4473 :
4474 65930 : while (HeapTupleIsValid(htup = systable_getnext(adscan)))
4475 : {
4476 38426 : Form_pg_attrdef adform = (Form_pg_attrdef) GETSTRUCT(htup);
4477 : Datum val;
4478 : bool isnull;
4479 :
4480 : /* protect limited size of array */
4481 38426 : if (found >= ndef)
4482 : {
4483 0 : elog(WARNING, "unexpected pg_attrdef record found for attribute %d of relation \"%s\"",
4484 : adform->adnum, RelationGetRelationName(relation));
4485 0 : break;
4486 : }
4487 :
4488 38426 : val = fastgetattr(htup,
4489 : Anum_pg_attrdef_adbin,
4490 : adrel->rd_att, &isnull);
4491 38426 : if (isnull)
4492 0 : elog(WARNING, "null adbin for attribute %d of relation \"%s\"",
4493 : adform->adnum, RelationGetRelationName(relation));
4494 : else
4495 : {
4496 : /* detoast and convert to cstring in caller's context */
4497 38426 : char *s = TextDatumGetCString(val);
4498 :
4499 38426 : attrdef[found].adnum = adform->adnum;
4500 38426 : attrdef[found].adbin = MemoryContextStrdup(CacheMemoryContext, s);
4501 38426 : pfree(s);
4502 38426 : found++;
4503 : }
4504 : }
4505 :
4506 27504 : systable_endscan(adscan);
4507 27504 : table_close(adrel, AccessShareLock);
4508 :
4509 27504 : if (found != ndef)
4510 0 : elog(WARNING, "%d pg_attrdef record(s) missing for relation \"%s\"",
4511 : ndef - found, RelationGetRelationName(relation));
4512 :
4513 : /*
4514 : * Sort the AttrDefault entries by adnum, for the convenience of
4515 : * equalTupleDescs(). (Usually, they already will be in order, but this
4516 : * might not be so if systable_getnext isn't using an index.)
4517 : */
4518 27504 : if (found > 1)
4519 5758 : qsort(attrdef, found, sizeof(AttrDefault), AttrDefaultCmp);
4520 :
4521 : /* Install array only after it's fully valid */
4522 27504 : relation->rd_att->constr->defval = attrdef;
4523 27504 : relation->rd_att->constr->num_defval = found;
4524 27504 : }
4525 :
4526 : /*
4527 : * qsort comparator to sort AttrDefault entries by adnum
4528 : */
4529 : static int
4530 10922 : AttrDefaultCmp(const void *a, const void *b)
4531 : {
4532 10922 : const AttrDefault *ada = (const AttrDefault *) a;
4533 10922 : const AttrDefault *adb = (const AttrDefault *) b;
4534 :
4535 10922 : return pg_cmp_s16(ada->adnum, adb->adnum);
4536 : }
4537 :
4538 : /*
4539 : * Load any check constraints for the relation.
4540 : *
4541 : * As with defaults, if we don't find the expected number of them, just warn
4542 : * here. The executor should throw an error if an INSERT/UPDATE is attempted.
4543 : */
4544 : static void
4545 10708 : CheckConstraintFetch(Relation relation)
4546 : {
4547 : ConstrCheck *check;
4548 10708 : int ncheck = relation->rd_rel->relchecks;
4549 : Relation conrel;
4550 : SysScanDesc conscan;
4551 : ScanKeyData skey[1];
4552 : HeapTuple htup;
4553 10708 : int found = 0;
4554 :
4555 : /* Allocate array with room for as many entries as expected */
4556 : check = (ConstrCheck *)
4557 10708 : MemoryContextAllocZero(CacheMemoryContext,
4558 : ncheck * sizeof(ConstrCheck));
4559 :
4560 : /* Search pg_constraint for relevant entries */
4561 10708 : ScanKeyInit(&skey[0],
4562 : Anum_pg_constraint_conrelid,
4563 : BTEqualStrategyNumber, F_OIDEQ,
4564 : ObjectIdGetDatum(RelationGetRelid(relation)));
4565 :
4566 10708 : conrel = table_open(ConstraintRelationId, AccessShareLock);
4567 10708 : conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
4568 : NULL, 1, skey);
4569 :
4570 35530 : while (HeapTupleIsValid(htup = systable_getnext(conscan)))
4571 : {
4572 24822 : Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(htup);
4573 : Datum val;
4574 : bool isnull;
4575 :
4576 : /* We want check constraints only */
4577 24822 : if (conform->contype != CONSTRAINT_CHECK)
4578 11092 : continue;
4579 :
4580 : /* protect limited size of array */
4581 13730 : if (found >= ncheck)
4582 : {
4583 0 : elog(WARNING, "unexpected pg_constraint record found for relation \"%s\"",
4584 : RelationGetRelationName(relation));
4585 0 : break;
4586 : }
4587 :
4588 13730 : check[found].ccvalid = conform->convalidated;
4589 13730 : check[found].ccnoinherit = conform->connoinherit;
4590 27460 : check[found].ccname = MemoryContextStrdup(CacheMemoryContext,
4591 13730 : NameStr(conform->conname));
4592 :
4593 : /* Grab and test conbin is actually set */
4594 13730 : val = fastgetattr(htup,
4595 : Anum_pg_constraint_conbin,
4596 : conrel->rd_att, &isnull);
4597 13730 : if (isnull)
4598 0 : elog(WARNING, "null conbin for relation \"%s\"",
4599 : RelationGetRelationName(relation));
4600 : else
4601 : {
4602 : /* detoast and convert to cstring in caller's context */
4603 13730 : char *s = TextDatumGetCString(val);
4604 :
4605 13730 : check[found].ccbin = MemoryContextStrdup(CacheMemoryContext, s);
4606 13730 : pfree(s);
4607 13730 : found++;
4608 : }
4609 : }
4610 :
4611 10708 : systable_endscan(conscan);
4612 10708 : table_close(conrel, AccessShareLock);
4613 :
4614 10708 : if (found != ncheck)
4615 0 : elog(WARNING, "%d pg_constraint record(s) missing for relation \"%s\"",
4616 : ncheck - found, RelationGetRelationName(relation));
4617 :
4618 : /*
4619 : * Sort the records by name. This ensures that CHECKs are applied in a
4620 : * deterministic order, and it also makes equalTupleDescs() faster.
4621 : */
4622 10708 : if (found > 1)
4623 2472 : qsort(check, found, sizeof(ConstrCheck), CheckConstraintCmp);
4624 :
4625 : /* Install array only after it's fully valid */
4626 10708 : relation->rd_att->constr->check = check;
4627 10708 : relation->rd_att->constr->num_check = found;
4628 10708 : }
4629 :
4630 : /*
4631 : * qsort comparator to sort ConstrCheck entries by name
4632 : */
4633 : static int
4634 3022 : CheckConstraintCmp(const void *a, const void *b)
4635 : {
4636 3022 : const ConstrCheck *ca = (const ConstrCheck *) a;
4637 3022 : const ConstrCheck *cb = (const ConstrCheck *) b;
4638 :
4639 3022 : return strcmp(ca->ccname, cb->ccname);
4640 : }
4641 :
4642 : /*
4643 : * RelationGetFKeyList -- get a list of foreign key info for the relation
4644 : *
4645 : * Returns a list of ForeignKeyCacheInfo structs, one per FK constraining
4646 : * the given relation. This data is a direct copy of relevant fields from
4647 : * pg_constraint. The list items are in no particular order.
4648 : *
4649 : * CAUTION: the returned list is part of the relcache's data, and could
4650 : * vanish in a relcache entry reset. Callers must inspect or copy it
4651 : * before doing anything that might trigger a cache flush, such as
4652 : * system catalog accesses. copyObject() can be used if desired.
4653 : * (We define it this way because current callers want to filter and
4654 : * modify the list entries anyway, so copying would be a waste of time.)
4655 : */
4656 : List *
4657 205616 : RelationGetFKeyList(Relation relation)
4658 : {
4659 : List *result;
4660 : Relation conrel;
4661 : SysScanDesc conscan;
4662 : ScanKeyData skey;
4663 : HeapTuple htup;
4664 : List *oldlist;
4665 : MemoryContext oldcxt;
4666 :
4667 : /* Quick exit if we already computed the list. */
4668 205616 : if (relation->rd_fkeyvalid)
4669 1244 : return relation->rd_fkeylist;
4670 :
4671 : /* Fast path: non-partitioned tables without triggers can't have FKs */
4672 204372 : if (!relation->rd_rel->relhastriggers &&
4673 201356 : relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
4674 192678 : return NIL;
4675 :
4676 : /*
4677 : * We build the list we intend to return (in the caller's context) while
4678 : * doing the scan. After successfully completing the scan, we copy that
4679 : * list into the relcache entry. This avoids cache-context memory leakage
4680 : * if we get some sort of error partway through.
4681 : */
4682 11694 : result = NIL;
4683 :
4684 : /* Prepare to scan pg_constraint for entries having conrelid = this rel. */
4685 11694 : ScanKeyInit(&skey,
4686 : Anum_pg_constraint_conrelid,
4687 : BTEqualStrategyNumber, F_OIDEQ,
4688 : ObjectIdGetDatum(RelationGetRelid(relation)));
4689 :
4690 11694 : conrel = table_open(ConstraintRelationId, AccessShareLock);
4691 11694 : conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
4692 : NULL, 1, &skey);
4693 :
4694 21280 : while (HeapTupleIsValid(htup = systable_getnext(conscan)))
4695 : {
4696 9586 : Form_pg_constraint constraint = (Form_pg_constraint) GETSTRUCT(htup);
4697 : ForeignKeyCacheInfo *info;
4698 :
4699 : /* consider only foreign keys */
4700 9586 : if (constraint->contype != CONSTRAINT_FOREIGN)
4701 6550 : continue;
4702 :
4703 3036 : info = makeNode(ForeignKeyCacheInfo);
4704 3036 : info->conoid = constraint->oid;
4705 3036 : info->conrelid = constraint->conrelid;
4706 3036 : info->confrelid = constraint->confrelid;
4707 :
4708 3036 : DeconstructFkConstraintRow(htup, &info->nkeys,
4709 3036 : info->conkey,
4710 3036 : info->confkey,
4711 3036 : info->conpfeqop,
4712 : NULL, NULL, NULL, NULL);
4713 :
4714 : /* Add FK's node to the result list */
4715 3036 : result = lappend(result, info);
4716 : }
4717 :
4718 11694 : systable_endscan(conscan);
4719 11694 : table_close(conrel, AccessShareLock);
4720 :
4721 : /* Now save a copy of the completed list in the relcache entry. */
4722 11694 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
4723 11694 : oldlist = relation->rd_fkeylist;
4724 11694 : relation->rd_fkeylist = copyObject(result);
4725 11694 : relation->rd_fkeyvalid = true;
4726 11694 : MemoryContextSwitchTo(oldcxt);
4727 :
4728 : /* Don't leak the old list, if there is one */
4729 11694 : list_free_deep(oldlist);
4730 :
4731 11694 : return result;
4732 : }
4733 :
4734 : /*
4735 : * RelationGetIndexList -- get a list of OIDs of indexes on this relation
4736 : *
4737 : * The index list is created only if someone requests it. We scan pg_index
4738 : * to find relevant indexes, and add the list to the relcache entry so that
4739 : * we won't have to compute it again. Note that shared cache inval of a
4740 : * relcache entry will delete the old list and set rd_indexvalid to false,
4741 : * so that we must recompute the index list on next request. This handles
4742 : * creation or deletion of an index.
4743 : *
4744 : * Indexes that are marked not indislive are omitted from the returned list.
4745 : * Such indexes are expected to be dropped momentarily, and should not be
4746 : * touched at all by any caller of this function.
4747 : *
4748 : * The returned list is guaranteed to be sorted in order by OID. This is
4749 : * needed by the executor, since for index types that we obtain exclusive
4750 : * locks on when updating the index, all backends must lock the indexes in
4751 : * the same order or we will get deadlocks (see ExecOpenIndices()). Any
4752 : * consistent ordering would do, but ordering by OID is easy.
4753 : *
4754 : * Since shared cache inval causes the relcache's copy of the list to go away,
4755 : * we return a copy of the list palloc'd in the caller's context. The caller
4756 : * may list_free() the returned list after scanning it. This is necessary
4757 : * since the caller will typically be doing syscache lookups on the relevant
4758 : * indexes, and syscache lookup could cause SI messages to be processed!
4759 : *
4760 : * In exactly the same way, we update rd_pkindex, which is the OID of the
4761 : * relation's primary key index if any, else InvalidOid; and rd_replidindex,
4762 : * which is the pg_class OID of an index to be used as the relation's
4763 : * replication identity index, or InvalidOid if there is no such index.
4764 : */
4765 : List *
4766 2153084 : RelationGetIndexList(Relation relation)
4767 : {
4768 : Relation indrel;
4769 : SysScanDesc indscan;
4770 : ScanKeyData skey;
4771 : HeapTuple htup;
4772 : List *result;
4773 : List *oldlist;
4774 2153084 : char replident = relation->rd_rel->relreplident;
4775 2153084 : Oid pkeyIndex = InvalidOid;
4776 2153084 : Oid candidateIndex = InvalidOid;
4777 2153084 : bool pkdeferrable = false;
4778 : MemoryContext oldcxt;
4779 :
4780 : /* Quick exit if we already computed the list. */
4781 2153084 : if (relation->rd_indexvalid)
4782 1913362 : return list_copy(relation->rd_indexlist);
4783 :
4784 : /*
4785 : * We build the list we intend to return (in the caller's context) while
4786 : * doing the scan. After successfully completing the scan, we copy that
4787 : * list into the relcache entry. This avoids cache-context memory leakage
4788 : * if we get some sort of error partway through.
4789 : */
4790 239722 : result = NIL;
4791 :
4792 : /* Prepare to scan pg_index for entries having indrelid = this rel. */
4793 239722 : ScanKeyInit(&skey,
4794 : Anum_pg_index_indrelid,
4795 : BTEqualStrategyNumber, F_OIDEQ,
4796 : ObjectIdGetDatum(RelationGetRelid(relation)));
4797 :
4798 239722 : indrel = table_open(IndexRelationId, AccessShareLock);
4799 239722 : indscan = systable_beginscan(indrel, IndexIndrelidIndexId, true,
4800 : NULL, 1, &skey);
4801 :
4802 589342 : while (HeapTupleIsValid(htup = systable_getnext(indscan)))
4803 : {
4804 349620 : Form_pg_index index = (Form_pg_index) GETSTRUCT(htup);
4805 :
4806 : /*
4807 : * Ignore any indexes that are currently being dropped. This will
4808 : * prevent them from being searched, inserted into, or considered in
4809 : * HOT-safety decisions. It's unsafe to touch such an index at all
4810 : * since its catalog entries could disappear at any instant.
4811 : */
4812 349620 : if (!index->indislive)
4813 66 : continue;
4814 :
4815 : /* add index's OID to result list */
4816 349554 : result = lappend_oid(result, index->indexrelid);
4817 :
4818 : /*
4819 : * Non-unique or predicate indexes aren't interesting for either oid
4820 : * indexes or replication identity indexes, so don't check them.
4821 : * Deferred ones are not useful for replication identity either; but
4822 : * we do include them if they are PKs.
4823 : */
4824 349554 : if (!index->indisunique ||
4825 293424 : !heap_attisnull(htup, Anum_pg_index_indpred, NULL))
4826 56284 : continue;
4827 :
4828 : /*
4829 : * Remember primary key index, if any. For regular tables we do this
4830 : * only if the index is valid; but for partitioned tables, then we do
4831 : * it even if it's invalid.
4832 : *
4833 : * The reason for returning invalid primary keys for partitioned
4834 : * tables is that we need it to prevent drop of not-null constraints
4835 : * that may underlie such a primary key, which is only a problem for
4836 : * partitioned tables.
4837 : */
4838 293270 : if (index->indisprimary &&
4839 188726 : (index->indisvalid ||
4840 12 : relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE))
4841 : {
4842 188726 : pkeyIndex = index->indexrelid;
4843 188726 : pkdeferrable = !index->indimmediate;
4844 : }
4845 :
4846 293270 : if (!index->indimmediate)
4847 140 : continue;
4848 :
4849 293130 : if (!index->indisvalid)
4850 68 : continue;
4851 :
4852 : /* remember explicitly chosen replica index */
4853 293062 : if (index->indisreplident)
4854 506 : candidateIndex = index->indexrelid;
4855 : }
4856 :
4857 239722 : systable_endscan(indscan);
4858 :
4859 239722 : table_close(indrel, AccessShareLock);
4860 :
4861 : /* Sort the result list into OID order, per API spec. */
4862 239722 : list_sort(result, list_oid_cmp);
4863 :
4864 : /* Now save a copy of the completed list in the relcache entry. */
4865 239722 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
4866 239722 : oldlist = relation->rd_indexlist;
4867 239722 : relation->rd_indexlist = list_copy(result);
4868 239722 : relation->rd_pkindex = pkeyIndex;
4869 239722 : relation->rd_ispkdeferrable = pkdeferrable;
4870 239722 : if (replident == REPLICA_IDENTITY_DEFAULT && OidIsValid(pkeyIndex) && !pkdeferrable)
4871 25030 : relation->rd_replidindex = pkeyIndex;
4872 214692 : else if (replident == REPLICA_IDENTITY_INDEX && OidIsValid(candidateIndex))
4873 506 : relation->rd_replidindex = candidateIndex;
4874 : else
4875 214186 : relation->rd_replidindex = InvalidOid;
4876 239722 : relation->rd_indexvalid = true;
4877 239722 : MemoryContextSwitchTo(oldcxt);
4878 :
4879 : /* Don't leak the old list, if there is one */
4880 239722 : list_free(oldlist);
4881 :
4882 239722 : return result;
4883 : }
4884 :
4885 : /*
4886 : * RelationGetStatExtList
4887 : * get a list of OIDs of statistics objects on this relation
4888 : *
4889 : * The statistics list is created only if someone requests it, in a way
4890 : * similar to RelationGetIndexList(). We scan pg_statistic_ext to find
4891 : * relevant statistics, and add the list to the relcache entry so that we
4892 : * won't have to compute it again. Note that shared cache inval of a
4893 : * relcache entry will delete the old list and set rd_statvalid to 0,
4894 : * so that we must recompute the statistics list on next request. This
4895 : * handles creation or deletion of a statistics object.
4896 : *
4897 : * The returned list is guaranteed to be sorted in order by OID, although
4898 : * this is not currently needed.
4899 : *
4900 : * Since shared cache inval causes the relcache's copy of the list to go away,
4901 : * we return a copy of the list palloc'd in the caller's context. The caller
4902 : * may list_free() the returned list after scanning it. This is necessary
4903 : * since the caller will typically be doing syscache lookups on the relevant
4904 : * statistics, and syscache lookup could cause SI messages to be processed!
4905 : */
4906 : List *
4907 425522 : RelationGetStatExtList(Relation relation)
4908 : {
4909 : Relation indrel;
4910 : SysScanDesc indscan;
4911 : ScanKeyData skey;
4912 : HeapTuple htup;
4913 : List *result;
4914 : List *oldlist;
4915 : MemoryContext oldcxt;
4916 :
4917 : /* Quick exit if we already computed the list. */
4918 425522 : if (relation->rd_statvalid != 0)
4919 322598 : return list_copy(relation->rd_statlist);
4920 :
4921 : /*
4922 : * We build the list we intend to return (in the caller's context) while
4923 : * doing the scan. After successfully completing the scan, we copy that
4924 : * list into the relcache entry. This avoids cache-context memory leakage
4925 : * if we get some sort of error partway through.
4926 : */
4927 102924 : result = NIL;
4928 :
4929 : /*
4930 : * Prepare to scan pg_statistic_ext for entries having stxrelid = this
4931 : * rel.
4932 : */
4933 102924 : ScanKeyInit(&skey,
4934 : Anum_pg_statistic_ext_stxrelid,
4935 : BTEqualStrategyNumber, F_OIDEQ,
4936 : ObjectIdGetDatum(RelationGetRelid(relation)));
4937 :
4938 102924 : indrel = table_open(StatisticExtRelationId, AccessShareLock);
4939 102924 : indscan = systable_beginscan(indrel, StatisticExtRelidIndexId, true,
4940 : NULL, 1, &skey);
4941 :
4942 103310 : while (HeapTupleIsValid(htup = systable_getnext(indscan)))
4943 : {
4944 386 : Oid oid = ((Form_pg_statistic_ext) GETSTRUCT(htup))->oid;
4945 :
4946 386 : result = lappend_oid(result, oid);
4947 : }
4948 :
4949 102924 : systable_endscan(indscan);
4950 :
4951 102924 : table_close(indrel, AccessShareLock);
4952 :
4953 : /* Sort the result list into OID order, per API spec. */
4954 102924 : list_sort(result, list_oid_cmp);
4955 :
4956 : /* Now save a copy of the completed list in the relcache entry. */
4957 102924 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
4958 102924 : oldlist = relation->rd_statlist;
4959 102924 : relation->rd_statlist = list_copy(result);
4960 :
4961 102924 : relation->rd_statvalid = true;
4962 102924 : MemoryContextSwitchTo(oldcxt);
4963 :
4964 : /* Don't leak the old list, if there is one */
4965 102924 : list_free(oldlist);
4966 :
4967 102924 : return result;
4968 : }
4969 :
4970 : /*
4971 : * RelationGetPrimaryKeyIndex -- get OID of the relation's primary key index
4972 : *
4973 : * Returns InvalidOid if there is no such index, or if the primary key is
4974 : * DEFERRABLE and the caller isn't OK with that.
4975 : */
4976 : Oid
4977 380 : RelationGetPrimaryKeyIndex(Relation relation, bool deferrable_ok)
4978 : {
4979 : List *ilist;
4980 :
4981 380 : if (!relation->rd_indexvalid)
4982 : {
4983 : /* RelationGetIndexList does the heavy lifting. */
4984 18 : ilist = RelationGetIndexList(relation);
4985 18 : list_free(ilist);
4986 : Assert(relation->rd_indexvalid);
4987 : }
4988 :
4989 380 : if (deferrable_ok)
4990 18 : return relation->rd_pkindex;
4991 362 : else if (relation->rd_ispkdeferrable)
4992 0 : return InvalidOid;
4993 362 : return relation->rd_pkindex;
4994 : }
4995 :
4996 : /*
4997 : * RelationGetReplicaIndex -- get OID of the relation's replica identity index
4998 : *
4999 : * Returns InvalidOid if there is no such index.
5000 : */
5001 : Oid
5002 317676 : RelationGetReplicaIndex(Relation relation)
5003 : {
5004 : List *ilist;
5005 :
5006 317676 : if (!relation->rd_indexvalid)
5007 : {
5008 : /* RelationGetIndexList does the heavy lifting. */
5009 4836 : ilist = RelationGetIndexList(relation);
5010 4836 : list_free(ilist);
5011 : Assert(relation->rd_indexvalid);
5012 : }
5013 :
5014 317676 : return relation->rd_replidindex;
5015 : }
5016 :
5017 : /*
5018 : * RelationGetIndexExpressions -- get the index expressions for an index
5019 : *
5020 : * We cache the result of transforming pg_index.indexprs into a node tree.
5021 : * If the rel is not an index or has no expressional columns, we return NIL.
5022 : * Otherwise, the returned tree is copied into the caller's memory context.
5023 : * (We don't want to return a pointer to the relcache copy, since it could
5024 : * disappear due to relcache invalidation.)
5025 : */
5026 : List *
5027 3884918 : RelationGetIndexExpressions(Relation relation)
5028 : {
5029 : List *result;
5030 : Datum exprsDatum;
5031 : bool isnull;
5032 : char *exprsString;
5033 : MemoryContext oldcxt;
5034 :
5035 : /* Quick exit if we already computed the result. */
5036 3884918 : if (relation->rd_indexprs)
5037 2996 : return copyObject(relation->rd_indexprs);
5038 :
5039 : /* Quick exit if there is nothing to do. */
5040 7763844 : if (relation->rd_indextuple == NULL ||
5041 3881922 : heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
5042 3880372 : return NIL;
5043 :
5044 : /*
5045 : * We build the tree we intend to return in the caller's context. After
5046 : * successfully completing the work, we copy it into the relcache entry.
5047 : * This avoids problems if we get some sort of error partway through.
5048 : */
5049 1550 : exprsDatum = heap_getattr(relation->rd_indextuple,
5050 : Anum_pg_index_indexprs,
5051 : GetPgIndexDescriptor(),
5052 : &isnull);
5053 : Assert(!isnull);
5054 1550 : exprsString = TextDatumGetCString(exprsDatum);
5055 1550 : result = (List *) stringToNode(exprsString);
5056 1550 : pfree(exprsString);
5057 :
5058 : /*
5059 : * Run the expressions through eval_const_expressions. This is not just an
5060 : * optimization, but is necessary, because the planner will be comparing
5061 : * them to similarly-processed qual clauses, and may fail to detect valid
5062 : * matches without this. We must not use canonicalize_qual, however,
5063 : * since these aren't qual expressions.
5064 : */
5065 1550 : result = (List *) eval_const_expressions(NULL, (Node *) result);
5066 :
5067 : /* May as well fix opfuncids too */
5068 1550 : fix_opfuncids((Node *) result);
5069 :
5070 : /* Now save a copy of the completed tree in the relcache entry. */
5071 1550 : oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
5072 1550 : relation->rd_indexprs = copyObject(result);
5073 1550 : MemoryContextSwitchTo(oldcxt);
5074 :
5075 1550 : return result;
5076 : }
5077 :
5078 : /*
5079 : * RelationGetDummyIndexExpressions -- get dummy expressions for an index
5080 : *
5081 : * Return a list of dummy expressions (just Const nodes) with the same
5082 : * types/typmods/collations as the index's real expressions. This is
5083 : * useful in situations where we don't want to run any user-defined code.
5084 : */
5085 : List *
5086 238 : RelationGetDummyIndexExpressions(Relation relation)
5087 : {
5088 : List *result;
5089 : Datum exprsDatum;
5090 : bool isnull;
5091 : char *exprsString;
5092 : List *rawExprs;
5093 : ListCell *lc;
5094 :
5095 : /* Quick exit if there is nothing to do. */
5096 476 : if (relation->rd_indextuple == NULL ||
5097 238 : heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
5098 220 : return NIL;
5099 :
5100 : /* Extract raw node tree(s) from index tuple. */
5101 18 : exprsDatum = heap_getattr(relation->rd_indextuple,
5102 : Anum_pg_index_indexprs,
5103 : GetPgIndexDescriptor(),
5104 : &isnull);
5105 : Assert(!isnull);
5106 18 : exprsString = TextDatumGetCString(exprsDatum);
5107 18 : rawExprs = (List *) stringToNode(exprsString);
5108 18 : pfree(exprsString);
5109 :
5110 : /* Construct null Consts; the typlen and typbyval are arbitrary. */
5111 18 : result = NIL;
5112 36 : foreach(lc, rawExprs)
5113 : {
5114 18 : Node *rawExpr = (Node *) lfirst(lc);
5115 :
5116 18 : result = lappend(result,
5117 18 : makeConst(exprType(rawExpr),
5118 : exprTypmod(rawExpr),
5119 : exprCollation(rawExpr),
5120 : 1,
5121 : (Datum) 0,
5122 : true,
5123 : true));
5124 : }
5125 :
5126 18 : return result;
5127 : }
5128 :
5129 : /*
5130 : * RelationGetIndexPredicate -- get the index predicate for an index
5131 : *
5132 : * We cache the result of transforming pg_index.indpred into an implicit-AND
5133 : * node tree (suitable for use in planning).
5134 : * If the rel is not an index or has no predicate, we return NIL.
5135 : * Otherwise, the returned tree is copied into the caller's memory context.
5136 : * (We don't want to return a pointer to the relcache copy, since it could
5137 : * disappear due to relcache invalidation.)
5138 : */
5139 : List *
5140 3884770 : RelationGetIndexPredicate(Relation relation)
5141 : {
5142 : List *result;
5143 : Datum predDatum;
5144 : bool isnull;
5145 : char *predString;
5146 : MemoryContext oldcxt;
5147 :
5148 : /* Quick exit if we already computed the result. */
5149 3884770 : if (relation->rd_indpred)
5150 1288 : return copyObject(relation->rd_indpred);
5151 :
5152 : /* Quick exit if there is nothing to do. */
5153 7766964 : if (relation->rd_indextuple == NULL ||
5154 3883482 : heap_attisnull(relation->rd_indextuple, Anum_pg_index_indpred, NULL))
5155 3882532 : return NIL;
5156 :
5157 : /*
5158 : * We build the tree we intend to return in the caller's context. After
5159 : * successfully completing the work, we copy it into the relcache entry.
5160 : * This avoids problems if we get some sort of error partway through.
5161 : */
5162 950 : predDatum = heap_getattr(relation->rd_indextuple,
5163 : Anum_pg_index_indpred,
5164 : GetPgIndexDescriptor(),
5165 : &isnull);
5166 : Assert(!isnull);
5167 950 : predString = TextDatumGetCString(predDatum);
5168 950 : result = (List *) stringToNode(predString);
5169 950 : pfree(predString);
5170 :
5171 : /*
5172 : * Run the expression through const-simplification and canonicalization.
5173 : * This is not just an optimization, but is necessary, because the planner
5174 : * will be comparing it to similarly-processed qual clauses, and may fail
5175 : * to detect valid matches without this. This must match the processing
5176 : * done to qual clauses in preprocess_expression()! (We can skip the
5177 : * stuff involving subqueries, however, since we don't allow any in index
5178 : * predicates.)
5179 : */
5180 950 : result = (List *) eval_const_expressions(NULL, (Node *) result);
5181 :
5182 950 : result = (List *) canonicalize_qual((Expr *) result, false);
5183 :
5184 : /* Also convert to implicit-AND format */
5185 950 : result = make_ands_implicit((Expr *) result);
5186 :
5187 : /* May as well fix opfuncids too */
5188 950 : fix_opfuncids((Node *) result);
5189 :
5190 : /* Now save a copy of the completed tree in the relcache entry. */
5191 950 : oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
5192 950 : relation->rd_indpred = copyObject(result);
5193 950 : MemoryContextSwitchTo(oldcxt);
5194 :
5195 950 : return result;
5196 : }
5197 :
5198 : /*
5199 : * RelationGetIndexAttrBitmap -- get a bitmap of index attribute numbers
5200 : *
5201 : * The result has a bit set for each attribute used anywhere in the index
5202 : * definitions of all the indexes on this relation. (This includes not only
5203 : * simple index keys, but attributes used in expressions and partial-index
5204 : * predicates.)
5205 : *
5206 : * Depending on attrKind, a bitmap covering attnums for certain columns is
5207 : * returned:
5208 : * INDEX_ATTR_BITMAP_KEY Columns in non-partial unique indexes not
5209 : * in expressions (i.e., usable for FKs)
5210 : * INDEX_ATTR_BITMAP_PRIMARY_KEY Columns in the table's primary key
5211 : * (beware: even if PK is deferrable!)
5212 : * INDEX_ATTR_BITMAP_IDENTITY_KEY Columns in the table's replica identity
5213 : * index (empty if FULL)
5214 : * INDEX_ATTR_BITMAP_HOT_BLOCKING Columns that block updates from being HOT
5215 : * INDEX_ATTR_BITMAP_SUMMARIZED Columns included in summarizing indexes
5216 : *
5217 : * Attribute numbers are offset by FirstLowInvalidHeapAttributeNumber so that
5218 : * we can include system attributes (e.g., OID) in the bitmap representation.
5219 : *
5220 : * Deferred indexes are considered for the primary key, but not for replica
5221 : * identity.
5222 : *
5223 : * Caller had better hold at least RowExclusiveLock on the target relation
5224 : * to ensure it is safe (deadlock-free) for us to take locks on the relation's
5225 : * indexes. Note that since the introduction of CREATE INDEX CONCURRENTLY,
5226 : * that lock level doesn't guarantee a stable set of indexes, so we have to
5227 : * be prepared to retry here in case of a change in the set of indexes.
5228 : *
5229 : * The returned result is palloc'd in the caller's memory context and should
5230 : * be bms_free'd when not needed anymore.
5231 : */
5232 : Bitmapset *
5233 2521978 : RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
5234 : {
5235 : Bitmapset *uindexattrs; /* columns in unique indexes */
5236 : Bitmapset *pkindexattrs; /* columns in the primary index */
5237 : Bitmapset *idindexattrs; /* columns in the replica identity */
5238 : Bitmapset *hotblockingattrs; /* columns with HOT blocking indexes */
5239 : Bitmapset *summarizedattrs; /* columns with summarizing indexes */
5240 : List *indexoidlist;
5241 : List *newindexoidlist;
5242 : Oid relpkindex;
5243 : Oid relreplindex;
5244 : ListCell *l;
5245 : MemoryContext oldcxt;
5246 :
5247 : /* Quick exit if we already computed the result. */
5248 2521978 : if (relation->rd_attrsvalid)
5249 : {
5250 2095794 : switch (attrKind)
5251 : {
5252 508126 : case INDEX_ATTR_BITMAP_KEY:
5253 508126 : return bms_copy(relation->rd_keyattr);
5254 54 : case INDEX_ATTR_BITMAP_PRIMARY_KEY:
5255 54 : return bms_copy(relation->rd_pkattr);
5256 595620 : case INDEX_ATTR_BITMAP_IDENTITY_KEY:
5257 595620 : return bms_copy(relation->rd_idattr);
5258 490382 : case INDEX_ATTR_BITMAP_HOT_BLOCKING:
5259 490382 : return bms_copy(relation->rd_hotblockingattr);
5260 501612 : case INDEX_ATTR_BITMAP_SUMMARIZED:
5261 501612 : return bms_copy(relation->rd_summarizedattr);
5262 0 : default:
5263 0 : elog(ERROR, "unknown attrKind %u", attrKind);
5264 : }
5265 : }
5266 :
5267 : /* Fast path if definitely no indexes */
5268 426184 : if (!RelationGetForm(relation)->relhasindex)
5269 411884 : return NULL;
5270 :
5271 : /*
5272 : * Get cached list of index OIDs. If we have to start over, we do so here.
5273 : */
5274 14300 : restart:
5275 14300 : indexoidlist = RelationGetIndexList(relation);
5276 :
5277 : /* Fall out if no indexes (but relhasindex was set) */
5278 14300 : if (indexoidlist == NIL)
5279 1134 : return NULL;
5280 :
5281 : /*
5282 : * Copy the rd_pkindex and rd_replidindex values computed by
5283 : * RelationGetIndexList before proceeding. This is needed because a
5284 : * relcache flush could occur inside index_open below, resetting the
5285 : * fields managed by RelationGetIndexList. We need to do the work with
5286 : * stable values of these fields.
5287 : */
5288 13166 : relpkindex = relation->rd_pkindex;
5289 13166 : relreplindex = relation->rd_replidindex;
5290 :
5291 : /*
5292 : * For each index, add referenced attributes to indexattrs.
5293 : *
5294 : * Note: we consider all indexes returned by RelationGetIndexList, even if
5295 : * they are not indisready or indisvalid. This is important because an
5296 : * index for which CREATE INDEX CONCURRENTLY has just started must be
5297 : * included in HOT-safety decisions (see README.HOT). If a DROP INDEX
5298 : * CONCURRENTLY is far enough along that we should ignore the index, it
5299 : * won't be returned at all by RelationGetIndexList.
5300 : */
5301 13166 : uindexattrs = NULL;
5302 13166 : pkindexattrs = NULL;
5303 13166 : idindexattrs = NULL;
5304 13166 : hotblockingattrs = NULL;
5305 13166 : summarizedattrs = NULL;
5306 37044 : foreach(l, indexoidlist)
5307 : {
5308 23878 : Oid indexOid = lfirst_oid(l);
5309 : Relation indexDesc;
5310 : Datum datum;
5311 : bool isnull;
5312 : Node *indexExpressions;
5313 : Node *indexPredicate;
5314 : int i;
5315 : bool isKey; /* candidate key */
5316 : bool isPK; /* primary key */
5317 : bool isIDKey; /* replica identity index */
5318 : Bitmapset **attrs;
5319 :
5320 23878 : indexDesc = index_open(indexOid, AccessShareLock);
5321 :
5322 : /*
5323 : * Extract index expressions and index predicate. Note: Don't use
5324 : * RelationGetIndexExpressions()/RelationGetIndexPredicate(), because
5325 : * those might run constant expressions evaluation, which needs a
5326 : * snapshot, which we might not have here. (Also, it's probably more
5327 : * sound to collect the bitmaps before any transformations that might
5328 : * eliminate columns, but the practical impact of this is limited.)
5329 : */
5330 :
5331 23878 : datum = heap_getattr(indexDesc->rd_indextuple, Anum_pg_index_indexprs,
5332 : GetPgIndexDescriptor(), &isnull);
5333 23878 : if (!isnull)
5334 32 : indexExpressions = stringToNode(TextDatumGetCString(datum));
5335 : else
5336 23846 : indexExpressions = NULL;
5337 :
5338 23878 : datum = heap_getattr(indexDesc->rd_indextuple, Anum_pg_index_indpred,
5339 : GetPgIndexDescriptor(), &isnull);
5340 23878 : if (!isnull)
5341 102 : indexPredicate = stringToNode(TextDatumGetCString(datum));
5342 : else
5343 23776 : indexPredicate = NULL;
5344 :
5345 : /* Can this index be referenced by a foreign key? */
5346 18910 : isKey = indexDesc->rd_index->indisunique &&
5347 42788 : indexExpressions == NULL &&
5348 : indexPredicate == NULL;
5349 :
5350 : /* Is this a primary key? */
5351 23878 : isPK = (indexOid == relpkindex);
5352 :
5353 : /* Is this index the configured (or default) replica identity? */
5354 23878 : isIDKey = (indexOid == relreplindex);
5355 :
5356 : /*
5357 : * If the index is summarizing, it doesn't block HOT updates, but we
5358 : * may still need to update it (if the attributes were modified). So
5359 : * decide which bitmap we'll update in the following loop.
5360 : */
5361 23878 : if (indexDesc->rd_indam->amsummarizing)
5362 56 : attrs = &summarizedattrs;
5363 : else
5364 23822 : attrs = &hotblockingattrs;
5365 :
5366 : /* Collect simple attribute references */
5367 61314 : for (i = 0; i < indexDesc->rd_index->indnatts; i++)
5368 : {
5369 37436 : int attrnum = indexDesc->rd_index->indkey.values[i];
5370 :
5371 : /*
5372 : * Since we have covering indexes with non-key columns, we must
5373 : * handle them accurately here. non-key columns must be added into
5374 : * hotblockingattrs or summarizedattrs, since they are in index,
5375 : * and update shouldn't miss them.
5376 : *
5377 : * Summarizing indexes do not block HOT, but do need to be updated
5378 : * when the column value changes, thus require a separate
5379 : * attribute bitmapset.
5380 : *
5381 : * Obviously, non-key columns couldn't be referenced by foreign
5382 : * key or identity key. Hence we do not include them into
5383 : * uindexattrs, pkindexattrs and idindexattrs bitmaps.
5384 : */
5385 37436 : if (attrnum != 0)
5386 : {
5387 37404 : *attrs = bms_add_member(*attrs,
5388 : attrnum - FirstLowInvalidHeapAttributeNumber);
5389 :
5390 37404 : if (isKey && i < indexDesc->rd_index->indnkeyatts)
5391 28144 : uindexattrs = bms_add_member(uindexattrs,
5392 : attrnum - FirstLowInvalidHeapAttributeNumber);
5393 :
5394 37404 : if (isPK && i < indexDesc->rd_index->indnkeyatts)
5395 14300 : pkindexattrs = bms_add_member(pkindexattrs,
5396 : attrnum - FirstLowInvalidHeapAttributeNumber);
5397 :
5398 37404 : if (isIDKey && i < indexDesc->rd_index->indnkeyatts)
5399 4186 : idindexattrs = bms_add_member(idindexattrs,
5400 : attrnum - FirstLowInvalidHeapAttributeNumber);
5401 : }
5402 : }
5403 :
5404 : /* Collect all attributes used in expressions, too */
5405 23878 : pull_varattnos(indexExpressions, 1, attrs);
5406 :
5407 : /* Collect all attributes in the index predicate, too */
5408 23878 : pull_varattnos(indexPredicate, 1, attrs);
5409 :
5410 23878 : index_close(indexDesc, AccessShareLock);
5411 : }
5412 :
5413 : /*
5414 : * During one of the index_opens in the above loop, we might have received
5415 : * a relcache flush event on this relcache entry, which might have been
5416 : * signaling a change in the rel's index list. If so, we'd better start
5417 : * over to ensure we deliver up-to-date attribute bitmaps.
5418 : */
5419 13166 : newindexoidlist = RelationGetIndexList(relation);
5420 13166 : if (equal(indexoidlist, newindexoidlist) &&
5421 13166 : relpkindex == relation->rd_pkindex &&
5422 13166 : relreplindex == relation->rd_replidindex)
5423 : {
5424 : /* Still the same index set, so proceed */
5425 13166 : list_free(newindexoidlist);
5426 13166 : list_free(indexoidlist);
5427 : }
5428 : else
5429 : {
5430 : /* Gotta do it over ... might as well not leak memory */
5431 0 : list_free(newindexoidlist);
5432 0 : list_free(indexoidlist);
5433 0 : bms_free(uindexattrs);
5434 0 : bms_free(pkindexattrs);
5435 0 : bms_free(idindexattrs);
5436 0 : bms_free(hotblockingattrs);
5437 0 : bms_free(summarizedattrs);
5438 :
5439 0 : goto restart;
5440 : }
5441 :
5442 : /* Don't leak the old values of these bitmaps, if any */
5443 13166 : relation->rd_attrsvalid = false;
5444 13166 : bms_free(relation->rd_keyattr);
5445 13166 : relation->rd_keyattr = NULL;
5446 13166 : bms_free(relation->rd_pkattr);
5447 13166 : relation->rd_pkattr = NULL;
5448 13166 : bms_free(relation->rd_idattr);
5449 13166 : relation->rd_idattr = NULL;
5450 13166 : bms_free(relation->rd_hotblockingattr);
5451 13166 : relation->rd_hotblockingattr = NULL;
5452 13166 : bms_free(relation->rd_summarizedattr);
5453 13166 : relation->rd_summarizedattr = NULL;
5454 :
5455 : /*
5456 : * Now save copies of the bitmaps in the relcache entry. We intentionally
5457 : * set rd_attrsvalid last, because that's the one that signals validity of
5458 : * the values; if we run out of memory before making that copy, we won't
5459 : * leave the relcache entry looking like the other ones are valid but
5460 : * empty.
5461 : */
5462 13166 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
5463 13166 : relation->rd_keyattr = bms_copy(uindexattrs);
5464 13166 : relation->rd_pkattr = bms_copy(pkindexattrs);
5465 13166 : relation->rd_idattr = bms_copy(idindexattrs);
5466 13166 : relation->rd_hotblockingattr = bms_copy(hotblockingattrs);
5467 13166 : relation->rd_summarizedattr = bms_copy(summarizedattrs);
5468 13166 : relation->rd_attrsvalid = true;
5469 13166 : MemoryContextSwitchTo(oldcxt);
5470 :
5471 : /* We return our original working copy for caller to play with */
5472 13166 : switch (attrKind)
5473 : {
5474 916 : case INDEX_ATTR_BITMAP_KEY:
5475 916 : return uindexattrs;
5476 48 : case INDEX_ATTR_BITMAP_PRIMARY_KEY:
5477 48 : return pkindexattrs;
5478 972 : case INDEX_ATTR_BITMAP_IDENTITY_KEY:
5479 972 : return idindexattrs;
5480 11230 : case INDEX_ATTR_BITMAP_HOT_BLOCKING:
5481 11230 : return hotblockingattrs;
5482 0 : case INDEX_ATTR_BITMAP_SUMMARIZED:
5483 0 : return summarizedattrs;
5484 0 : default:
5485 0 : elog(ERROR, "unknown attrKind %u", attrKind);
5486 : return NULL;
5487 : }
5488 : }
5489 :
5490 : /*
5491 : * RelationGetIdentityKeyBitmap -- get a bitmap of replica identity attribute
5492 : * numbers
5493 : *
5494 : * A bitmap of index attribute numbers for the configured replica identity
5495 : * index is returned.
5496 : *
5497 : * See also comments of RelationGetIndexAttrBitmap().
5498 : *
5499 : * This is a special purpose function used during logical replication. Here,
5500 : * unlike RelationGetIndexAttrBitmap(), we don't acquire a lock on the required
5501 : * index as we build the cache entry using a historic snapshot and all the
5502 : * later changes are absorbed while decoding WAL. Due to this reason, we don't
5503 : * need to retry here in case of a change in the set of indexes.
5504 : */
5505 : Bitmapset *
5506 572 : RelationGetIdentityKeyBitmap(Relation relation)
5507 : {
5508 572 : Bitmapset *idindexattrs = NULL; /* columns in the replica identity */
5509 : Relation indexDesc;
5510 : int i;
5511 : Oid replidindex;
5512 : MemoryContext oldcxt;
5513 :
5514 : /* Quick exit if we already computed the result */
5515 572 : if (relation->rd_idattr != NULL)
5516 96 : return bms_copy(relation->rd_idattr);
5517 :
5518 : /* Fast path if definitely no indexes */
5519 476 : if (!RelationGetForm(relation)->relhasindex)
5520 110 : return NULL;
5521 :
5522 : /* Historic snapshot must be set. */
5523 : Assert(HistoricSnapshotActive());
5524 :
5525 366 : replidindex = RelationGetReplicaIndex(relation);
5526 :
5527 : /* Fall out if there is no replica identity index */
5528 366 : if (!OidIsValid(replidindex))
5529 4 : return NULL;
5530 :
5531 : /* Look up the description for the replica identity index */
5532 362 : indexDesc = RelationIdGetRelation(replidindex);
5533 :
5534 362 : if (!RelationIsValid(indexDesc))
5535 0 : elog(ERROR, "could not open relation with OID %u",
5536 : relation->rd_replidindex);
5537 :
5538 : /* Add referenced attributes to idindexattrs */
5539 732 : for (i = 0; i < indexDesc->rd_index->indnatts; i++)
5540 : {
5541 370 : int attrnum = indexDesc->rd_index->indkey.values[i];
5542 :
5543 : /*
5544 : * We don't include non-key columns into idindexattrs bitmaps. See
5545 : * RelationGetIndexAttrBitmap.
5546 : */
5547 370 : if (attrnum != 0)
5548 : {
5549 370 : if (i < indexDesc->rd_index->indnkeyatts)
5550 368 : idindexattrs = bms_add_member(idindexattrs,
5551 : attrnum - FirstLowInvalidHeapAttributeNumber);
5552 : }
5553 : }
5554 :
5555 362 : RelationClose(indexDesc);
5556 :
5557 : /* Don't leak the old values of these bitmaps, if any */
5558 362 : bms_free(relation->rd_idattr);
5559 362 : relation->rd_idattr = NULL;
5560 :
5561 : /* Now save copy of the bitmap in the relcache entry */
5562 362 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
5563 362 : relation->rd_idattr = bms_copy(idindexattrs);
5564 362 : MemoryContextSwitchTo(oldcxt);
5565 :
5566 : /* We return our original working copy for caller to play with */
5567 362 : return idindexattrs;
5568 : }
5569 :
5570 : /*
5571 : * RelationGetExclusionInfo -- get info about index's exclusion constraint
5572 : *
5573 : * This should be called only for an index that is known to have an associated
5574 : * exclusion constraint or primary key/unique constraint using WITHOUT
5575 : * OVERLAPS.
5576 :
5577 : * It returns arrays (palloc'd in caller's context) of the exclusion operator
5578 : * OIDs, their underlying functions' OIDs, and their strategy numbers in the
5579 : * index's opclasses. We cache all this information since it requires a fair
5580 : * amount of work to get.
5581 : */
5582 : void
5583 2328 : RelationGetExclusionInfo(Relation indexRelation,
5584 : Oid **operators,
5585 : Oid **procs,
5586 : uint16 **strategies)
5587 : {
5588 : int indnkeyatts;
5589 : Oid *ops;
5590 : Oid *funcs;
5591 : uint16 *strats;
5592 : Relation conrel;
5593 : SysScanDesc conscan;
5594 : ScanKeyData skey[1];
5595 : HeapTuple htup;
5596 : bool found;
5597 : MemoryContext oldcxt;
5598 : int i;
5599 :
5600 2328 : indnkeyatts = IndexRelationGetNumberOfKeyAttributes(indexRelation);
5601 :
5602 : /* Allocate result space in caller context */
5603 2328 : *operators = ops = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
5604 2328 : *procs = funcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
5605 2328 : *strategies = strats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
5606 :
5607 : /* Quick exit if we have the data cached already */
5608 2328 : if (indexRelation->rd_exclstrats != NULL)
5609 : {
5610 1662 : memcpy(ops, indexRelation->rd_exclops, sizeof(Oid) * indnkeyatts);
5611 1662 : memcpy(funcs, indexRelation->rd_exclprocs, sizeof(Oid) * indnkeyatts);
5612 1662 : memcpy(strats, indexRelation->rd_exclstrats, sizeof(uint16) * indnkeyatts);
5613 1662 : return;
5614 : }
5615 :
5616 : /*
5617 : * Search pg_constraint for the constraint associated with the index. To
5618 : * make this not too painfully slow, we use the index on conrelid; that
5619 : * will hold the parent relation's OID not the index's own OID.
5620 : *
5621 : * Note: if we wanted to rely on the constraint name matching the index's
5622 : * name, we could just do a direct lookup using pg_constraint's unique
5623 : * index. For the moment it doesn't seem worth requiring that.
5624 : */
5625 666 : ScanKeyInit(&skey[0],
5626 : Anum_pg_constraint_conrelid,
5627 : BTEqualStrategyNumber, F_OIDEQ,
5628 666 : ObjectIdGetDatum(indexRelation->rd_index->indrelid));
5629 :
5630 666 : conrel = table_open(ConstraintRelationId, AccessShareLock);
5631 666 : conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
5632 : NULL, 1, skey);
5633 666 : found = false;
5634 :
5635 2764 : while (HeapTupleIsValid(htup = systable_getnext(conscan)))
5636 : {
5637 2098 : Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(htup);
5638 : Datum val;
5639 : bool isnull;
5640 : ArrayType *arr;
5641 : int nelem;
5642 :
5643 : /* We want the exclusion constraint owning the index */
5644 2098 : if ((conform->contype != CONSTRAINT_EXCLUSION &&
5645 1868 : !(conform->conperiod && (conform->contype == CONSTRAINT_PRIMARY
5646 266 : || conform->contype == CONSTRAINT_UNIQUE))) ||
5647 798 : conform->conindid != RelationGetRelid(indexRelation))
5648 1432 : continue;
5649 :
5650 : /* There should be only one */
5651 666 : if (found)
5652 0 : elog(ERROR, "unexpected exclusion constraint record found for rel %s",
5653 : RelationGetRelationName(indexRelation));
5654 666 : found = true;
5655 :
5656 : /* Extract the operator OIDS from conexclop */
5657 666 : val = fastgetattr(htup,
5658 : Anum_pg_constraint_conexclop,
5659 : conrel->rd_att, &isnull);
5660 666 : if (isnull)
5661 0 : elog(ERROR, "null conexclop for rel %s",
5662 : RelationGetRelationName(indexRelation));
5663 :
5664 666 : arr = DatumGetArrayTypeP(val); /* ensure not toasted */
5665 666 : nelem = ARR_DIMS(arr)[0];
5666 666 : if (ARR_NDIM(arr) != 1 ||
5667 666 : nelem != indnkeyatts ||
5668 666 : ARR_HASNULL(arr) ||
5669 666 : ARR_ELEMTYPE(arr) != OIDOID)
5670 0 : elog(ERROR, "conexclop is not a 1-D Oid array");
5671 :
5672 666 : memcpy(ops, ARR_DATA_PTR(arr), sizeof(Oid) * indnkeyatts);
5673 : }
5674 :
5675 666 : systable_endscan(conscan);
5676 666 : table_close(conrel, AccessShareLock);
5677 :
5678 666 : if (!found)
5679 0 : elog(ERROR, "exclusion constraint record missing for rel %s",
5680 : RelationGetRelationName(indexRelation));
5681 :
5682 : /* We need the func OIDs and strategy numbers too */
5683 1912 : for (i = 0; i < indnkeyatts; i++)
5684 : {
5685 1246 : funcs[i] = get_opcode(ops[i]);
5686 2492 : strats[i] = get_op_opfamily_strategy(ops[i],
5687 1246 : indexRelation->rd_opfamily[i]);
5688 : /* shouldn't fail, since it was checked at index creation */
5689 1246 : if (strats[i] == InvalidStrategy)
5690 0 : elog(ERROR, "could not find strategy for operator %u in family %u",
5691 : ops[i], indexRelation->rd_opfamily[i]);
5692 : }
5693 :
5694 : /* Save a copy of the results in the relcache entry. */
5695 666 : oldcxt = MemoryContextSwitchTo(indexRelation->rd_indexcxt);
5696 666 : indexRelation->rd_exclops = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
5697 666 : indexRelation->rd_exclprocs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
5698 666 : indexRelation->rd_exclstrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
5699 666 : memcpy(indexRelation->rd_exclops, ops, sizeof(Oid) * indnkeyatts);
5700 666 : memcpy(indexRelation->rd_exclprocs, funcs, sizeof(Oid) * indnkeyatts);
5701 666 : memcpy(indexRelation->rd_exclstrats, strats, sizeof(uint16) * indnkeyatts);
5702 666 : MemoryContextSwitchTo(oldcxt);
5703 : }
5704 :
5705 : /*
5706 : * Get the publication information for the given relation.
5707 : *
5708 : * Traverse all the publications which the relation is in to get the
5709 : * publication actions and validate the row filter expressions for such
5710 : * publications if any. We consider the row filter expression as invalid if it
5711 : * references any column which is not part of REPLICA IDENTITY.
5712 : *
5713 : * To avoid fetching the publication information repeatedly, we cache the
5714 : * publication actions and row filter validation information.
5715 : */
5716 : void
5717 171648 : RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc)
5718 : {
5719 : List *puboids;
5720 : ListCell *lc;
5721 : MemoryContext oldcxt;
5722 : Oid schemaid;
5723 171648 : List *ancestors = NIL;
5724 171648 : Oid relid = RelationGetRelid(relation);
5725 :
5726 : /*
5727 : * If not publishable, it publishes no actions. (pgoutput_change() will
5728 : * ignore it.)
5729 : */
5730 171648 : if (!is_publishable_relation(relation))
5731 : {
5732 5184 : memset(pubdesc, 0, sizeof(PublicationDesc));
5733 5184 : pubdesc->rf_valid_for_update = true;
5734 5184 : pubdesc->rf_valid_for_delete = true;
5735 5184 : pubdesc->cols_valid_for_update = true;
5736 5184 : pubdesc->cols_valid_for_delete = true;
5737 5184 : return;
5738 : }
5739 :
5740 166464 : if (relation->rd_pubdesc)
5741 : {
5742 158580 : memcpy(pubdesc, relation->rd_pubdesc, sizeof(PublicationDesc));
5743 158580 : return;
5744 : }
5745 :
5746 7884 : memset(pubdesc, 0, sizeof(PublicationDesc));
5747 7884 : pubdesc->rf_valid_for_update = true;
5748 7884 : pubdesc->rf_valid_for_delete = true;
5749 7884 : pubdesc->cols_valid_for_update = true;
5750 7884 : pubdesc->cols_valid_for_delete = true;
5751 :
5752 : /* Fetch the publication membership info. */
5753 7884 : puboids = GetRelationPublications(relid);
5754 7884 : schemaid = RelationGetNamespace(relation);
5755 7884 : puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid));
5756 :
5757 7884 : if (relation->rd_rel->relispartition)
5758 : {
5759 : /* Add publications that the ancestors are in too. */
5760 1840 : ancestors = get_partition_ancestors(relid);
5761 :
5762 4312 : foreach(lc, ancestors)
5763 : {
5764 2472 : Oid ancestor = lfirst_oid(lc);
5765 :
5766 2472 : puboids = list_concat_unique_oid(puboids,
5767 2472 : GetRelationPublications(ancestor));
5768 2472 : schemaid = get_rel_namespace(ancestor);
5769 2472 : puboids = list_concat_unique_oid(puboids,
5770 2472 : GetSchemaPublications(schemaid));
5771 : }
5772 : }
5773 7884 : puboids = list_concat_unique_oid(puboids, GetAllTablesPublications());
5774 :
5775 8550 : foreach(lc, puboids)
5776 : {
5777 834 : Oid pubid = lfirst_oid(lc);
5778 : HeapTuple tup;
5779 : Form_pg_publication pubform;
5780 :
5781 834 : tup = SearchSysCache1(PUBLICATIONOID, ObjectIdGetDatum(pubid));
5782 :
5783 834 : if (!HeapTupleIsValid(tup))
5784 0 : elog(ERROR, "cache lookup failed for publication %u", pubid);
5785 :
5786 834 : pubform = (Form_pg_publication) GETSTRUCT(tup);
5787 :
5788 834 : pubdesc->pubactions.pubinsert |= pubform->pubinsert;
5789 834 : pubdesc->pubactions.pubupdate |= pubform->pubupdate;
5790 834 : pubdesc->pubactions.pubdelete |= pubform->pubdelete;
5791 834 : pubdesc->pubactions.pubtruncate |= pubform->pubtruncate;
5792 :
5793 : /*
5794 : * Check if all columns referenced in the filter expression are part
5795 : * of the REPLICA IDENTITY index or not.
5796 : *
5797 : * If the publication is FOR ALL TABLES then it means the table has no
5798 : * row filters and we can skip the validation.
5799 : */
5800 834 : if (!pubform->puballtables &&
5801 1368 : (pubform->pubupdate || pubform->pubdelete) &&
5802 682 : pub_rf_contains_invalid_column(pubid, relation, ancestors,
5803 682 : pubform->pubviaroot))
5804 : {
5805 60 : if (pubform->pubupdate)
5806 60 : pubdesc->rf_valid_for_update = false;
5807 60 : if (pubform->pubdelete)
5808 60 : pubdesc->rf_valid_for_delete = false;
5809 : }
5810 :
5811 : /*
5812 : * Check if all columns are part of the REPLICA IDENTITY index or not.
5813 : *
5814 : * If the publication is FOR ALL TABLES then it means the table has no
5815 : * column list and we can skip the validation.
5816 : */
5817 834 : if (!pubform->puballtables &&
5818 1368 : (pubform->pubupdate || pubform->pubdelete) &&
5819 682 : pub_collist_contains_invalid_column(pubid, relation, ancestors,
5820 682 : pubform->pubviaroot))
5821 : {
5822 108 : if (pubform->pubupdate)
5823 108 : pubdesc->cols_valid_for_update = false;
5824 108 : if (pubform->pubdelete)
5825 108 : pubdesc->cols_valid_for_delete = false;
5826 : }
5827 :
5828 834 : ReleaseSysCache(tup);
5829 :
5830 : /*
5831 : * If we know everything is replicated and the row filter is invalid
5832 : * for update and delete, there is no point to check for other
5833 : * publications.
5834 : */
5835 834 : if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5836 828 : pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5837 816 : !pubdesc->rf_valid_for_update && !pubdesc->rf_valid_for_delete)
5838 60 : break;
5839 :
5840 : /*
5841 : * If we know everything is replicated and the column list is invalid
5842 : * for update and delete, there is no point to check for other
5843 : * publications.
5844 : */
5845 774 : if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5846 768 : pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5847 756 : !pubdesc->cols_valid_for_update && !pubdesc->cols_valid_for_delete)
5848 108 : break;
5849 : }
5850 :
5851 7884 : if (relation->rd_pubdesc)
5852 : {
5853 0 : pfree(relation->rd_pubdesc);
5854 0 : relation->rd_pubdesc = NULL;
5855 : }
5856 :
5857 : /* Now save copy of the descriptor in the relcache entry. */
5858 7884 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
5859 7884 : relation->rd_pubdesc = palloc(sizeof(PublicationDesc));
5860 7884 : memcpy(relation->rd_pubdesc, pubdesc, sizeof(PublicationDesc));
5861 7884 : MemoryContextSwitchTo(oldcxt);
5862 : }
5863 :
5864 : static bytea **
5865 1173612 : CopyIndexAttOptions(bytea **srcopts, int natts)
5866 : {
5867 1173612 : bytea **opts = palloc(sizeof(*opts) * natts);
5868 :
5869 3318420 : for (int i = 0; i < natts; i++)
5870 : {
5871 2144808 : bytea *opt = srcopts[i];
5872 :
5873 2236474 : opts[i] = !opt ? NULL : (bytea *)
5874 91666 : DatumGetPointer(datumCopy(PointerGetDatum(opt), false, -1));
5875 : }
5876 :
5877 1173612 : return opts;
5878 : }
5879 :
5880 : /*
5881 : * RelationGetIndexAttOptions
5882 : * get AM/opclass-specific options for an index parsed into a binary form
5883 : */
5884 : bytea **
5885 2200056 : RelationGetIndexAttOptions(Relation relation, bool copy)
5886 : {
5887 : MemoryContext oldcxt;
5888 2200056 : bytea **opts = relation->rd_opcoptions;
5889 2200056 : Oid relid = RelationGetRelid(relation);
5890 2200056 : int natts = RelationGetNumberOfAttributes(relation); /* XXX
5891 : * IndexRelationGetNumberOfKeyAttributes */
5892 : int i;
5893 :
5894 : /* Try to copy cached options. */
5895 2200056 : if (opts)
5896 1666090 : return copy ? CopyIndexAttOptions(opts, natts) : opts;
5897 :
5898 : /* Get and parse opclass options. */
5899 533966 : opts = palloc0(sizeof(*opts) * natts);
5900 :
5901 1437460 : for (i = 0; i < natts; i++)
5902 : {
5903 903500 : if (criticalRelcachesBuilt && relid != AttributeRelidNumIndexId)
5904 : {
5905 845580 : Datum attoptions = get_attoptions(relid, i + 1);
5906 :
5907 845580 : opts[i] = index_opclass_options(relation, i + 1, attoptions, false);
5908 :
5909 845574 : if (attoptions != (Datum) 0)
5910 292 : pfree(DatumGetPointer(attoptions));
5911 : }
5912 : }
5913 :
5914 : /* Copy parsed options to the cache. */
5915 533960 : oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
5916 533960 : relation->rd_opcoptions = CopyIndexAttOptions(opts, natts);
5917 533960 : MemoryContextSwitchTo(oldcxt);
5918 :
5919 533960 : if (copy)
5920 0 : return opts;
5921 :
5922 1437454 : for (i = 0; i < natts; i++)
5923 : {
5924 903494 : if (opts[i])
5925 1678 : pfree(opts[i]);
5926 : }
5927 :
5928 533960 : pfree(opts);
5929 :
5930 533960 : return relation->rd_opcoptions;
5931 : }
5932 :
5933 : /*
5934 : * Routines to support ereport() reports of relation-related errors
5935 : *
5936 : * These could have been put into elog.c, but it seems like a module layering
5937 : * violation to have elog.c calling relcache or syscache stuff --- and we
5938 : * definitely don't want elog.h including rel.h. So we put them here.
5939 : */
5940 :
5941 : /*
5942 : * errtable --- stores schema_name and table_name of a table
5943 : * within the current errordata.
5944 : */
5945 : int
5946 3368 : errtable(Relation rel)
5947 : {
5948 3368 : err_generic_string(PG_DIAG_SCHEMA_NAME,
5949 3368 : get_namespace_name(RelationGetNamespace(rel)));
5950 3368 : err_generic_string(PG_DIAG_TABLE_NAME, RelationGetRelationName(rel));
5951 :
5952 3368 : return 0; /* return value does not matter */
5953 : }
5954 :
5955 : /*
5956 : * errtablecol --- stores schema_name, table_name and column_name
5957 : * of a table column within the current errordata.
5958 : *
5959 : * The column is specified by attribute number --- for most callers, this is
5960 : * easier and less error-prone than getting the column name for themselves.
5961 : */
5962 : int
5963 428 : errtablecol(Relation rel, int attnum)
5964 : {
5965 428 : TupleDesc reldesc = RelationGetDescr(rel);
5966 : const char *colname;
5967 :
5968 : /* Use reldesc if it's a user attribute, else consult the catalogs */
5969 428 : if (attnum > 0 && attnum <= reldesc->natts)
5970 428 : colname = NameStr(TupleDescAttr(reldesc, attnum - 1)->attname);
5971 : else
5972 0 : colname = get_attname(RelationGetRelid(rel), attnum, false);
5973 :
5974 428 : return errtablecolname(rel, colname);
5975 : }
5976 :
5977 : /*
5978 : * errtablecolname --- stores schema_name, table_name and column_name
5979 : * of a table column within the current errordata, where the column name is
5980 : * given directly rather than extracted from the relation's catalog data.
5981 : *
5982 : * Don't use this directly unless errtablecol() is inconvenient for some
5983 : * reason. This might possibly be needed during intermediate states in ALTER
5984 : * TABLE, for instance.
5985 : */
5986 : int
5987 428 : errtablecolname(Relation rel, const char *colname)
5988 : {
5989 428 : errtable(rel);
5990 428 : err_generic_string(PG_DIAG_COLUMN_NAME, colname);
5991 :
5992 428 : return 0; /* return value does not matter */
5993 : }
5994 :
5995 : /*
5996 : * errtableconstraint --- stores schema_name, table_name and constraint_name
5997 : * of a table-related constraint within the current errordata.
5998 : */
5999 : int
6000 2432 : errtableconstraint(Relation rel, const char *conname)
6001 : {
6002 2432 : errtable(rel);
6003 2432 : err_generic_string(PG_DIAG_CONSTRAINT_NAME, conname);
6004 :
6005 2432 : return 0; /* return value does not matter */
6006 : }
6007 :
6008 :
6009 : /*
6010 : * load_relcache_init_file, write_relcache_init_file
6011 : *
6012 : * In late 1992, we started regularly having databases with more than
6013 : * a thousand classes in them. With this number of classes, it became
6014 : * critical to do indexed lookups on the system catalogs.
6015 : *
6016 : * Bootstrapping these lookups is very hard. We want to be able to
6017 : * use an index on pg_attribute, for example, but in order to do so,
6018 : * we must have read pg_attribute for the attributes in the index,
6019 : * which implies that we need to use the index.
6020 : *
6021 : * In order to get around the problem, we do the following:
6022 : *
6023 : * + When the database system is initialized (at initdb time), we
6024 : * don't use indexes. We do sequential scans.
6025 : *
6026 : * + When the backend is started up in normal mode, we load an image
6027 : * of the appropriate relation descriptors, in internal format,
6028 : * from an initialization file in the data/base/... directory.
6029 : *
6030 : * + If the initialization file isn't there, then we create the
6031 : * relation descriptors using sequential scans and write 'em to
6032 : * the initialization file for use by subsequent backends.
6033 : *
6034 : * As of Postgres 9.0, there is one local initialization file in each
6035 : * database, plus one shared initialization file for shared catalogs.
6036 : *
6037 : * We could dispense with the initialization files and just build the
6038 : * critical reldescs the hard way on every backend startup, but that
6039 : * slows down backend startup noticeably.
6040 : *
6041 : * We can in fact go further, and save more relcache entries than
6042 : * just the ones that are absolutely critical; this allows us to speed
6043 : * up backend startup by not having to build such entries the hard way.
6044 : * Presently, all the catalog and index entries that are referred to
6045 : * by catcaches are stored in the initialization files.
6046 : *
6047 : * The same mechanism that detects when catcache and relcache entries
6048 : * need to be invalidated (due to catalog updates) also arranges to
6049 : * unlink the initialization files when the contents may be out of date.
6050 : * The files will then be rebuilt during the next backend startup.
6051 : */
6052 :
6053 : /*
6054 : * load_relcache_init_file -- attempt to load cache from the shared
6055 : * or local cache init file
6056 : *
6057 : * If successful, return true and set criticalRelcachesBuilt or
6058 : * criticalSharedRelcachesBuilt to true.
6059 : * If not successful, return false.
6060 : *
6061 : * NOTE: we assume we are already switched into CacheMemoryContext.
6062 : */
6063 : static bool
6064 54382 : load_relcache_init_file(bool shared)
6065 : {
6066 : FILE *fp;
6067 : char initfilename[MAXPGPATH];
6068 : Relation *rels;
6069 : int relno,
6070 : num_rels,
6071 : max_rels,
6072 : nailed_rels,
6073 : nailed_indexes,
6074 : magic;
6075 : int i;
6076 :
6077 54382 : if (shared)
6078 28440 : snprintf(initfilename, sizeof(initfilename), "global/%s",
6079 : RELCACHE_INIT_FILENAME);
6080 : else
6081 25942 : snprintf(initfilename, sizeof(initfilename), "%s/%s",
6082 : DatabasePath, RELCACHE_INIT_FILENAME);
6083 :
6084 54382 : fp = AllocateFile(initfilename, PG_BINARY_R);
6085 54382 : if (fp == NULL)
6086 6290 : return false;
6087 :
6088 : /*
6089 : * Read the index relcache entries from the file. Note we will not enter
6090 : * any of them into the cache if the read fails partway through; this
6091 : * helps to guard against broken init files.
6092 : */
6093 48092 : max_rels = 100;
6094 48092 : rels = (Relation *) palloc(max_rels * sizeof(Relation));
6095 48092 : num_rels = 0;
6096 48092 : nailed_rels = nailed_indexes = 0;
6097 :
6098 : /* check for correct magic number (compatible version) */
6099 48092 : if (fread(&magic, 1, sizeof(magic), fp) != sizeof(magic))
6100 0 : goto read_failed;
6101 48092 : if (magic != RELCACHE_INIT_FILEMAGIC)
6102 0 : goto read_failed;
6103 :
6104 48092 : for (relno = 0;; relno++)
6105 3234410 : {
6106 : Size len;
6107 : size_t nread;
6108 : Relation rel;
6109 : Form_pg_class relform;
6110 : bool has_not_null;
6111 :
6112 : /* first read the relation descriptor length */
6113 3282502 : nread = fread(&len, 1, sizeof(len), fp);
6114 3282502 : if (nread != sizeof(len))
6115 : {
6116 48092 : if (nread == 0)
6117 48092 : break; /* end of file */
6118 0 : goto read_failed;
6119 : }
6120 :
6121 : /* safety check for incompatible relcache layout */
6122 3234410 : if (len != sizeof(RelationData))
6123 0 : goto read_failed;
6124 :
6125 : /* allocate another relcache header */
6126 3234410 : if (num_rels >= max_rels)
6127 : {
6128 23402 : max_rels *= 2;
6129 23402 : rels = (Relation *) repalloc(rels, max_rels * sizeof(Relation));
6130 : }
6131 :
6132 3234410 : rel = rels[num_rels++] = (Relation) palloc(len);
6133 :
6134 : /* then, read the Relation structure */
6135 3234410 : if (fread(rel, 1, len, fp) != len)
6136 0 : goto read_failed;
6137 :
6138 : /* next read the relation tuple form */
6139 3234410 : if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
6140 0 : goto read_failed;
6141 :
6142 3234410 : relform = (Form_pg_class) palloc(len);
6143 3234410 : if (fread(relform, 1, len, fp) != len)
6144 0 : goto read_failed;
6145 :
6146 3234410 : rel->rd_rel = relform;
6147 :
6148 : /* initialize attribute tuple forms */
6149 3234410 : rel->rd_att = CreateTemplateTupleDesc(relform->relnatts);
6150 3234410 : rel->rd_att->tdrefcount = 1; /* mark as refcounted */
6151 :
6152 3234410 : rel->rd_att->tdtypeid = relform->reltype ? relform->reltype : RECORDOID;
6153 3234410 : rel->rd_att->tdtypmod = -1; /* just to be sure */
6154 :
6155 : /* next read all the attribute tuple form data entries */
6156 3234410 : has_not_null = false;
6157 18936062 : for (i = 0; i < relform->relnatts; i++)
6158 : {
6159 15701652 : Form_pg_attribute attr = TupleDescAttr(rel->rd_att, i);
6160 :
6161 15701652 : if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
6162 0 : goto read_failed;
6163 15701652 : if (len != ATTRIBUTE_FIXED_PART_SIZE)
6164 0 : goto read_failed;
6165 15701652 : if (fread(attr, 1, len, fp) != len)
6166 0 : goto read_failed;
6167 :
6168 15701652 : has_not_null |= attr->attnotnull;
6169 : }
6170 :
6171 : /* next read the access method specific field */
6172 3234410 : if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
6173 0 : goto read_failed;
6174 3234410 : if (len > 0)
6175 : {
6176 0 : rel->rd_options = palloc(len);
6177 0 : if (fread(rel->rd_options, 1, len, fp) != len)
6178 0 : goto read_failed;
6179 0 : if (len != VARSIZE(rel->rd_options))
6180 0 : goto read_failed; /* sanity check */
6181 : }
6182 : else
6183 : {
6184 3234410 : rel->rd_options = NULL;
6185 : }
6186 :
6187 : /* mark not-null status */
6188 3234410 : if (has_not_null)
6189 : {
6190 1203806 : TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
6191 :
6192 1203806 : constr->has_not_null = true;
6193 1203806 : rel->rd_att->constr = constr;
6194 : }
6195 :
6196 : /*
6197 : * If it's an index, there's more to do. Note we explicitly ignore
6198 : * partitioned indexes here.
6199 : */
6200 3234410 : if (rel->rd_rel->relkind == RELKIND_INDEX)
6201 : {
6202 : MemoryContext indexcxt;
6203 : Oid *opfamily;
6204 : Oid *opcintype;
6205 : RegProcedure *support;
6206 : int nsupport;
6207 : int16 *indoption;
6208 : Oid *indcollation;
6209 :
6210 : /* Count nailed indexes to ensure we have 'em all */
6211 2030604 : if (rel->rd_isnailed)
6212 311954 : nailed_indexes++;
6213 :
6214 : /* read the pg_index tuple */
6215 2030604 : if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
6216 0 : goto read_failed;
6217 :
6218 2030604 : rel->rd_indextuple = (HeapTuple) palloc(len);
6219 2030604 : if (fread(rel->rd_indextuple, 1, len, fp) != len)
6220 0 : goto read_failed;
6221 :
6222 : /* Fix up internal pointers in the tuple -- see heap_copytuple */
6223 2030604 : rel->rd_indextuple->t_data = (HeapTupleHeader) ((char *) rel->rd_indextuple + HEAPTUPLESIZE);
6224 2030604 : rel->rd_index = (Form_pg_index) GETSTRUCT(rel->rd_indextuple);
6225 :
6226 : /*
6227 : * prepare index info context --- parameters should match
6228 : * RelationInitIndexAccessInfo
6229 : */
6230 2030604 : indexcxt = AllocSetContextCreate(CacheMemoryContext,
6231 : "index info",
6232 : ALLOCSET_SMALL_SIZES);
6233 2030604 : rel->rd_indexcxt = indexcxt;
6234 2030604 : MemoryContextCopyAndSetIdentifier(indexcxt,
6235 : RelationGetRelationName(rel));
6236 :
6237 : /*
6238 : * Now we can fetch the index AM's API struct. (We can't store
6239 : * that in the init file, since it contains function pointers that
6240 : * might vary across server executions. Fortunately, it should be
6241 : * safe to call the amhandler even while bootstrapping indexes.)
6242 : */
6243 2030604 : InitIndexAmRoutine(rel);
6244 :
6245 : /* read the vector of opfamily OIDs */
6246 2030604 : if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
6247 0 : goto read_failed;
6248 :
6249 2030604 : opfamily = (Oid *) MemoryContextAlloc(indexcxt, len);
6250 2030604 : if (fread(opfamily, 1, len, fp) != len)
6251 0 : goto read_failed;
6252 :
6253 2030604 : rel->rd_opfamily = opfamily;
6254 :
6255 : /* read the vector of opcintype OIDs */
6256 2030604 : if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
6257 0 : goto read_failed;
6258 :
6259 2030604 : opcintype = (Oid *) MemoryContextAlloc(indexcxt, len);
6260 2030604 : if (fread(opcintype, 1, len, fp) != len)
6261 0 : goto read_failed;
6262 :
6263 2030604 : rel->rd_opcintype = opcintype;
6264 :
6265 : /* read the vector of support procedure OIDs */
6266 2030604 : if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
6267 0 : goto read_failed;
6268 2030604 : support = (RegProcedure *) MemoryContextAlloc(indexcxt, len);
6269 2030604 : if (fread(support, 1, len, fp) != len)
6270 0 : goto read_failed;
6271 :
6272 2030604 : rel->rd_support = support;
6273 :
6274 : /* read the vector of collation OIDs */
6275 2030604 : if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
6276 0 : goto read_failed;
6277 :
6278 2030604 : indcollation = (Oid *) MemoryContextAlloc(indexcxt, len);
6279 2030604 : if (fread(indcollation, 1, len, fp) != len)
6280 0 : goto read_failed;
6281 :
6282 2030604 : rel->rd_indcollation = indcollation;
6283 :
6284 : /* read the vector of indoption values */
6285 2030604 : if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
6286 0 : goto read_failed;
6287 :
6288 2030604 : indoption = (int16 *) MemoryContextAlloc(indexcxt, len);
6289 2030604 : if (fread(indoption, 1, len, fp) != len)
6290 0 : goto read_failed;
6291 :
6292 2030604 : rel->rd_indoption = indoption;
6293 :
6294 : /* read the vector of opcoptions values */
6295 2030604 : rel->rd_opcoptions = (bytea **)
6296 2030604 : MemoryContextAllocZero(indexcxt, sizeof(*rel->rd_opcoptions) * relform->relnatts);
6297 :
6298 5357334 : for (i = 0; i < relform->relnatts; i++)
6299 : {
6300 3326730 : if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
6301 0 : goto read_failed;
6302 :
6303 3326730 : if (len > 0)
6304 : {
6305 0 : rel->rd_opcoptions[i] = (bytea *) MemoryContextAlloc(indexcxt, len);
6306 0 : if (fread(rel->rd_opcoptions[i], 1, len, fp) != len)
6307 0 : goto read_failed;
6308 : }
6309 : }
6310 :
6311 : /* set up zeroed fmgr-info vector */
6312 2030604 : nsupport = relform->relnatts * rel->rd_indam->amsupport;
6313 2030604 : rel->rd_supportinfo = (FmgrInfo *)
6314 2030604 : MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
6315 : }
6316 : else
6317 : {
6318 : /* Count nailed rels to ensure we have 'em all */
6319 1203806 : if (rel->rd_isnailed)
6320 217058 : nailed_rels++;
6321 :
6322 : /* Load table AM data */
6323 1203806 : if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind) || rel->rd_rel->relkind == RELKIND_SEQUENCE)
6324 1203806 : RelationInitTableAccessMethod(rel);
6325 :
6326 : Assert(rel->rd_index == NULL);
6327 : Assert(rel->rd_indextuple == NULL);
6328 : Assert(rel->rd_indexcxt == NULL);
6329 : Assert(rel->rd_indam == NULL);
6330 : Assert(rel->rd_opfamily == NULL);
6331 : Assert(rel->rd_opcintype == NULL);
6332 : Assert(rel->rd_support == NULL);
6333 : Assert(rel->rd_supportinfo == NULL);
6334 : Assert(rel->rd_indoption == NULL);
6335 : Assert(rel->rd_indcollation == NULL);
6336 : Assert(rel->rd_opcoptions == NULL);
6337 : }
6338 :
6339 : /*
6340 : * Rules and triggers are not saved (mainly because the internal
6341 : * format is complex and subject to change). They must be rebuilt if
6342 : * needed by RelationCacheInitializePhase3. This is not expected to
6343 : * be a big performance hit since few system catalogs have such. Ditto
6344 : * for RLS policy data, partition info, index expressions, predicates,
6345 : * exclusion info, and FDW info.
6346 : */
6347 3234410 : rel->rd_rules = NULL;
6348 3234410 : rel->rd_rulescxt = NULL;
6349 3234410 : rel->trigdesc = NULL;
6350 3234410 : rel->rd_rsdesc = NULL;
6351 3234410 : rel->rd_partkey = NULL;
6352 3234410 : rel->rd_partkeycxt = NULL;
6353 3234410 : rel->rd_partdesc = NULL;
6354 3234410 : rel->rd_partdesc_nodetached = NULL;
6355 3234410 : rel->rd_partdesc_nodetached_xmin = InvalidTransactionId;
6356 3234410 : rel->rd_pdcxt = NULL;
6357 3234410 : rel->rd_pddcxt = NULL;
6358 3234410 : rel->rd_partcheck = NIL;
6359 3234410 : rel->rd_partcheckvalid = false;
6360 3234410 : rel->rd_partcheckcxt = NULL;
6361 3234410 : rel->rd_indexprs = NIL;
6362 3234410 : rel->rd_indpred = NIL;
6363 3234410 : rel->rd_exclops = NULL;
6364 3234410 : rel->rd_exclprocs = NULL;
6365 3234410 : rel->rd_exclstrats = NULL;
6366 3234410 : rel->rd_fdwroutine = NULL;
6367 :
6368 : /*
6369 : * Reset transient-state fields in the relcache entry
6370 : */
6371 3234410 : rel->rd_smgr = NULL;
6372 3234410 : if (rel->rd_isnailed)
6373 529012 : rel->rd_refcnt = 1;
6374 : else
6375 2705398 : rel->rd_refcnt = 0;
6376 3234410 : rel->rd_indexvalid = false;
6377 3234410 : rel->rd_indexlist = NIL;
6378 3234410 : rel->rd_pkindex = InvalidOid;
6379 3234410 : rel->rd_replidindex = InvalidOid;
6380 3234410 : rel->rd_attrsvalid = false;
6381 3234410 : rel->rd_keyattr = NULL;
6382 3234410 : rel->rd_pkattr = NULL;
6383 3234410 : rel->rd_idattr = NULL;
6384 3234410 : rel->rd_pubdesc = NULL;
6385 3234410 : rel->rd_statvalid = false;
6386 3234410 : rel->rd_statlist = NIL;
6387 3234410 : rel->rd_fkeyvalid = false;
6388 3234410 : rel->rd_fkeylist = NIL;
6389 3234410 : rel->rd_createSubid = InvalidSubTransactionId;
6390 3234410 : rel->rd_newRelfilelocatorSubid = InvalidSubTransactionId;
6391 3234410 : rel->rd_firstRelfilelocatorSubid = InvalidSubTransactionId;
6392 3234410 : rel->rd_droppedSubid = InvalidSubTransactionId;
6393 3234410 : rel->rd_amcache = NULL;
6394 3234410 : rel->pgstat_info = NULL;
6395 :
6396 : /*
6397 : * Recompute lock and physical addressing info. This is needed in
6398 : * case the pg_internal.init file was copied from some other database
6399 : * by CREATE DATABASE.
6400 : */
6401 3234410 : RelationInitLockInfo(rel);
6402 3234410 : RelationInitPhysicalAddr(rel);
6403 : }
6404 :
6405 : /*
6406 : * We reached the end of the init file without apparent problem. Did we
6407 : * get the right number of nailed items? This is a useful crosscheck in
6408 : * case the set of critical rels or indexes changes. However, that should
6409 : * not happen in a normally-running system, so let's bleat if it does.
6410 : *
6411 : * For the shared init file, we're called before client authentication is
6412 : * done, which means that elog(WARNING) will go only to the postmaster
6413 : * log, where it's easily missed. To ensure that developers notice bad
6414 : * values of NUM_CRITICAL_SHARED_RELS/NUM_CRITICAL_SHARED_INDEXES, we put
6415 : * an Assert(false) there.
6416 : */
6417 48092 : if (shared)
6418 : {
6419 24690 : if (nailed_rels != NUM_CRITICAL_SHARED_RELS ||
6420 : nailed_indexes != NUM_CRITICAL_SHARED_INDEXES)
6421 : {
6422 0 : elog(WARNING, "found %d nailed shared rels and %d nailed shared indexes in init file, but expected %d and %d respectively",
6423 : nailed_rels, nailed_indexes,
6424 : NUM_CRITICAL_SHARED_RELS, NUM_CRITICAL_SHARED_INDEXES);
6425 : /* Make sure we get developers' attention about this */
6426 : Assert(false);
6427 : /* In production builds, recover by bootstrapping the relcache */
6428 0 : goto read_failed;
6429 : }
6430 : }
6431 : else
6432 : {
6433 23402 : if (nailed_rels != NUM_CRITICAL_LOCAL_RELS ||
6434 : nailed_indexes != NUM_CRITICAL_LOCAL_INDEXES)
6435 : {
6436 0 : elog(WARNING, "found %d nailed rels and %d nailed indexes in init file, but expected %d and %d respectively",
6437 : nailed_rels, nailed_indexes,
6438 : NUM_CRITICAL_LOCAL_RELS, NUM_CRITICAL_LOCAL_INDEXES);
6439 : /* We don't need an Assert() in this case */
6440 0 : goto read_failed;
6441 : }
6442 : }
6443 :
6444 : /*
6445 : * OK, all appears well.
6446 : *
6447 : * Now insert all the new relcache entries into the cache.
6448 : */
6449 3282502 : for (relno = 0; relno < num_rels; relno++)
6450 : {
6451 3234410 : RelationCacheInsert(rels[relno], false);
6452 : }
6453 :
6454 48092 : pfree(rels);
6455 48092 : FreeFile(fp);
6456 :
6457 48092 : if (shared)
6458 24690 : criticalSharedRelcachesBuilt = true;
6459 : else
6460 23402 : criticalRelcachesBuilt = true;
6461 48092 : return true;
6462 :
6463 : /*
6464 : * init file is broken, so do it the hard way. We don't bother trying to
6465 : * free the clutter we just allocated; it's not in the relcache so it
6466 : * won't hurt.
6467 : */
6468 0 : read_failed:
6469 0 : pfree(rels);
6470 0 : FreeFile(fp);
6471 :
6472 0 : return false;
6473 : }
6474 :
6475 : /*
6476 : * Write out a new initialization file with the current contents
6477 : * of the relcache (either shared rels or local rels, as indicated).
6478 : */
6479 : static void
6480 5540 : write_relcache_init_file(bool shared)
6481 : {
6482 : FILE *fp;
6483 : char tempfilename[MAXPGPATH];
6484 : char finalfilename[MAXPGPATH];
6485 : int magic;
6486 : HASH_SEQ_STATUS status;
6487 : RelIdCacheEnt *idhentry;
6488 : int i;
6489 :
6490 : /*
6491 : * If we have already received any relcache inval events, there's no
6492 : * chance of succeeding so we may as well skip the whole thing.
6493 : */
6494 5540 : if (relcacheInvalsReceived != 0L)
6495 8 : return;
6496 :
6497 : /*
6498 : * We must write a temporary file and rename it into place. Otherwise,
6499 : * another backend starting at about the same time might crash trying to
6500 : * read the partially-complete file.
6501 : */
6502 5532 : if (shared)
6503 : {
6504 2766 : snprintf(tempfilename, sizeof(tempfilename), "global/%s.%d",
6505 : RELCACHE_INIT_FILENAME, MyProcPid);
6506 2766 : snprintf(finalfilename, sizeof(finalfilename), "global/%s",
6507 : RELCACHE_INIT_FILENAME);
6508 : }
6509 : else
6510 : {
6511 2766 : snprintf(tempfilename, sizeof(tempfilename), "%s/%s.%d",
6512 : DatabasePath, RELCACHE_INIT_FILENAME, MyProcPid);
6513 2766 : snprintf(finalfilename, sizeof(finalfilename), "%s/%s",
6514 : DatabasePath, RELCACHE_INIT_FILENAME);
6515 : }
6516 :
6517 5532 : unlink(tempfilename); /* in case it exists w/wrong permissions */
6518 :
6519 5532 : fp = AllocateFile(tempfilename, PG_BINARY_W);
6520 5532 : if (fp == NULL)
6521 : {
6522 : /*
6523 : * We used to consider this a fatal error, but we might as well
6524 : * continue with backend startup ...
6525 : */
6526 0 : ereport(WARNING,
6527 : (errcode_for_file_access(),
6528 : errmsg("could not create relation-cache initialization file \"%s\": %m",
6529 : tempfilename),
6530 : errdetail("Continuing anyway, but there's something wrong.")));
6531 0 : return;
6532 : }
6533 :
6534 : /*
6535 : * Write a magic number to serve as a file version identifier. We can
6536 : * change the magic number whenever the relcache layout changes.
6537 : */
6538 5532 : magic = RELCACHE_INIT_FILEMAGIC;
6539 5532 : if (fwrite(&magic, 1, sizeof(magic), fp) != sizeof(magic))
6540 0 : ereport(FATAL,
6541 : errcode_for_file_access(),
6542 : errmsg_internal("could not write init file: %m"));
6543 :
6544 : /*
6545 : * Write all the appropriate reldescs (in no particular order).
6546 : */
6547 5532 : hash_seq_init(&status, RelationIdCache);
6548 :
6549 763416 : while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
6550 : {
6551 757884 : Relation rel = idhentry->reldesc;
6552 757884 : Form_pg_class relform = rel->rd_rel;
6553 :
6554 : /* ignore if not correct group */
6555 757884 : if (relform->relisshared != shared)
6556 378942 : continue;
6557 :
6558 : /*
6559 : * Ignore if not supposed to be in init file. We can allow any shared
6560 : * relation that's been loaded so far to be in the shared init file,
6561 : * but unshared relations must be ones that should be in the local
6562 : * file per RelationIdIsInInitFile. (Note: if you want to change the
6563 : * criterion for rels to be kept in the init file, see also inval.c.
6564 : * The reason for filtering here is to be sure that we don't put
6565 : * anything into the local init file for which a relcache inval would
6566 : * not cause invalidation of that init file.)
6567 : */
6568 378942 : if (!shared && !RelationIdIsInInitFile(RelationGetRelid(rel)))
6569 : {
6570 : /* Nailed rels had better get stored. */
6571 : Assert(!rel->rd_isnailed);
6572 0 : continue;
6573 : }
6574 :
6575 : /* first write the relcache entry proper */
6576 378942 : write_item(rel, sizeof(RelationData), fp);
6577 :
6578 : /* next write the relation tuple form */
6579 378942 : write_item(relform, CLASS_TUPLE_SIZE, fp);
6580 :
6581 : /* next, do all the attribute tuple form data entries */
6582 2221098 : for (i = 0; i < relform->relnatts; i++)
6583 : {
6584 1842156 : write_item(TupleDescAttr(rel->rd_att, i),
6585 : ATTRIBUTE_FIXED_PART_SIZE, fp);
6586 : }
6587 :
6588 : /* next, do the access method specific field */
6589 378942 : write_item(rel->rd_options,
6590 378942 : (rel->rd_options ? VARSIZE(rel->rd_options) : 0),
6591 : fp);
6592 :
6593 : /*
6594 : * If it's an index, there's more to do. Note we explicitly ignore
6595 : * partitioned indexes here.
6596 : */
6597 378942 : if (rel->rd_rel->relkind == RELKIND_INDEX)
6598 : {
6599 : /* write the pg_index tuple */
6600 : /* we assume this was created by heap_copytuple! */
6601 237876 : write_item(rel->rd_indextuple,
6602 237876 : HEAPTUPLESIZE + rel->rd_indextuple->t_len,
6603 : fp);
6604 :
6605 : /* write the vector of opfamily OIDs */
6606 237876 : write_item(rel->rd_opfamily,
6607 237876 : relform->relnatts * sizeof(Oid),
6608 : fp);
6609 :
6610 : /* write the vector of opcintype OIDs */
6611 237876 : write_item(rel->rd_opcintype,
6612 237876 : relform->relnatts * sizeof(Oid),
6613 : fp);
6614 :
6615 : /* write the vector of support procedure OIDs */
6616 237876 : write_item(rel->rd_support,
6617 237876 : relform->relnatts * (rel->rd_indam->amsupport * sizeof(RegProcedure)),
6618 : fp);
6619 :
6620 : /* write the vector of collation OIDs */
6621 237876 : write_item(rel->rd_indcollation,
6622 237876 : relform->relnatts * sizeof(Oid),
6623 : fp);
6624 :
6625 : /* write the vector of indoption values */
6626 237876 : write_item(rel->rd_indoption,
6627 237876 : relform->relnatts * sizeof(int16),
6628 : fp);
6629 :
6630 : Assert(rel->rd_opcoptions);
6631 :
6632 : /* write the vector of opcoptions values */
6633 627882 : for (i = 0; i < relform->relnatts; i++)
6634 : {
6635 390006 : bytea *opt = rel->rd_opcoptions[i];
6636 :
6637 390006 : write_item(opt, opt ? VARSIZE(opt) : 0, fp);
6638 : }
6639 : }
6640 : }
6641 :
6642 5532 : if (FreeFile(fp))
6643 0 : ereport(FATAL,
6644 : errcode_for_file_access(),
6645 : errmsg_internal("could not write init file: %m"));
6646 :
6647 : /*
6648 : * Now we have to check whether the data we've so painstakingly
6649 : * accumulated is already obsolete due to someone else's just-committed
6650 : * catalog changes. If so, we just delete the temp file and leave it to
6651 : * the next backend to try again. (Our own relcache entries will be
6652 : * updated by SI message processing, but we can't be sure whether what we
6653 : * wrote out was up-to-date.)
6654 : *
6655 : * This mustn't run concurrently with the code that unlinks an init file
6656 : * and sends SI messages, so grab a serialization lock for the duration.
6657 : */
6658 5532 : LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
6659 :
6660 : /* Make sure we have seen all incoming SI messages */
6661 5532 : AcceptInvalidationMessages();
6662 :
6663 : /*
6664 : * If we have received any SI relcache invals since backend start, assume
6665 : * we may have written out-of-date data.
6666 : */
6667 5532 : if (relcacheInvalsReceived == 0L)
6668 : {
6669 : /*
6670 : * OK, rename the temp file to its final name, deleting any
6671 : * previously-existing init file.
6672 : *
6673 : * Note: a failure here is possible under Cygwin, if some other
6674 : * backend is holding open an unlinked-but-not-yet-gone init file. So
6675 : * treat this as a noncritical failure; just remove the useless temp
6676 : * file on failure.
6677 : */
6678 5530 : if (rename(tempfilename, finalfilename) < 0)
6679 0 : unlink(tempfilename);
6680 : }
6681 : else
6682 : {
6683 : /* Delete the already-obsolete temp file */
6684 2 : unlink(tempfilename);
6685 : }
6686 :
6687 5532 : LWLockRelease(RelCacheInitLock);
6688 : }
6689 :
6690 : /* write a chunk of data preceded by its length */
6691 : static void
6692 4796244 : write_item(const void *data, Size len, FILE *fp)
6693 : {
6694 4796244 : if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len))
6695 0 : ereport(FATAL,
6696 : errcode_for_file_access(),
6697 : errmsg_internal("could not write init file: %m"));
6698 4796244 : if (len > 0 && fwrite(data, 1, len, fp) != len)
6699 0 : ereport(FATAL,
6700 : errcode_for_file_access(),
6701 : errmsg_internal("could not write init file: %m"));
6702 4796244 : }
6703 :
6704 : /*
6705 : * Determine whether a given relation (identified by OID) is one of the ones
6706 : * we should store in a relcache init file.
6707 : *
6708 : * We must cache all nailed rels, and for efficiency we should cache every rel
6709 : * that supports a syscache. The former set is almost but not quite a subset
6710 : * of the latter. The special cases are relations where
6711 : * RelationCacheInitializePhase2/3 chooses to nail for efficiency reasons, but
6712 : * which do not support any syscache.
6713 : */
6714 : bool
6715 2243802 : RelationIdIsInInitFile(Oid relationId)
6716 : {
6717 2243802 : if (relationId == SharedSecLabelRelationId ||
6718 2238684 : relationId == TriggerRelidNameIndexId ||
6719 2238428 : relationId == DatabaseNameIndexId ||
6720 : relationId == SharedSecLabelObjectIndexId)
6721 : {
6722 : /*
6723 : * If this Assert fails, we don't need the applicable special case
6724 : * anymore.
6725 : */
6726 : Assert(!RelationSupportsSysCache(relationId));
6727 5656 : return true;
6728 : }
6729 2238146 : return RelationSupportsSysCache(relationId);
6730 : }
6731 :
6732 : /*
6733 : * Invalidate (remove) the init file during commit of a transaction that
6734 : * changed one or more of the relation cache entries that are kept in the
6735 : * local init file.
6736 : *
6737 : * To be safe against concurrent inspection or rewriting of the init file,
6738 : * we must take RelCacheInitLock, then remove the old init file, then send
6739 : * the SI messages that include relcache inval for such relations, and then
6740 : * release RelCacheInitLock. This serializes the whole affair against
6741 : * write_relcache_init_file, so that we can be sure that any other process
6742 : * that's concurrently trying to create a new init file won't move an
6743 : * already-stale version into place after we unlink. Also, because we unlink
6744 : * before sending the SI messages, a backend that's currently starting cannot
6745 : * read the now-obsolete init file and then miss the SI messages that will
6746 : * force it to update its relcache entries. (This works because the backend
6747 : * startup sequence gets into the sinval array before trying to load the init
6748 : * file.)
6749 : *
6750 : * We take the lock and do the unlink in RelationCacheInitFilePreInvalidate,
6751 : * then release the lock in RelationCacheInitFilePostInvalidate. Caller must
6752 : * send any pending SI messages between those calls.
6753 : */
6754 : void
6755 64112 : RelationCacheInitFilePreInvalidate(void)
6756 : {
6757 : char localinitfname[MAXPGPATH];
6758 : char sharedinitfname[MAXPGPATH];
6759 :
6760 64112 : if (DatabasePath)
6761 64112 : snprintf(localinitfname, sizeof(localinitfname), "%s/%s",
6762 : DatabasePath, RELCACHE_INIT_FILENAME);
6763 64112 : snprintf(sharedinitfname, sizeof(sharedinitfname), "global/%s",
6764 : RELCACHE_INIT_FILENAME);
6765 :
6766 64112 : LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
6767 :
6768 : /*
6769 : * The files might not be there if no backend has been started since the
6770 : * last removal. But complain about failures other than ENOENT with
6771 : * ERROR. Fortunately, it's not too late to abort the transaction if we
6772 : * can't get rid of the would-be-obsolete init file.
6773 : */
6774 64112 : if (DatabasePath)
6775 64112 : unlink_initfile(localinitfname, ERROR);
6776 64112 : unlink_initfile(sharedinitfname, ERROR);
6777 64112 : }
6778 :
6779 : void
6780 64112 : RelationCacheInitFilePostInvalidate(void)
6781 : {
6782 64112 : LWLockRelease(RelCacheInitLock);
6783 64112 : }
6784 :
6785 : /*
6786 : * Remove the init files during postmaster startup.
6787 : *
6788 : * We used to keep the init files across restarts, but that is unsafe in PITR
6789 : * scenarios, and even in simple crash-recovery cases there are windows for
6790 : * the init files to become out-of-sync with the database. So now we just
6791 : * remove them during startup and expect the first backend launch to rebuild
6792 : * them. Of course, this has to happen in each database of the cluster.
6793 : */
6794 : void
6795 1634 : RelationCacheInitFileRemove(void)
6796 : {
6797 1634 : const char *tblspcdir = PG_TBLSPC_DIR;
6798 : DIR *dir;
6799 : struct dirent *de;
6800 : char path[MAXPGPATH + sizeof(PG_TBLSPC_DIR) + sizeof(TABLESPACE_VERSION_DIRECTORY)];
6801 :
6802 1634 : snprintf(path, sizeof(path), "global/%s",
6803 : RELCACHE_INIT_FILENAME);
6804 1634 : unlink_initfile(path, LOG);
6805 :
6806 : /* Scan everything in the default tablespace */
6807 1634 : RelationCacheInitFileRemoveInDir("base");
6808 :
6809 : /* Scan the tablespace link directory to find non-default tablespaces */
6810 1634 : dir = AllocateDir(tblspcdir);
6811 :
6812 4998 : while ((de = ReadDirExtended(dir, tblspcdir, LOG)) != NULL)
6813 : {
6814 3364 : if (strspn(de->d_name, "0123456789") == strlen(de->d_name))
6815 : {
6816 : /* Scan the tablespace dir for per-database dirs */
6817 96 : snprintf(path, sizeof(path), "%s/%s/%s",
6818 96 : tblspcdir, de->d_name, TABLESPACE_VERSION_DIRECTORY);
6819 96 : RelationCacheInitFileRemoveInDir(path);
6820 : }
6821 : }
6822 :
6823 1634 : FreeDir(dir);
6824 1634 : }
6825 :
6826 : /* Process one per-tablespace directory for RelationCacheInitFileRemove */
6827 : static void
6828 1730 : RelationCacheInitFileRemoveInDir(const char *tblspcpath)
6829 : {
6830 : DIR *dir;
6831 : struct dirent *de;
6832 : char initfilename[MAXPGPATH * 2];
6833 :
6834 : /* Scan the tablespace directory to find per-database directories */
6835 1730 : dir = AllocateDir(tblspcpath);
6836 :
6837 10452 : while ((de = ReadDirExtended(dir, tblspcpath, LOG)) != NULL)
6838 : {
6839 8722 : if (strspn(de->d_name, "0123456789") == strlen(de->d_name))
6840 : {
6841 : /* Try to remove the init file in each database */
6842 5122 : snprintf(initfilename, sizeof(initfilename), "%s/%s/%s",
6843 5122 : tblspcpath, de->d_name, RELCACHE_INIT_FILENAME);
6844 5122 : unlink_initfile(initfilename, LOG);
6845 : }
6846 : }
6847 :
6848 1730 : FreeDir(dir);
6849 1730 : }
6850 :
6851 : static void
6852 134980 : unlink_initfile(const char *initfilename, int elevel)
6853 : {
6854 134980 : if (unlink(initfilename) < 0)
6855 : {
6856 : /* It might not be there, but log any error other than ENOENT */
6857 132446 : if (errno != ENOENT)
6858 0 : ereport(elevel,
6859 : (errcode_for_file_access(),
6860 : errmsg("could not remove cache file \"%s\": %m",
6861 : initfilename)));
6862 : }
6863 134980 : }
6864 :
6865 : /*
6866 : * ResourceOwner callbacks
6867 : */
6868 : static char *
6869 0 : ResOwnerPrintRelCache(Datum res)
6870 : {
6871 0 : Relation rel = (Relation) DatumGetPointer(res);
6872 :
6873 0 : return psprintf("relation \"%s\"", RelationGetRelationName(rel));
6874 : }
6875 :
6876 : static void
6877 37424 : ResOwnerReleaseRelation(Datum res)
6878 : {
6879 37424 : Relation rel = (Relation) DatumGetPointer(res);
6880 :
6881 : /*
6882 : * This reference has already been removed from the resource owner, so
6883 : * just decrement reference count without calling
6884 : * ResourceOwnerForgetRelationRef.
6885 : */
6886 : Assert(rel->rd_refcnt > 0);
6887 37424 : rel->rd_refcnt -= 1;
6888 :
6889 37424 : RelationCloseCleanup((Relation) res);
6890 37424 : }
|