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