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