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