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