PostgreSQL Source Code  git master
relcache.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * relcache.c
4  * POSTGRES relation descriptor cache code
5  *
6  * Portions Copyright (c) 1996-2021, 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/nbtree.h"
36 #include "access/parallel.h"
37 #include "access/reloptions.h"
38 #include "access/sysattr.h"
39 #include "access/table.h"
40 #include "access/tableam.h"
41 #include "access/tupdesc_details.h"
42 #include "access/xact.h"
43 #include "access/xlog.h"
44 #include "catalog/catalog.h"
45 #include "catalog/index.h"
46 #include "catalog/indexing.h"
47 #include "catalog/namespace.h"
48 #include "catalog/partition.h"
49 #include "catalog/pg_am.h"
50 #include "catalog/pg_amproc.h"
51 #include "catalog/pg_attrdef.h"
53 #include "catalog/pg_authid.h"
54 #include "catalog/pg_constraint.h"
55 #include "catalog/pg_database.h"
56 #include "catalog/pg_namespace.h"
57 #include "catalog/pg_opclass.h"
58 #include "catalog/pg_proc.h"
59 #include "catalog/pg_publication.h"
60 #include "catalog/pg_rewrite.h"
61 #include "catalog/pg_shseclabel.h"
64 #include "catalog/pg_tablespace.h"
65 #include "catalog/pg_trigger.h"
66 #include "catalog/pg_type.h"
67 #include "catalog/schemapg.h"
68 #include "catalog/storage.h"
69 #include "commands/policy.h"
70 #include "commands/trigger.h"
71 #include "miscadmin.h"
72 #include "nodes/makefuncs.h"
73 #include "nodes/nodeFuncs.h"
74 #include "optimizer/optimizer.h"
75 #include "rewrite/rewriteDefine.h"
76 #include "rewrite/rowsecurity.h"
77 #include "storage/lmgr.h"
78 #include "storage/smgr.h"
79 #include "utils/array.h"
80 #include "utils/builtins.h"
81 #include "utils/datum.h"
82 #include "utils/fmgroids.h"
83 #include "utils/inval.h"
84 #include "utils/lsyscache.h"
85 #include "utils/memutils.h"
86 #include "utils/relmapper.h"
87 #include "utils/resowner_private.h"
88 #include "utils/snapmgr.h"
89 #include "utils/syscache.h"
90 
91 #define RELCACHE_INIT_FILEMAGIC 0x573266 /* version ID value */
92 
93 /*
94  * Whether to bother checking if relation cache memory needs to be freed
95  * eagerly. See also RelationBuildDesc() and pg_config_manual.h.
96  */
97 #if defined(RECOVER_RELATION_BUILD_MEMORY) && (RECOVER_RELATION_BUILD_MEMORY != 0)
98 #define MAYBE_RECOVER_RELATION_BUILD_MEMORY 1
99 #else
100 #define RECOVER_RELATION_BUILD_MEMORY 0
101 #ifdef CLOBBER_CACHE_ENABLED
102 #define MAYBE_RECOVER_RELATION_BUILD_MEMORY 1
103 #endif
104 #endif
105 
106 /*
107  * hardcoded tuple descriptors, contents generated by genbki.pl
108  */
109 static const FormData_pg_attribute Desc_pg_class[Natts_pg_class] = {Schema_pg_class};
110 static const FormData_pg_attribute Desc_pg_attribute[Natts_pg_attribute] = {Schema_pg_attribute};
111 static const FormData_pg_attribute Desc_pg_proc[Natts_pg_proc] = {Schema_pg_proc};
112 static const FormData_pg_attribute Desc_pg_type[Natts_pg_type] = {Schema_pg_type};
113 static const FormData_pg_attribute Desc_pg_database[Natts_pg_database] = {Schema_pg_database};
114 static const FormData_pg_attribute Desc_pg_authid[Natts_pg_authid] = {Schema_pg_authid};
115 static const FormData_pg_attribute Desc_pg_auth_members[Natts_pg_auth_members] = {Schema_pg_auth_members};
116 static const FormData_pg_attribute Desc_pg_index[Natts_pg_index] = {Schema_pg_index};
117 static const FormData_pg_attribute Desc_pg_shseclabel[Natts_pg_shseclabel] = {Schema_pg_shseclabel};
118 static const FormData_pg_attribute Desc_pg_subscription[Natts_pg_subscription] = {Schema_pg_subscription};
119 
120 /*
121  * Hash tables that index the relation cache
122  *
123  * We used to index the cache by both name and OID, but now there
124  * is only an index by OID.
125  */
126 typedef struct relidcacheent
127 {
130 } RelIdCacheEnt;
131 
133 
134 /*
135  * This flag is false until we have prepared the critical relcache entries
136  * that are needed to do indexscans on the tables read by relcache building.
137  */
139 
140 /*
141  * This flag is false until we have prepared the critical relcache entries
142  * for shared catalogs (which are the tables needed for login).
143  */
145 
146 /*
147  * This counter counts relcache inval events received since backend startup
148  * (but only for rels that are actually in cache). Presently, we use it only
149  * to detect whether data about to be written by write_relcache_init_file()
150  * might already be obsolete.
151  */
152 static long relcacheInvalsReceived = 0L;
153 
154 /*
155  * eoxact_list[] stores the OIDs of relations that (might) need AtEOXact
156  * cleanup work. This list intentionally has limited size; if it overflows,
157  * we fall back to scanning the whole hashtable. There is no value in a very
158  * large list because (1) at some point, a hash_seq_search scan is faster than
159  * retail lookups, and (2) the value of this is to reduce EOXact work for
160  * short transactions, which can't have dirtied all that many tables anyway.
161  * EOXactListAdd() does not bother to prevent duplicate list entries, so the
162  * cleanup processing must be idempotent.
163  */
164 #define MAX_EOXACT_LIST 32
166 static int eoxact_list_len = 0;
167 static bool eoxact_list_overflowed = false;
168 
169 #define EOXactListAdd(rel) \
170  do { \
171  if (eoxact_list_len < MAX_EOXACT_LIST) \
172  eoxact_list[eoxact_list_len++] = (rel)->rd_id; \
173  else \
174  eoxact_list_overflowed = true; \
175  } while (0)
176 
177 /*
178  * EOXactTupleDescArray stores TupleDescs that (might) need AtEOXact
179  * cleanup work. The array expands as needed; there is no hashtable because
180  * we don't need to access individual items except at EOXact.
181  */
183 static int NextEOXactTupleDescNum = 0;
184 static int EOXactTupleDescArrayLen = 0;
185 
186 /*
187  * macros to manipulate the lookup hashtable
188  */
189 #define RelationCacheInsert(RELATION, replace_allowed) \
190 do { \
191  RelIdCacheEnt *hentry; bool found; \
192  hentry = (RelIdCacheEnt *) hash_search(RelationIdCache, \
193  (void *) &((RELATION)->rd_id), \
194  HASH_ENTER, &found); \
195  if (found) \
196  { \
197  /* see comments in RelationBuildDesc and RelationBuildLocalRelation */ \
198  Relation _old_rel = hentry->reldesc; \
199  Assert(replace_allowed); \
200  hentry->reldesc = (RELATION); \
201  if (RelationHasReferenceCountZero(_old_rel)) \
202  RelationDestroyRelation(_old_rel, false); \
203  else if (!IsBootstrapProcessingMode()) \
204  elog(WARNING, "leaking still-referenced relcache entry for \"%s\"", \
205  RelationGetRelationName(_old_rel)); \
206  } \
207  else \
208  hentry->reldesc = (RELATION); \
209 } while(0)
210 
211 #define RelationIdCacheLookup(ID, RELATION) \
212 do { \
213  RelIdCacheEnt *hentry; \
214  hentry = (RelIdCacheEnt *) hash_search(RelationIdCache, \
215  (void *) &(ID), \
216  HASH_FIND, NULL); \
217  if (hentry) \
218  RELATION = hentry->reldesc; \
219  else \
220  RELATION = NULL; \
221 } while(0)
222 
223 #define RelationCacheDelete(RELATION) \
224 do { \
225  RelIdCacheEnt *hentry; \
226  hentry = (RelIdCacheEnt *) hash_search(RelationIdCache, \
227  (void *) &((RELATION)->rd_id), \
228  HASH_REMOVE, NULL); \
229  if (hentry == NULL) \
230  elog(WARNING, "failed to delete relcache entry for OID %u", \
231  (RELATION)->rd_id); \
232 } while(0)
233 
234 
235 /*
236  * Special cache for opclass-related information
237  *
238  * Note: only default support procs get cached, ie, those with
239  * lefttype = righttype = opcintype.
240  */
241 typedef struct opclasscacheent
242 {
243  Oid opclassoid; /* lookup key: OID of opclass */
244  bool valid; /* set true after successful fill-in */
245  StrategyNumber numSupport; /* max # of support procs (from pg_am) */
246  Oid opcfamily; /* OID of opclass's family */
247  Oid opcintype; /* OID of opclass's declared input type */
248  RegProcedure *supportProcs; /* OIDs of support procedures */
250 
251 static HTAB *OpClassCache = NULL;
252 
253 
254 /* non-export function prototypes */
255 
256 static void RelationDestroyRelation(Relation relation, bool remember_tupdesc);
257 static void RelationClearRelation(Relation relation, bool rebuild);
258 
259 static void RelationReloadIndexInfo(Relation relation);
260 static void RelationReloadNailed(Relation relation);
261 static void RelationFlushRelation(Relation relation);
263 #ifdef USE_ASSERT_CHECKING
264 static void AssertPendingSyncConsistency(Relation relation);
265 #endif
266 static void AtEOXact_cleanup(Relation relation, bool isCommit);
267 static void AtEOSubXact_cleanup(Relation relation, bool isCommit,
268  SubTransactionId mySubid, SubTransactionId parentSubid);
269 static bool load_relcache_init_file(bool shared);
270 static void write_relcache_init_file(bool shared);
271 static void write_item(const void *data, Size len, FILE *fp);
272 
273 static void formrdesc(const char *relationName, Oid relationReltype,
274  bool isshared, int natts, const FormData_pg_attribute *attrs);
275 
276 static HeapTuple ScanPgRelation(Oid targetRelId, bool indexOK, bool force_non_historic);
278 static void RelationParseRelOptions(Relation relation, HeapTuple tuple);
279 static void RelationBuildTupleDesc(Relation relation);
280 static Relation RelationBuildDesc(Oid targetRelId, bool insertIt);
281 static void RelationInitPhysicalAddr(Relation relation);
282 static void load_critical_index(Oid indexoid, Oid heapoid);
283 static TupleDesc GetPgClassDescriptor(void);
284 static TupleDesc GetPgIndexDescriptor(void);
285 static void AttrDefaultFetch(Relation relation);
286 static void CheckConstraintFetch(Relation relation);
287 static int CheckConstraintCmp(const void *a, const void *b);
288 static void InitIndexAmRoutine(Relation relation);
289 static void IndexSupportInitialize(oidvector *indclass,
290  RegProcedure *indexSupport,
291  Oid *opFamily,
292  Oid *opcInType,
293  StrategyNumber maxSupportNumber,
294  AttrNumber maxAttributeNumber);
295 static OpClassCacheEnt *LookupOpclassInfo(Oid operatorClassOid,
296  StrategyNumber numSupport);
297 static void RelationCacheInitFileRemoveInDir(const char *tblspcpath);
298 static void unlink_initfile(const char *initfilename, int elevel);
299 
300 
301 /*
302  * ScanPgRelation
303  *
304  * This is used by RelationBuildDesc to find a pg_class
305  * tuple matching targetRelId. The caller must hold at least
306  * AccessShareLock on the target relid to prevent concurrent-update
307  * scenarios; it isn't guaranteed that all scans used to build the
308  * relcache entry will use the same snapshot. If, for example,
309  * an attribute were to be added after scanning pg_class and before
310  * scanning pg_attribute, relnatts wouldn't match.
311  *
312  * NB: the returned tuple has been copied into palloc'd storage
313  * and must eventually be freed with heap_freetuple.
314  */
315 static HeapTuple
316 ScanPgRelation(Oid targetRelId, bool indexOK, bool force_non_historic)
317 {
318  HeapTuple pg_class_tuple;
319  Relation pg_class_desc;
320  SysScanDesc pg_class_scan;
321  ScanKeyData key[1];
322  Snapshot snapshot = NULL;
323 
324  /*
325  * If something goes wrong during backend startup, we might find ourselves
326  * trying to read pg_class before we've selected a database. That ain't
327  * gonna work, so bail out with a useful error message. If this happens,
328  * it probably means a relcache entry that needs to be nailed isn't.
329  */
330  if (!OidIsValid(MyDatabaseId))
331  elog(FATAL, "cannot read pg_class without having selected a database");
332 
333  /*
334  * form a scan key
335  */
336  ScanKeyInit(&key[0],
337  Anum_pg_class_oid,
338  BTEqualStrategyNumber, F_OIDEQ,
339  ObjectIdGetDatum(targetRelId));
340 
341  /*
342  * Open pg_class and fetch a tuple. Force heap scan if we haven't yet
343  * built the critical relcache entries (this includes initdb and startup
344  * without a pg_internal.init file). The caller can also force a heap
345  * scan by setting indexOK == false.
346  */
347  pg_class_desc = table_open(RelationRelationId, AccessShareLock);
348 
349  /*
350  * The caller might need a tuple that's newer than the one the historic
351  * snapshot; currently the only case requiring to do so is looking up the
352  * relfilenode of non mapped system relations during decoding. That
353  * snapshot can't change in the midst of a relcache build, so there's no
354  * need to register the snapshot.
355  */
356  if (force_non_historic)
357  snapshot = GetNonHistoricCatalogSnapshot(RelationRelationId);
358 
359  pg_class_scan = systable_beginscan(pg_class_desc, ClassOidIndexId,
360  indexOK && criticalRelcachesBuilt,
361  snapshot,
362  1, key);
363 
364  pg_class_tuple = systable_getnext(pg_class_scan);
365 
366  /*
367  * Must copy tuple before releasing buffer.
368  */
369  if (HeapTupleIsValid(pg_class_tuple))
370  pg_class_tuple = heap_copytuple(pg_class_tuple);
371 
372  /* all done */
373  systable_endscan(pg_class_scan);
374  table_close(pg_class_desc, AccessShareLock);
375 
376  return pg_class_tuple;
377 }
378 
379 /*
380  * AllocateRelationDesc
381  *
382  * This is used to allocate memory for a new relation descriptor
383  * and initialize the rd_rel field from the given pg_class tuple.
384  */
385 static Relation
387 {
388  Relation relation;
389  MemoryContext oldcxt;
390  Form_pg_class relationForm;
391 
392  /* Relcache entries must live in CacheMemoryContext */
394 
395  /*
396  * allocate and zero space for new relation descriptor
397  */
398  relation = (Relation) palloc0(sizeof(RelationData));
399 
400  /* make sure relation is marked as having no open file yet */
401  relation->rd_smgr = NULL;
402 
403  /*
404  * Copy the relation tuple form
405  *
406  * We only allocate space for the fixed fields, ie, CLASS_TUPLE_SIZE. The
407  * variable-length fields (relacl, reloptions) are NOT stored in the
408  * relcache --- there'd be little point in it, since we don't copy the
409  * tuple's nulls bitmap and hence wouldn't know if the values are valid.
410  * Bottom line is that relacl *cannot* be retrieved from the relcache. Get
411  * it from the syscache if you need it. The same goes for the original
412  * form of reloptions (however, we do store the parsed form of reloptions
413  * in rd_options).
414  */
415  relationForm = (Form_pg_class) palloc(CLASS_TUPLE_SIZE);
416 
417  memcpy(relationForm, relp, CLASS_TUPLE_SIZE);
418 
419  /* initialize relation tuple form */
420  relation->rd_rel = relationForm;
421 
422  /* and allocate attribute tuple form storage */
423  relation->rd_att = CreateTemplateTupleDesc(relationForm->relnatts);
424  /* which we mark as a reference-counted tupdesc */
425  relation->rd_att->tdrefcount = 1;
426 
427  MemoryContextSwitchTo(oldcxt);
428 
429  return relation;
430 }
431 
432 /*
433  * RelationParseRelOptions
434  * Convert pg_class.reloptions into pre-parsed rd_options
435  *
436  * tuple is the real pg_class tuple (not rd_rel!) for relation
437  *
438  * Note: rd_rel and (if an index) rd_indam must be valid already
439  */
440 static void
442 {
443  bytea *options;
444  amoptions_function amoptsfn;
445 
446  relation->rd_options = NULL;
447 
448  /*
449  * Look up any AM-specific parse function; fall out if relkind should not
450  * have options.
451  */
452  switch (relation->rd_rel->relkind)
453  {
454  case RELKIND_RELATION:
455  case RELKIND_TOASTVALUE:
456  case RELKIND_VIEW:
457  case RELKIND_MATVIEW:
458  case RELKIND_PARTITIONED_TABLE:
459  amoptsfn = NULL;
460  break;
461  case RELKIND_INDEX:
462  case RELKIND_PARTITIONED_INDEX:
463  amoptsfn = relation->rd_indam->amoptions;
464  break;
465  default:
466  return;
467  }
468 
469  /*
470  * Fetch reloptions from tuple; have to use a hardwired descriptor because
471  * we might not have any other for pg_class yet (consider executing this
472  * code for pg_class itself)
473  */
474  options = extractRelOptions(tuple, GetPgClassDescriptor(), amoptsfn);
475 
476  /*
477  * Copy parsed data into CacheMemoryContext. To guard against the
478  * possibility of leaks in the reloptions code, we want to do the actual
479  * parsing in the caller's memory context and copy the results into
480  * CacheMemoryContext after the fact.
481  */
482  if (options)
483  {
485  VARSIZE(options));
486  memcpy(relation->rd_options, options, VARSIZE(options));
487  pfree(options);
488  }
489 }
490 
491 /*
492  * RelationBuildTupleDesc
493  *
494  * Form the relation's tuple descriptor from information in
495  * the pg_attribute, pg_attrdef & pg_constraint system catalogs.
496  */
497 static void
499 {
500  HeapTuple pg_attribute_tuple;
501  Relation pg_attribute_desc;
502  SysScanDesc pg_attribute_scan;
503  ScanKeyData skey[2];
504  int need;
505  TupleConstr *constr;
506  AttrDefault *attrdef = NULL;
507  AttrMissing *attrmiss = NULL;
508  int ndef = 0;
509 
510  /* fill rd_att's type ID fields (compare heap.c's AddNewRelationTuple) */
511  relation->rd_att->tdtypeid =
512  relation->rd_rel->reltype ? relation->rd_rel->reltype : RECORDOID;
513  relation->rd_att->tdtypmod = -1; /* just to be sure */
514 
516  sizeof(TupleConstr));
517  constr->has_not_null = false;
518  constr->has_generated_stored = false;
519 
520  /*
521  * Form a scan key that selects only user attributes (attnum > 0).
522  * (Eliminating system attribute rows at the index level is lots faster
523  * than fetching them.)
524  */
525  ScanKeyInit(&skey[0],
526  Anum_pg_attribute_attrelid,
527  BTEqualStrategyNumber, F_OIDEQ,
529  ScanKeyInit(&skey[1],
530  Anum_pg_attribute_attnum,
531  BTGreaterStrategyNumber, F_INT2GT,
532  Int16GetDatum(0));
533 
534  /*
535  * Open pg_attribute and begin a scan. Force heap scan if we haven't yet
536  * built the critical relcache entries (this includes initdb and startup
537  * without a pg_internal.init file).
538  */
539  pg_attribute_desc = table_open(AttributeRelationId, AccessShareLock);
540  pg_attribute_scan = systable_beginscan(pg_attribute_desc,
543  NULL,
544  2, skey);
545 
546  /*
547  * add attribute data to relation->rd_att
548  */
549  need = RelationGetNumberOfAttributes(relation);
550 
551  while (HeapTupleIsValid(pg_attribute_tuple = systable_getnext(pg_attribute_scan)))
552  {
553  Form_pg_attribute attp;
554  int attnum;
555 
556  attp = (Form_pg_attribute) GETSTRUCT(pg_attribute_tuple);
557 
558  attnum = attp->attnum;
559  if (attnum <= 0 || attnum > RelationGetNumberOfAttributes(relation))
560  elog(ERROR, "invalid attribute number %d for %s",
561  attp->attnum, RelationGetRelationName(relation));
562 
563 
564  memcpy(TupleDescAttr(relation->rd_att, attnum - 1),
565  attp,
567 
568  /* Update constraint/default info */
569  if (attp->attnotnull)
570  constr->has_not_null = true;
571  if (attp->attgenerated == ATTRIBUTE_GENERATED_STORED)
572  constr->has_generated_stored = true;
573 
574  /* If the column has a default, fill it into the attrdef array */
575  if (attp->atthasdef)
576  {
577  if (attrdef == NULL)
578  attrdef = (AttrDefault *)
581  sizeof(AttrDefault));
582  attrdef[ndef].adnum = attnum;
583  attrdef[ndef].adbin = NULL;
584 
585  ndef++;
586  }
587 
588  /* Likewise for a missing value */
589  if (attp->atthasmissing)
590  {
591  Datum missingval;
592  bool missingNull;
593 
594  /* Do we have a missing value? */
595  missingval = heap_getattr(pg_attribute_tuple,
596  Anum_pg_attribute_attmissingval,
597  pg_attribute_desc->rd_att,
598  &missingNull);
599  if (!missingNull)
600  {
601  /* Yes, fetch from the array */
602  MemoryContext oldcxt;
603  bool is_null;
604  int one = 1;
605  Datum missval;
606 
607  if (attrmiss == NULL)
608  attrmiss = (AttrMissing *)
610  relation->rd_rel->relnatts *
611  sizeof(AttrMissing));
612 
613  missval = array_get_element(missingval,
614  1,
615  &one,
616  -1,
617  attp->attlen,
618  attp->attbyval,
619  attp->attalign,
620  &is_null);
621  Assert(!is_null);
622  if (attp->attbyval)
623  {
624  /* for copy by val just copy the datum direct */
625  attrmiss[attnum - 1].am_value = missval;
626  }
627  else
628  {
629  /* otherwise copy in the correct context */
631  attrmiss[attnum - 1].am_value = datumCopy(missval,
632  attp->attbyval,
633  attp->attlen);
634  MemoryContextSwitchTo(oldcxt);
635  }
636  attrmiss[attnum - 1].am_present = true;
637  }
638  }
639  need--;
640  if (need == 0)
641  break;
642  }
643 
644  /*
645  * end the scan and close the attribute relation
646  */
647  systable_endscan(pg_attribute_scan);
648  table_close(pg_attribute_desc, AccessShareLock);
649 
650  if (need != 0)
651  elog(ERROR, "catalog is missing %d attribute(s) for relid %u",
652  need, RelationGetRelid(relation));
653 
654  /*
655  * The attcacheoff values we read from pg_attribute should all be -1
656  * ("unknown"). Verify this if assert checking is on. They will be
657  * computed when and if needed during tuple access.
658  */
659 #ifdef USE_ASSERT_CHECKING
660  {
661  int i;
662 
663  for (i = 0; i < RelationGetNumberOfAttributes(relation); i++)
664  Assert(TupleDescAttr(relation->rd_att, i)->attcacheoff == -1);
665  }
666 #endif
667 
668  /*
669  * However, we can easily set the attcacheoff value for the first
670  * attribute: it must be zero. This eliminates the need for special cases
671  * for attnum=1 that used to exist in fastgetattr() and index_getattr().
672  */
673  if (RelationGetNumberOfAttributes(relation) > 0)
674  TupleDescAttr(relation->rd_att, 0)->attcacheoff = 0;
675 
676  /*
677  * Set up constraint/default info
678  */
679  if (constr->has_not_null ||
680  constr->has_generated_stored ||
681  ndef > 0 ||
682  attrmiss ||
683  relation->rd_rel->relchecks)
684  {
685  relation->rd_att->constr = constr;
686 
687  if (ndef > 0) /* DEFAULTs */
688  {
689  if (ndef < RelationGetNumberOfAttributes(relation))
690  constr->defval = (AttrDefault *)
691  repalloc(attrdef, ndef * sizeof(AttrDefault));
692  else
693  constr->defval = attrdef;
694  constr->num_defval = ndef;
695  AttrDefaultFetch(relation);
696  }
697  else
698  constr->num_defval = 0;
699 
700  constr->missing = attrmiss;
701 
702  if (relation->rd_rel->relchecks > 0) /* CHECKs */
703  {
704  constr->num_check = relation->rd_rel->relchecks;
705  constr->check = (ConstrCheck *)
707  constr->num_check * sizeof(ConstrCheck));
708  CheckConstraintFetch(relation);
709  }
710  else
711  constr->num_check = 0;
712  }
713  else
714  {
715  pfree(constr);
716  relation->rd_att->constr = NULL;
717  }
718 }
719 
720 /*
721  * RelationBuildRuleLock
722  *
723  * Form the relation's rewrite rules from information in
724  * the pg_rewrite system catalog.
725  *
726  * Note: The rule parsetrees are potentially very complex node structures.
727  * To allow these trees to be freed when the relcache entry is flushed,
728  * we make a private memory context to hold the RuleLock information for
729  * each relcache entry that has associated rules. The context is used
730  * just for rule info, not for any other subsidiary data of the relcache
731  * entry, because that keeps the update logic in RelationClearRelation()
732  * manageable. The other subsidiary data structures are simple enough
733  * to be easy to free explicitly, anyway.
734  */
735 static void
737 {
738  MemoryContext rulescxt;
739  MemoryContext oldcxt;
740  HeapTuple rewrite_tuple;
741  Relation rewrite_desc;
742  TupleDesc rewrite_tupdesc;
743  SysScanDesc rewrite_scan;
745  RuleLock *rulelock;
746  int numlocks;
747  RewriteRule **rules;
748  int maxlocks;
749 
750  /*
751  * Make the private context. Assume it'll not contain much data.
752  */
754  "relation rules",
756  relation->rd_rulescxt = rulescxt;
758  RelationGetRelationName(relation));
759 
760  /*
761  * allocate an array to hold the rewrite rules (the array is extended if
762  * necessary)
763  */
764  maxlocks = 4;
765  rules = (RewriteRule **)
766  MemoryContextAlloc(rulescxt, sizeof(RewriteRule *) * maxlocks);
767  numlocks = 0;
768 
769  /*
770  * form a scan key
771  */
772  ScanKeyInit(&key,
773  Anum_pg_rewrite_ev_class,
774  BTEqualStrategyNumber, F_OIDEQ,
776 
777  /*
778  * open pg_rewrite and begin a scan
779  *
780  * Note: since we scan the rules using RewriteRelRulenameIndexId, we will
781  * be reading the rules in name order, except possibly during
782  * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
783  * ensures that rules will be fired in name order.
784  */
785  rewrite_desc = table_open(RewriteRelationId, AccessShareLock);
786  rewrite_tupdesc = RelationGetDescr(rewrite_desc);
787  rewrite_scan = systable_beginscan(rewrite_desc,
789  true, NULL,
790  1, &key);
791 
792  while (HeapTupleIsValid(rewrite_tuple = systable_getnext(rewrite_scan)))
793  {
794  Form_pg_rewrite rewrite_form = (Form_pg_rewrite) GETSTRUCT(rewrite_tuple);
795  bool isnull;
796  Datum rule_datum;
797  char *rule_str;
798  RewriteRule *rule;
799 
800  rule = (RewriteRule *) MemoryContextAlloc(rulescxt,
801  sizeof(RewriteRule));
802 
803  rule->ruleId = rewrite_form->oid;
804 
805  rule->event = rewrite_form->ev_type - '0';
806  rule->enabled = rewrite_form->ev_enabled;
807  rule->isInstead = rewrite_form->is_instead;
808 
809  /*
810  * Must use heap_getattr to fetch ev_action and ev_qual. Also, the
811  * rule strings are often large enough to be toasted. To avoid
812  * leaking memory in the caller's context, do the detoasting here so
813  * we can free the detoasted version.
814  */
815  rule_datum = heap_getattr(rewrite_tuple,
816  Anum_pg_rewrite_ev_action,
817  rewrite_tupdesc,
818  &isnull);
819  Assert(!isnull);
820  rule_str = TextDatumGetCString(rule_datum);
821  oldcxt = MemoryContextSwitchTo(rulescxt);
822  rule->actions = (List *) stringToNode(rule_str);
823  MemoryContextSwitchTo(oldcxt);
824  pfree(rule_str);
825 
826  rule_datum = heap_getattr(rewrite_tuple,
827  Anum_pg_rewrite_ev_qual,
828  rewrite_tupdesc,
829  &isnull);
830  Assert(!isnull);
831  rule_str = TextDatumGetCString(rule_datum);
832  oldcxt = MemoryContextSwitchTo(rulescxt);
833  rule->qual = (Node *) stringToNode(rule_str);
834  MemoryContextSwitchTo(oldcxt);
835  pfree(rule_str);
836 
837  /*
838  * We want the rule's table references to be checked as though by the
839  * table owner, not the user referencing the rule. Therefore, scan
840  * through the rule's actions and set the checkAsUser field on all
841  * rtable entries. We have to look at the qual as well, in case it
842  * contains sublinks.
843  *
844  * The reason for doing this when the rule is loaded, rather than when
845  * it is stored, is that otherwise ALTER TABLE OWNER would have to
846  * grovel through stored rules to update checkAsUser fields. Scanning
847  * the rule tree during load is relatively cheap (compared to
848  * constructing it in the first place), so we do it here.
849  */
850  setRuleCheckAsUser((Node *) rule->actions, relation->rd_rel->relowner);
851  setRuleCheckAsUser(rule->qual, relation->rd_rel->relowner);
852 
853  if (numlocks >= maxlocks)
854  {
855  maxlocks *= 2;
856  rules = (RewriteRule **)
857  repalloc(rules, sizeof(RewriteRule *) * maxlocks);
858  }
859  rules[numlocks++] = rule;
860  }
861 
862  /*
863  * end the scan and close the attribute relation
864  */
865  systable_endscan(rewrite_scan);
866  table_close(rewrite_desc, AccessShareLock);
867 
868  /*
869  * there might not be any rules (if relhasrules is out-of-date)
870  */
871  if (numlocks == 0)
872  {
873  relation->rd_rules = NULL;
874  relation->rd_rulescxt = NULL;
875  MemoryContextDelete(rulescxt);
876  return;
877  }
878 
879  /*
880  * form a RuleLock and insert into relation
881  */
882  rulelock = (RuleLock *) MemoryContextAlloc(rulescxt, sizeof(RuleLock));
883  rulelock->numLocks = numlocks;
884  rulelock->rules = rules;
885 
886  relation->rd_rules = rulelock;
887 }
888 
889 /*
890  * equalRuleLocks
891  *
892  * Determine whether two RuleLocks are equivalent
893  *
894  * Probably this should be in the rules code someplace...
895  */
896 static bool
898 {
899  int i;
900 
901  /*
902  * As of 7.3 we assume the rule ordering is repeatable, because
903  * RelationBuildRuleLock should read 'em in a consistent order. So just
904  * compare corresponding slots.
905  */
906  if (rlock1 != NULL)
907  {
908  if (rlock2 == NULL)
909  return false;
910  if (rlock1->numLocks != rlock2->numLocks)
911  return false;
912  for (i = 0; i < rlock1->numLocks; i++)
913  {
914  RewriteRule *rule1 = rlock1->rules[i];
915  RewriteRule *rule2 = rlock2->rules[i];
916 
917  if (rule1->ruleId != rule2->ruleId)
918  return false;
919  if (rule1->event != rule2->event)
920  return false;
921  if (rule1->enabled != rule2->enabled)
922  return false;
923  if (rule1->isInstead != rule2->isInstead)
924  return false;
925  if (!equal(rule1->qual, rule2->qual))
926  return false;
927  if (!equal(rule1->actions, rule2->actions))
928  return false;
929  }
930  }
931  else if (rlock2 != NULL)
932  return false;
933  return true;
934 }
935 
936 /*
937  * equalPolicy
938  *
939  * Determine whether two policies are equivalent
940  */
941 static bool
943 {
944  int i;
945  Oid *r1,
946  *r2;
947 
948  if (policy1 != NULL)
949  {
950  if (policy2 == NULL)
951  return false;
952 
953  if (policy1->polcmd != policy2->polcmd)
954  return false;
955  if (policy1->hassublinks != policy2->hassublinks)
956  return false;
957  if (strcmp(policy1->policy_name, policy2->policy_name) != 0)
958  return false;
959  if (ARR_DIMS(policy1->roles)[0] != ARR_DIMS(policy2->roles)[0])
960  return false;
961 
962  r1 = (Oid *) ARR_DATA_PTR(policy1->roles);
963  r2 = (Oid *) ARR_DATA_PTR(policy2->roles);
964 
965  for (i = 0; i < ARR_DIMS(policy1->roles)[0]; i++)
966  {
967  if (r1[i] != r2[i])
968  return false;
969  }
970 
971  if (!equal(policy1->qual, policy2->qual))
972  return false;
973  if (!equal(policy1->with_check_qual, policy2->with_check_qual))
974  return false;
975  }
976  else if (policy2 != NULL)
977  return false;
978 
979  return true;
980 }
981 
982 /*
983  * equalRSDesc
984  *
985  * Determine whether two RowSecurityDesc's are equivalent
986  */
987 static bool
989 {
990  ListCell *lc,
991  *rc;
992 
993  if (rsdesc1 == NULL && rsdesc2 == NULL)
994  return true;
995 
996  if ((rsdesc1 != NULL && rsdesc2 == NULL) ||
997  (rsdesc1 == NULL && rsdesc2 != NULL))
998  return false;
999 
1000  if (list_length(rsdesc1->policies) != list_length(rsdesc2->policies))
1001  return false;
1002 
1003  /* RelationBuildRowSecurity should build policies in order */
1004  forboth(lc, rsdesc1->policies, rc, rsdesc2->policies)
1005  {
1008 
1009  if (!equalPolicy(l, r))
1010  return false;
1011  }
1012 
1013  return true;
1014 }
1015 
1016 /*
1017  * RelationBuildDesc
1018  *
1019  * Build a relation descriptor. The caller must hold at least
1020  * AccessShareLock on the target relid.
1021  *
1022  * The new descriptor is inserted into the hash table if insertIt is true.
1023  *
1024  * Returns NULL if no pg_class row could be found for the given relid
1025  * (suggesting we are trying to access a just-deleted relation).
1026  * Any other error is reported via elog.
1027  */
1028 static Relation
1029 RelationBuildDesc(Oid targetRelId, bool insertIt)
1030 {
1031  Relation relation;
1032  Oid relid;
1033  HeapTuple pg_class_tuple;
1034  Form_pg_class relp;
1035 
1036  /*
1037  * This function and its subroutines can allocate a good deal of transient
1038  * data in CurrentMemoryContext. Traditionally we've just leaked that
1039  * data, reasoning that the caller's context is at worst of transaction
1040  * scope, and relcache loads shouldn't happen so often that it's essential
1041  * to recover transient data before end of statement/transaction. However
1042  * that's definitely not true in clobber-cache test builds, and perhaps
1043  * it's not true in other cases.
1044  *
1045  * When cache clobbering is enabled or when forced to by
1046  * RECOVER_RELATION_BUILD_MEMORY=1, arrange to allocate the junk in a
1047  * temporary context that we'll free before returning. Make it a child
1048  * of caller's context so that it will get cleaned up appropriately if
1049  * we error out partway through.
1050  */
1051 #ifdef MAYBE_RECOVER_RELATION_BUILD_MEMORY
1052  MemoryContext tmpcxt = NULL;
1053  MemoryContext oldcxt = NULL;
1054 
1056  {
1058  "RelationBuildDesc workspace",
1060  oldcxt = MemoryContextSwitchTo(tmpcxt);
1061  }
1062 #endif
1063 
1064  /*
1065  * find the tuple in pg_class corresponding to the given relation id
1066  */
1067  pg_class_tuple = ScanPgRelation(targetRelId, true, false);
1068 
1069  /*
1070  * if no such tuple exists, return NULL
1071  */
1072  if (!HeapTupleIsValid(pg_class_tuple))
1073  {
1074 #ifdef MAYBE_RECOVER_RELATION_BUILD_MEMORY
1075  if (tmpcxt)
1076  {
1077  /* Return to caller's context, and blow away the temporary context */
1078  MemoryContextSwitchTo(oldcxt);
1079  MemoryContextDelete(tmpcxt);
1080  }
1081 #endif
1082  return NULL;
1083  }
1084 
1085  /*
1086  * get information from the pg_class_tuple
1087  */
1088  relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
1089  relid = relp->oid;
1090  Assert(relid == targetRelId);
1091 
1092  /*
1093  * allocate storage for the relation descriptor, and copy pg_class_tuple
1094  * to relation->rd_rel.
1095  */
1096  relation = AllocateRelationDesc(relp);
1097 
1098  /*
1099  * initialize the relation's relation id (relation->rd_id)
1100  */
1101  RelationGetRelid(relation) = relid;
1102 
1103  /*
1104  * Normal relations are not nailed into the cache. Since we don't flush
1105  * new relations, it won't be new. It could be temp though.
1106  */
1107  relation->rd_refcnt = 0;
1108  relation->rd_isnailed = false;
1113  switch (relation->rd_rel->relpersistence)
1114  {
1115  case RELPERSISTENCE_UNLOGGED:
1116  case RELPERSISTENCE_PERMANENT:
1117  relation->rd_backend = InvalidBackendId;
1118  relation->rd_islocaltemp = false;
1119  break;
1120  case RELPERSISTENCE_TEMP:
1121  if (isTempOrTempToastNamespace(relation->rd_rel->relnamespace))
1122  {
1123  relation->rd_backend = BackendIdForTempRelations();
1124  relation->rd_islocaltemp = true;
1125  }
1126  else
1127  {
1128  /*
1129  * If it's a temp table, but not one of ours, we have to use
1130  * the slow, grotty method to figure out the owning backend.
1131  *
1132  * Note: it's possible that rd_backend gets set to MyBackendId
1133  * here, in case we are looking at a pg_class entry left over
1134  * from a crashed backend that coincidentally had the same
1135  * BackendId we're using. We should *not* consider such a
1136  * table to be "ours"; this is why we need the separate
1137  * rd_islocaltemp flag. The pg_class entry will get flushed
1138  * if/when we clean out the corresponding temp table namespace
1139  * in preparation for using it.
1140  */
1141  relation->rd_backend =
1142  GetTempNamespaceBackendId(relation->rd_rel->relnamespace);
1143  Assert(relation->rd_backend != InvalidBackendId);
1144  relation->rd_islocaltemp = false;
1145  }
1146  break;
1147  default:
1148  elog(ERROR, "invalid relpersistence: %c",
1149  relation->rd_rel->relpersistence);
1150  break;
1151  }
1152 
1153  /*
1154  * initialize the tuple descriptor (relation->rd_att).
1155  */
1156  RelationBuildTupleDesc(relation);
1157 
1158  /*
1159  * Fetch rules and triggers that affect this relation
1160  */
1161  if (relation->rd_rel->relhasrules)
1162  RelationBuildRuleLock(relation);
1163  else
1164  {
1165  relation->rd_rules = NULL;
1166  relation->rd_rulescxt = NULL;
1167  }
1168 
1169  if (relation->rd_rel->relhastriggers)
1170  RelationBuildTriggers(relation);
1171  else
1172  relation->trigdesc = NULL;
1173 
1174  if (relation->rd_rel->relrowsecurity)
1175  RelationBuildRowSecurity(relation);
1176  else
1177  relation->rd_rsdesc = NULL;
1178 
1179  /* foreign key data is not loaded till asked for */
1180  relation->rd_fkeylist = NIL;
1181  relation->rd_fkeyvalid = false;
1182 
1183  /* partitioning data is not loaded till asked for */
1184  relation->rd_partkey = NULL;
1185  relation->rd_partkeycxt = NULL;
1186  relation->rd_partdesc = NULL;
1187  relation->rd_pdcxt = NULL;
1188  relation->rd_partcheck = NIL;
1189  relation->rd_partcheckvalid = false;
1190  relation->rd_partcheckcxt = NULL;
1191 
1192  /*
1193  * initialize access method information
1194  */
1195  switch (relation->rd_rel->relkind)
1196  {
1197  case RELKIND_INDEX:
1198  case RELKIND_PARTITIONED_INDEX:
1199  Assert(relation->rd_rel->relam != InvalidOid);
1200  RelationInitIndexAccessInfo(relation);
1201  break;
1202  case RELKIND_RELATION:
1203  case RELKIND_TOASTVALUE:
1204  case RELKIND_MATVIEW:
1205  Assert(relation->rd_rel->relam != InvalidOid);
1207  break;
1208  case RELKIND_SEQUENCE:
1209  Assert(relation->rd_rel->relam == InvalidOid);
1211  break;
1212  case RELKIND_VIEW:
1213  case RELKIND_COMPOSITE_TYPE:
1214  case RELKIND_FOREIGN_TABLE:
1215  case RELKIND_PARTITIONED_TABLE:
1216  Assert(relation->rd_rel->relam == InvalidOid);
1217  break;
1218  }
1219 
1220  /* extract reloptions if any */
1221  RelationParseRelOptions(relation, pg_class_tuple);
1222 
1223  /*
1224  * initialize the relation lock manager information
1225  */
1226  RelationInitLockInfo(relation); /* see lmgr.c */
1227 
1228  /*
1229  * initialize physical addressing information for the relation
1230  */
1231  RelationInitPhysicalAddr(relation);
1232 
1233  /* make sure relation is marked as having no open file yet */
1234  relation->rd_smgr = NULL;
1235 
1236  /*
1237  * now we can free the memory allocated for pg_class_tuple
1238  */
1239  heap_freetuple(pg_class_tuple);
1240 
1241  /*
1242  * Insert newly created relation into relcache hash table, if requested.
1243  *
1244  * There is one scenario in which we might find a hashtable entry already
1245  * present, even though our caller failed to find it: if the relation is a
1246  * system catalog or index that's used during relcache load, we might have
1247  * recursively created the same relcache entry during the preceding steps.
1248  * So allow RelationCacheInsert to delete any already-present relcache
1249  * entry for the same OID. The already-present entry should have refcount
1250  * zero (else somebody forgot to close it); in the event that it doesn't,
1251  * we'll elog a WARNING and leak the already-present entry.
1252  */
1253  if (insertIt)
1254  RelationCacheInsert(relation, true);
1255 
1256  /* It's fully valid */
1257  relation->rd_isvalid = true;
1258 
1259 #ifdef MAYBE_RECOVER_RELATION_BUILD_MEMORY
1260  if (tmpcxt)
1261  {
1262  /* Return to caller's context, and blow away the temporary context */
1263  MemoryContextSwitchTo(oldcxt);
1264  MemoryContextDelete(tmpcxt);
1265  }
1266 #endif
1267 
1268  return relation;
1269 }
1270 
1271 /*
1272  * Initialize the physical addressing info (RelFileNode) for a relcache entry
1273  *
1274  * Note: at the physical level, relations in the pg_global tablespace must
1275  * be treated as shared, even if relisshared isn't set. Hence we do not
1276  * look at relisshared here.
1277  */
1278 static void
1280 {
1281  Oid oldnode = relation->rd_node.relNode;
1282 
1283  /* these relations kinds never have storage */
1284  if (!RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
1285  return;
1286 
1287  if (relation->rd_rel->reltablespace)
1288  relation->rd_node.spcNode = relation->rd_rel->reltablespace;
1289  else
1290  relation->rd_node.spcNode = MyDatabaseTableSpace;
1291  if (relation->rd_node.spcNode == GLOBALTABLESPACE_OID)
1292  relation->rd_node.dbNode = InvalidOid;
1293  else
1294  relation->rd_node.dbNode = MyDatabaseId;
1295 
1296  if (relation->rd_rel->relfilenode)
1297  {
1298  /*
1299  * Even if we are using a decoding snapshot that doesn't represent the
1300  * current state of the catalog we need to make sure the filenode
1301  * points to the current file since the older file will be gone (or
1302  * truncated). The new file will still contain older rows so lookups
1303  * in them will work correctly. This wouldn't work correctly if
1304  * rewrites were allowed to change the schema in an incompatible way,
1305  * but those are prevented both on catalog tables and on user tables
1306  * declared as additional catalog tables.
1307  */
1310  && IsTransactionState())
1311  {
1312  HeapTuple phys_tuple;
1313  Form_pg_class physrel;
1314 
1315  phys_tuple = ScanPgRelation(RelationGetRelid(relation),
1316  RelationGetRelid(relation) != ClassOidIndexId,
1317  true);
1318  if (!HeapTupleIsValid(phys_tuple))
1319  elog(ERROR, "could not find pg_class entry for %u",
1320  RelationGetRelid(relation));
1321  physrel = (Form_pg_class) GETSTRUCT(phys_tuple);
1322 
1323  relation->rd_rel->reltablespace = physrel->reltablespace;
1324  relation->rd_rel->relfilenode = physrel->relfilenode;
1325  heap_freetuple(phys_tuple);
1326  }
1327 
1328  relation->rd_node.relNode = relation->rd_rel->relfilenode;
1329  }
1330  else
1331  {
1332  /* Consult the relation mapper */
1333  relation->rd_node.relNode =
1334  RelationMapOidToFilenode(relation->rd_id,
1335  relation->rd_rel->relisshared);
1336  if (!OidIsValid(relation->rd_node.relNode))
1337  elog(ERROR, "could not find relation mapping for relation \"%s\", OID %u",
1338  RelationGetRelationName(relation), relation->rd_id);
1339  }
1340 
1341  /*
1342  * For RelationNeedsWAL() to answer correctly on parallel workers, restore
1343  * rd_firstRelfilenodeSubid. No subtransactions start or end while in
1344  * parallel mode, so the specific SubTransactionId does not matter.
1345  */
1346  if (IsParallelWorker() && oldnode != relation->rd_node.relNode)
1347  {
1348  if (RelFileNodeSkippingWAL(relation->rd_node))
1350  else
1352  }
1353 }
1354 
1355 /*
1356  * Fill in the IndexAmRoutine for an index relation.
1357  *
1358  * relation's rd_amhandler and rd_indexcxt must be valid already.
1359  */
1360 static void
1362 {
1363  IndexAmRoutine *cached,
1364  *tmp;
1365 
1366  /*
1367  * Call the amhandler in current, short-lived memory context, just in case
1368  * it leaks anything (it probably won't, but let's be paranoid).
1369  */
1370  tmp = GetIndexAmRoutine(relation->rd_amhandler);
1371 
1372  /* OK, now transfer the data into relation's rd_indexcxt. */
1373  cached = (IndexAmRoutine *) MemoryContextAlloc(relation->rd_indexcxt,
1374  sizeof(IndexAmRoutine));
1375  memcpy(cached, tmp, sizeof(IndexAmRoutine));
1376  relation->rd_indam = cached;
1377 
1378  pfree(tmp);
1379 }
1380 
1381 /*
1382  * Initialize index-access-method support data for an index relation
1383  */
1384 void
1386 {
1387  HeapTuple tuple;
1388  Form_pg_am aform;
1389  Datum indcollDatum;
1390  Datum indclassDatum;
1391  Datum indoptionDatum;
1392  bool isnull;
1393  oidvector *indcoll;
1394  oidvector *indclass;
1395  int2vector *indoption;
1396  MemoryContext indexcxt;
1397  MemoryContext oldcontext;
1398  int indnatts;
1399  int indnkeyatts;
1400  uint16 amsupport;
1401 
1402  /*
1403  * Make a copy of the pg_index entry for the index. Since pg_index
1404  * contains variable-length and possibly-null fields, we have to do this
1405  * honestly rather than just treating it as a Form_pg_index struct.
1406  */
1407  tuple = SearchSysCache1(INDEXRELID,
1408  ObjectIdGetDatum(RelationGetRelid(relation)));
1409  if (!HeapTupleIsValid(tuple))
1410  elog(ERROR, "cache lookup failed for index %u",
1411  RelationGetRelid(relation));
1413  relation->rd_indextuple = heap_copytuple(tuple);
1414  relation->rd_index = (Form_pg_index) GETSTRUCT(relation->rd_indextuple);
1415  MemoryContextSwitchTo(oldcontext);
1416  ReleaseSysCache(tuple);
1417 
1418  /*
1419  * Look up the index's access method, save the OID of its handler function
1420  */
1421  tuple = SearchSysCache1(AMOID, ObjectIdGetDatum(relation->rd_rel->relam));
1422  if (!HeapTupleIsValid(tuple))
1423  elog(ERROR, "cache lookup failed for access method %u",
1424  relation->rd_rel->relam);
1425  aform = (Form_pg_am) GETSTRUCT(tuple);
1426  relation->rd_amhandler = aform->amhandler;
1427  ReleaseSysCache(tuple);
1428 
1429  indnatts = RelationGetNumberOfAttributes(relation);
1430  if (indnatts != IndexRelationGetNumberOfAttributes(relation))
1431  elog(ERROR, "relnatts disagrees with indnatts for index %u",
1432  RelationGetRelid(relation));
1433  indnkeyatts = IndexRelationGetNumberOfKeyAttributes(relation);
1434 
1435  /*
1436  * Make the private context to hold index access info. The reason we need
1437  * a context, and not just a couple of pallocs, is so that we won't leak
1438  * any subsidiary info attached to fmgr lookup records.
1439  */
1441  "index info",
1443  relation->rd_indexcxt = indexcxt;
1445  RelationGetRelationName(relation));
1446 
1447  /*
1448  * Now we can fetch the index AM's API struct
1449  */
1450  InitIndexAmRoutine(relation);
1451 
1452  /*
1453  * Allocate arrays to hold data. Opclasses are not used for included
1454  * columns, so allocate them for indnkeyatts only.
1455  */
1456  relation->rd_opfamily = (Oid *)
1457  MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1458  relation->rd_opcintype = (Oid *)
1459  MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1460 
1461  amsupport = relation->rd_indam->amsupport;
1462  if (amsupport > 0)
1463  {
1464  int nsupport = indnatts * amsupport;
1465 
1466  relation->rd_support = (RegProcedure *)
1467  MemoryContextAllocZero(indexcxt, nsupport * sizeof(RegProcedure));
1468  relation->rd_supportinfo = (FmgrInfo *)
1469  MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
1470  }
1471  else
1472  {
1473  relation->rd_support = NULL;
1474  relation->rd_supportinfo = NULL;
1475  }
1476 
1477  relation->rd_indcollation = (Oid *)
1478  MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1479 
1480  relation->rd_indoption = (int16 *)
1481  MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(int16));
1482 
1483  /*
1484  * indcollation cannot be referenced directly through the C struct,
1485  * because it comes after the variable-width indkey field. Must extract
1486  * the datum the hard way...
1487  */
1488  indcollDatum = fastgetattr(relation->rd_indextuple,
1489  Anum_pg_index_indcollation,
1491  &isnull);
1492  Assert(!isnull);
1493  indcoll = (oidvector *) DatumGetPointer(indcollDatum);
1494  memcpy(relation->rd_indcollation, indcoll->values, indnkeyatts * sizeof(Oid));
1495 
1496  /*
1497  * indclass cannot be referenced directly through the C struct, because it
1498  * comes after the variable-width indkey field. Must extract the datum
1499  * the hard way...
1500  */
1501  indclassDatum = fastgetattr(relation->rd_indextuple,
1502  Anum_pg_index_indclass,
1504  &isnull);
1505  Assert(!isnull);
1506  indclass = (oidvector *) DatumGetPointer(indclassDatum);
1507 
1508  /*
1509  * Fill the support procedure OID array, as well as the info about
1510  * opfamilies and opclass input types. (aminfo and supportinfo are left
1511  * as zeroes, and are filled on-the-fly when used)
1512  */
1513  IndexSupportInitialize(indclass, relation->rd_support,
1514  relation->rd_opfamily, relation->rd_opcintype,
1515  amsupport, indnkeyatts);
1516 
1517  /*
1518  * Similarly extract indoption and copy it to the cache entry
1519  */
1520  indoptionDatum = fastgetattr(relation->rd_indextuple,
1521  Anum_pg_index_indoption,
1523  &isnull);
1524  Assert(!isnull);
1525  indoption = (int2vector *) DatumGetPointer(indoptionDatum);
1526  memcpy(relation->rd_indoption, indoption->values, indnkeyatts * sizeof(int16));
1527 
1528  (void) RelationGetIndexAttOptions(relation, false);
1529 
1530  /*
1531  * expressions, predicate, exclusion caches will be filled later
1532  */
1533  relation->rd_indexprs = NIL;
1534  relation->rd_indpred = NIL;
1535  relation->rd_exclops = NULL;
1536  relation->rd_exclprocs = NULL;
1537  relation->rd_exclstrats = NULL;
1538  relation->rd_amcache = NULL;
1539 }
1540 
1541 /*
1542  * IndexSupportInitialize
1543  * Initializes an index's cached opclass information,
1544  * given the index's pg_index.indclass entry.
1545  *
1546  * Data is returned into *indexSupport, *opFamily, and *opcInType,
1547  * which are arrays allocated by the caller.
1548  *
1549  * The caller also passes maxSupportNumber and maxAttributeNumber, since these
1550  * indicate the size of the arrays it has allocated --- but in practice these
1551  * numbers must always match those obtainable from the system catalog entries
1552  * for the index and access method.
1553  */
1554 static void
1556  RegProcedure *indexSupport,
1557  Oid *opFamily,
1558  Oid *opcInType,
1559  StrategyNumber maxSupportNumber,
1560  AttrNumber maxAttributeNumber)
1561 {
1562  int attIndex;
1563 
1564  for (attIndex = 0; attIndex < maxAttributeNumber; attIndex++)
1565  {
1566  OpClassCacheEnt *opcentry;
1567 
1568  if (!OidIsValid(indclass->values[attIndex]))
1569  elog(ERROR, "bogus pg_index tuple");
1570 
1571  /* look up the info for this opclass, using a cache */
1572  opcentry = LookupOpclassInfo(indclass->values[attIndex],
1573  maxSupportNumber);
1574 
1575  /* copy cached data into relcache entry */
1576  opFamily[attIndex] = opcentry->opcfamily;
1577  opcInType[attIndex] = opcentry->opcintype;
1578  if (maxSupportNumber > 0)
1579  memcpy(&indexSupport[attIndex * maxSupportNumber],
1580  opcentry->supportProcs,
1581  maxSupportNumber * sizeof(RegProcedure));
1582  }
1583 }
1584 
1585 /*
1586  * LookupOpclassInfo
1587  *
1588  * This routine maintains a per-opclass cache of the information needed
1589  * by IndexSupportInitialize(). This is more efficient than relying on
1590  * the catalog cache, because we can load all the info about a particular
1591  * opclass in a single indexscan of pg_amproc.
1592  *
1593  * The information from pg_am about expected range of support function
1594  * numbers is passed in, rather than being looked up, mainly because the
1595  * caller will have it already.
1596  *
1597  * Note there is no provision for flushing the cache. This is OK at the
1598  * moment because there is no way to ALTER any interesting properties of an
1599  * existing opclass --- all you can do is drop it, which will result in
1600  * a useless but harmless dead entry in the cache. To support altering
1601  * opclass membership (not the same as opfamily membership!), we'd need to
1602  * be able to flush this cache as well as the contents of relcache entries
1603  * for indexes.
1604  */
1605 static OpClassCacheEnt *
1606 LookupOpclassInfo(Oid operatorClassOid,
1607  StrategyNumber numSupport)
1608 {
1609  OpClassCacheEnt *opcentry;
1610  bool found;
1611  Relation rel;
1612  SysScanDesc scan;
1613  ScanKeyData skey[3];
1614  HeapTuple htup;
1615  bool indexOK;
1616 
1617  if (OpClassCache == NULL)
1618  {
1619  /* First time through: initialize the opclass cache */
1620  HASHCTL ctl;
1621 
1622  ctl.keysize = sizeof(Oid);
1623  ctl.entrysize = sizeof(OpClassCacheEnt);
1624  OpClassCache = hash_create("Operator class cache", 64,
1625  &ctl, HASH_ELEM | HASH_BLOBS);
1626 
1627  /* Also make sure CacheMemoryContext exists */
1628  if (!CacheMemoryContext)
1630  }
1631 
1632  opcentry = (OpClassCacheEnt *) hash_search(OpClassCache,
1633  (void *) &operatorClassOid,
1634  HASH_ENTER, &found);
1635 
1636  if (!found)
1637  {
1638  /* Need to allocate memory for new entry */
1639  opcentry->valid = false; /* until known OK */
1640  opcentry->numSupport = numSupport;
1641 
1642  if (numSupport > 0)
1643  opcentry->supportProcs = (RegProcedure *)
1645  (numSupport + 1) * sizeof(RegProcedure));
1646  else
1647  opcentry->supportProcs = NULL;
1648  }
1649  else
1650  {
1651  Assert(numSupport == opcentry->numSupport);
1652  }
1653 
1654  /*
1655  * When testing for cache-flush hazards, we intentionally disable the
1656  * operator class cache and force reloading of the info on each call. This
1657  * is helpful because we want to test the case where a cache flush occurs
1658  * while we are loading the info, and it's very hard to provoke that if
1659  * this happens only once per opclass per backend.
1660  */
1661 #ifdef CLOBBER_CACHE_ENABLED
1663  opcentry->valid = false;
1664 #endif
1665 
1666  if (opcentry->valid)
1667  return opcentry;
1668 
1669  /*
1670  * Need to fill in new entry.
1671  *
1672  * To avoid infinite recursion during startup, force heap scans if we're
1673  * looking up info for the opclasses used by the indexes we would like to
1674  * reference here.
1675  */
1676  indexOK = criticalRelcachesBuilt ||
1677  (operatorClassOid != OID_BTREE_OPS_OID &&
1678  operatorClassOid != INT2_BTREE_OPS_OID);
1679 
1680  /*
1681  * We have to fetch the pg_opclass row to determine its opfamily and
1682  * opcintype, which are needed to look up related operators and functions.
1683  * It'd be convenient to use the syscache here, but that probably doesn't
1684  * work while bootstrapping.
1685  */
1686  ScanKeyInit(&skey[0],
1687  Anum_pg_opclass_oid,
1688  BTEqualStrategyNumber, F_OIDEQ,
1689  ObjectIdGetDatum(operatorClassOid));
1690  rel = table_open(OperatorClassRelationId, AccessShareLock);
1691  scan = systable_beginscan(rel, OpclassOidIndexId, indexOK,
1692  NULL, 1, skey);
1693 
1694  if (HeapTupleIsValid(htup = systable_getnext(scan)))
1695  {
1696  Form_pg_opclass opclassform = (Form_pg_opclass) GETSTRUCT(htup);
1697 
1698  opcentry->opcfamily = opclassform->opcfamily;
1699  opcentry->opcintype = opclassform->opcintype;
1700  }
1701  else
1702  elog(ERROR, "could not find tuple for opclass %u", operatorClassOid);
1703 
1704  systable_endscan(scan);
1706 
1707  /*
1708  * Scan pg_amproc to obtain support procs for the opclass. We only fetch
1709  * the default ones (those with lefttype = righttype = opcintype).
1710  */
1711  if (numSupport > 0)
1712  {
1713  ScanKeyInit(&skey[0],
1714  Anum_pg_amproc_amprocfamily,
1715  BTEqualStrategyNumber, F_OIDEQ,
1716  ObjectIdGetDatum(opcentry->opcfamily));
1717  ScanKeyInit(&skey[1],
1718  Anum_pg_amproc_amproclefttype,
1719  BTEqualStrategyNumber, F_OIDEQ,
1720  ObjectIdGetDatum(opcentry->opcintype));
1721  ScanKeyInit(&skey[2],
1722  Anum_pg_amproc_amprocrighttype,
1723  BTEqualStrategyNumber, F_OIDEQ,
1724  ObjectIdGetDatum(opcentry->opcintype));
1725  rel = table_open(AccessMethodProcedureRelationId, AccessShareLock);
1726  scan = systable_beginscan(rel, AccessMethodProcedureIndexId, indexOK,
1727  NULL, 3, skey);
1728 
1729  while (HeapTupleIsValid(htup = systable_getnext(scan)))
1730  {
1731  Form_pg_amproc amprocform = (Form_pg_amproc) GETSTRUCT(htup);
1732 
1733  if (amprocform->amprocnum <= 0 ||
1734  (StrategyNumber) amprocform->amprocnum > numSupport)
1735  elog(ERROR, "invalid amproc number %d for opclass %u",
1736  amprocform->amprocnum, operatorClassOid);
1737 
1738  opcentry->supportProcs[amprocform->amprocnum - 1] =
1739  amprocform->amproc;
1740  }
1741 
1742  systable_endscan(scan);
1744  }
1745 
1746  opcentry->valid = true;
1747  return opcentry;
1748 }
1749 
1750 /*
1751  * Fill in the TableAmRoutine for a relation
1752  *
1753  * relation's rd_amhandler must be valid already.
1754  */
1755 static void
1757 {
1758  relation->rd_tableam = GetTableAmRoutine(relation->rd_amhandler);
1759 }
1760 
1761 /*
1762  * Initialize table access method support for a table like relation
1763  */
1764 void
1766 {
1767  HeapTuple tuple;
1768  Form_pg_am aform;
1769 
1770  if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
1771  {
1772  /*
1773  * Sequences are currently accessed like heap tables, but it doesn't
1774  * seem prudent to show that in the catalog. So just overwrite it
1775  * here.
1776  */
1777  relation->rd_amhandler = F_HEAP_TABLEAM_HANDLER;
1778  }
1779  else if (IsCatalogRelation(relation))
1780  {
1781  /*
1782  * Avoid doing a syscache lookup for catalog tables.
1783  */
1784  Assert(relation->rd_rel->relam == HEAP_TABLE_AM_OID);
1785  relation->rd_amhandler = F_HEAP_TABLEAM_HANDLER;
1786  }
1787  else
1788  {
1789  /*
1790  * Look up the table access method, save the OID of its handler
1791  * function.
1792  */
1793  Assert(relation->rd_rel->relam != InvalidOid);
1794  tuple = SearchSysCache1(AMOID,
1795  ObjectIdGetDatum(relation->rd_rel->relam));
1796  if (!HeapTupleIsValid(tuple))
1797  elog(ERROR, "cache lookup failed for access method %u",
1798  relation->rd_rel->relam);
1799  aform = (Form_pg_am) GETSTRUCT(tuple);
1800  relation->rd_amhandler = aform->amhandler;
1801  ReleaseSysCache(tuple);
1802  }
1803 
1804  /*
1805  * Now we can fetch the table AM's API struct
1806  */
1807  InitTableAmRoutine(relation);
1808 }
1809 
1810 /*
1811  * formrdesc
1812  *
1813  * This is a special cut-down version of RelationBuildDesc(),
1814  * used while initializing the relcache.
1815  * The relation descriptor is built just from the supplied parameters,
1816  * without actually looking at any system table entries. We cheat
1817  * quite a lot since we only need to work for a few basic system
1818  * catalogs.
1819  *
1820  * The catalogs this is used for can't have constraints (except attnotnull),
1821  * default values, rules, or triggers, since we don't cope with any of that.
1822  * (Well, actually, this only matters for properties that need to be valid
1823  * during bootstrap or before RelationCacheInitializePhase3 runs, and none of
1824  * these properties matter then...)
1825  *
1826  * NOTE: we assume we are already switched into CacheMemoryContext.
1827  */
1828 static void
1829 formrdesc(const char *relationName, Oid relationReltype,
1830  bool isshared,
1831  int natts, const FormData_pg_attribute *attrs)
1832 {
1833  Relation relation;
1834  int i;
1835  bool has_not_null;
1836 
1837  /*
1838  * allocate new relation desc, clear all fields of reldesc
1839  */
1840  relation = (Relation) palloc0(sizeof(RelationData));
1841 
1842  /* make sure relation is marked as having no open file yet */
1843  relation->rd_smgr = NULL;
1844 
1845  /*
1846  * initialize reference count: 1 because it is nailed in cache
1847  */
1848  relation->rd_refcnt = 1;
1849 
1850  /*
1851  * all entries built with this routine are nailed-in-cache; none are for
1852  * new or temp relations.
1853  */
1854  relation->rd_isnailed = true;
1859  relation->rd_backend = InvalidBackendId;
1860  relation->rd_islocaltemp = false;
1861 
1862  /*
1863  * initialize relation tuple form
1864  *
1865  * The data we insert here is pretty incomplete/bogus, but it'll serve to
1866  * get us launched. RelationCacheInitializePhase3() will read the real
1867  * data from pg_class and replace what we've done here. Note in
1868  * particular that relowner is left as zero; this cues
1869  * RelationCacheInitializePhase3 that the real data isn't there yet.
1870  */
1872 
1873  namestrcpy(&relation->rd_rel->relname, relationName);
1874  relation->rd_rel->relnamespace = PG_CATALOG_NAMESPACE;
1875  relation->rd_rel->reltype = relationReltype;
1876 
1877  /*
1878  * It's important to distinguish between shared and non-shared relations,
1879  * even at bootstrap time, to make sure we know where they are stored.
1880  */
1881  relation->rd_rel->relisshared = isshared;
1882  if (isshared)
1883  relation->rd_rel->reltablespace = GLOBALTABLESPACE_OID;
1884 
1885  /* formrdesc is used only for permanent relations */
1886  relation->rd_rel->relpersistence = RELPERSISTENCE_PERMANENT;
1887 
1888  /* ... and they're always populated, too */
1889  relation->rd_rel->relispopulated = true;
1890 
1891  relation->rd_rel->relreplident = REPLICA_IDENTITY_NOTHING;
1892  relation->rd_rel->relpages = 0;
1893  relation->rd_rel->reltuples = -1;
1894  relation->rd_rel->relallvisible = 0;
1895  relation->rd_rel->relkind = RELKIND_RELATION;
1896  relation->rd_rel->relnatts = (int16) natts;
1897  relation->rd_rel->relam = HEAP_TABLE_AM_OID;
1898 
1899  /*
1900  * initialize attribute tuple form
1901  *
1902  * Unlike the case with the relation tuple, this data had better be right
1903  * because it will never be replaced. The data comes from
1904  * src/include/catalog/ headers via genbki.pl.
1905  */
1906  relation->rd_att = CreateTemplateTupleDesc(natts);
1907  relation->rd_att->tdrefcount = 1; /* mark as refcounted */
1908 
1909  relation->rd_att->tdtypeid = relationReltype;
1910  relation->rd_att->tdtypmod = -1; /* just to be sure */
1911 
1912  /*
1913  * initialize tuple desc info
1914  */
1915  has_not_null = false;
1916  for (i = 0; i < natts; i++)
1917  {
1918  memcpy(TupleDescAttr(relation->rd_att, i),
1919  &attrs[i],
1921  has_not_null |= attrs[i].attnotnull;
1922  /* make sure attcacheoff is valid */
1923  TupleDescAttr(relation->rd_att, i)->attcacheoff = -1;
1924  }
1925 
1926  /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
1927  TupleDescAttr(relation->rd_att, 0)->attcacheoff = 0;
1928 
1929  /* mark not-null status */
1930  if (has_not_null)
1931  {
1932  TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
1933 
1934  constr->has_not_null = true;
1935  relation->rd_att->constr = constr;
1936  }
1937 
1938  /*
1939  * initialize relation id from info in att array (my, this is ugly)
1940  */
1941  RelationGetRelid(relation) = TupleDescAttr(relation->rd_att, 0)->attrelid;
1942 
1943  /*
1944  * All relations made with formrdesc are mapped. This is necessarily so
1945  * because there is no other way to know what filenode they currently
1946  * have. In bootstrap mode, add them to the initial relation mapper data,
1947  * specifying that the initial filenode is the same as the OID.
1948  */
1949  relation->rd_rel->relfilenode = InvalidOid;
1952  RelationGetRelid(relation),
1953  isshared, true);
1954 
1955  /*
1956  * initialize the relation lock manager information
1957  */
1958  RelationInitLockInfo(relation); /* see lmgr.c */
1959 
1960  /*
1961  * initialize physical addressing information for the relation
1962  */
1963  RelationInitPhysicalAddr(relation);
1964 
1965  /*
1966  * initialize the table am handler
1967  */
1968  relation->rd_rel->relam = HEAP_TABLE_AM_OID;
1969  relation->rd_tableam = GetHeapamTableAmRoutine();
1970 
1971  /*
1972  * initialize the rel-has-index flag, using hardwired knowledge
1973  */
1975  {
1976  /* In bootstrap mode, we have no indexes */
1977  relation->rd_rel->relhasindex = false;
1978  }
1979  else
1980  {
1981  /* Otherwise, all the rels formrdesc is used for have indexes */
1982  relation->rd_rel->relhasindex = true;
1983  }
1984 
1985  /*
1986  * add new reldesc to relcache
1987  */
1988  RelationCacheInsert(relation, false);
1989 
1990  /* It's fully valid */
1991  relation->rd_isvalid = true;
1992 }
1993 
1994 
1995 /* ----------------------------------------------------------------
1996  * Relation Descriptor Lookup Interface
1997  * ----------------------------------------------------------------
1998  */
1999 
2000 /*
2001  * RelationIdGetRelation
2002  *
2003  * Lookup a reldesc by OID; make one if not already in cache.
2004  *
2005  * Returns NULL if no pg_class row could be found for the given relid
2006  * (suggesting we are trying to access a just-deleted relation).
2007  * Any other error is reported via elog.
2008  *
2009  * NB: caller should already have at least AccessShareLock on the
2010  * relation ID, else there are nasty race conditions.
2011  *
2012  * NB: relation ref count is incremented, or set to 1 if new entry.
2013  * Caller should eventually decrement count. (Usually,
2014  * that happens by calling RelationClose().)
2015  */
2016 Relation
2018 {
2019  Relation rd;
2020 
2021  /* Make sure we're in an xact, even if this ends up being a cache hit */
2023 
2024  /*
2025  * first try to find reldesc in the cache
2026  */
2027  RelationIdCacheLookup(relationId, rd);
2028 
2029  if (RelationIsValid(rd))
2030  {
2031  /* return NULL for dropped relations */
2033  {
2034  Assert(!rd->rd_isvalid);
2035  return NULL;
2036  }
2037 
2039  /* revalidate cache entry if necessary */
2040  if (!rd->rd_isvalid)
2041  {
2042  /*
2043  * Indexes only have a limited number of possible schema changes,
2044  * and we don't want to use the full-blown procedure because it's
2045  * a headache for indexes that reload itself depends on.
2046  */
2047  if (rd->rd_rel->relkind == RELKIND_INDEX ||
2048  rd->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
2050  else
2051  RelationClearRelation(rd, true);
2052 
2053  /*
2054  * Normally entries need to be valid here, but before the relcache
2055  * has been initialized, not enough infrastructure exists to
2056  * perform pg_class lookups. The structure of such entries doesn't
2057  * change, but we still want to update the rd_rel entry. So
2058  * rd_isvalid = false is left in place for a later lookup.
2059  */
2060  Assert(rd->rd_isvalid ||
2062  }
2063  return rd;
2064  }
2065 
2066  /*
2067  * no reldesc in the cache, so have RelationBuildDesc() build one and add
2068  * it.
2069  */
2070  rd = RelationBuildDesc(relationId, true);
2071  if (RelationIsValid(rd))
2073  return rd;
2074 }
2075 
2076 /* ----------------------------------------------------------------
2077  * cache invalidation support routines
2078  * ----------------------------------------------------------------
2079  */
2080 
2081 /*
2082  * RelationIncrementReferenceCount
2083  * Increments relation reference count.
2084  *
2085  * Note: bootstrap mode has its own weird ideas about relation refcount
2086  * behavior; we ought to fix it someday, but for now, just disable
2087  * reference count ownership tracking in bootstrap mode.
2088  */
2089 void
2091 {
2093  rel->rd_refcnt += 1;
2096 }
2097 
2098 /*
2099  * RelationDecrementReferenceCount
2100  * Decrements relation reference count.
2101  */
2102 void
2104 {
2105  Assert(rel->rd_refcnt > 0);
2106  rel->rd_refcnt -= 1;
2109 }
2110 
2111 /*
2112  * RelationClose - close an open relation
2113  *
2114  * Actually, we just decrement the refcount.
2115  *
2116  * NOTE: if compiled with -DRELCACHE_FORCE_RELEASE then relcache entries
2117  * will be freed as soon as their refcount goes to zero. In combination
2118  * with aset.c's CLOBBER_FREED_MEMORY option, this provides a good test
2119  * to catch references to already-released relcache entries. It slows
2120  * things down quite a bit, however.
2121  */
2122 void
2124 {
2125  /* Note: no locking manipulations needed */
2127 
2128  /*
2129  * If the relation is no longer open in this session, we can clean up any
2130  * stale partition descriptors it has. This is unlikely, so check to see
2131  * if there are child contexts before expending a call to mcxt.c.
2132  */
2133  if (RelationHasReferenceCountZero(relation) &&
2134  relation->rd_pdcxt != NULL &&
2135  relation->rd_pdcxt->firstchild != NULL)
2137 
2138 #ifdef RELCACHE_FORCE_RELEASE
2139  if (RelationHasReferenceCountZero(relation) &&
2140  relation->rd_createSubid == InvalidSubTransactionId &&
2142  RelationClearRelation(relation, false);
2143 #endif
2144 }
2145 
2146 /*
2147  * RelationReloadIndexInfo - reload minimal information for an open index
2148  *
2149  * This function is used only for indexes. A relcache inval on an index
2150  * can mean that its pg_class or pg_index row changed. There are only
2151  * very limited changes that are allowed to an existing index's schema,
2152  * so we can update the relcache entry without a complete rebuild; which
2153  * is fortunate because we can't rebuild an index entry that is "nailed"
2154  * and/or in active use. We support full replacement of the pg_class row,
2155  * as well as updates of a few simple fields of the pg_index row.
2156  *
2157  * We can't necessarily reread the catalog rows right away; we might be
2158  * in a failed transaction when we receive the SI notification. If so,
2159  * RelationClearRelation just marks the entry as invalid by setting
2160  * rd_isvalid to false. This routine is called to fix the entry when it
2161  * is next needed.
2162  *
2163  * We assume that at the time we are called, we have at least AccessShareLock
2164  * on the target index. (Note: in the calls from RelationClearRelation,
2165  * this is legitimate because we know the rel has positive refcount.)
2166  *
2167  * If the target index is an index on pg_class or pg_index, we'd better have
2168  * previously gotten at least AccessShareLock on its underlying catalog,
2169  * else we are at risk of deadlock against someone trying to exclusive-lock
2170  * the heap and index in that order. This is ensured in current usage by
2171  * only applying this to indexes being opened or having positive refcount.
2172  */
2173 static void
2175 {
2176  bool indexOK;
2177  HeapTuple pg_class_tuple;
2178  Form_pg_class relp;
2179 
2180  /* Should be called only for invalidated, live indexes */
2181  Assert((relation->rd_rel->relkind == RELKIND_INDEX ||
2182  relation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX) &&
2183  !relation->rd_isvalid &&
2185 
2186  /* Ensure it's closed at smgr level */
2187  RelationCloseSmgr(relation);
2188 
2189  /* Must free any AM cached data upon relcache flush */
2190  if (relation->rd_amcache)
2191  pfree(relation->rd_amcache);
2192  relation->rd_amcache = NULL;
2193 
2194  /*
2195  * If it's a shared index, we might be called before backend startup has
2196  * finished selecting a database, in which case we have no way to read
2197  * pg_class yet. However, a shared index can never have any significant
2198  * schema updates, so it's okay to ignore the invalidation signal. Just
2199  * mark it valid and return without doing anything more.
2200  */
2201  if (relation->rd_rel->relisshared && !criticalRelcachesBuilt)
2202  {
2203  relation->rd_isvalid = true;
2204  return;
2205  }
2206 
2207  /*
2208  * Read the pg_class row
2209  *
2210  * Don't try to use an indexscan of pg_class_oid_index to reload the info
2211  * for pg_class_oid_index ...
2212  */
2213  indexOK = (RelationGetRelid(relation) != ClassOidIndexId);
2214  pg_class_tuple = ScanPgRelation(RelationGetRelid(relation), indexOK, false);
2215  if (!HeapTupleIsValid(pg_class_tuple))
2216  elog(ERROR, "could not find pg_class tuple for index %u",
2217  RelationGetRelid(relation));
2218  relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
2219  memcpy(relation->rd_rel, relp, CLASS_TUPLE_SIZE);
2220  /* Reload reloptions in case they changed */
2221  if (relation->rd_options)
2222  pfree(relation->rd_options);
2223  RelationParseRelOptions(relation, pg_class_tuple);
2224  /* done with pg_class tuple */
2225  heap_freetuple(pg_class_tuple);
2226  /* We must recalculate physical address in case it changed */
2227  RelationInitPhysicalAddr(relation);
2228 
2229  /*
2230  * For a non-system index, there are fields of the pg_index row that are
2231  * allowed to change, so re-read that row and update the relcache entry.
2232  * Most of the info derived from pg_index (such as support function lookup
2233  * info) cannot change, and indeed the whole point of this routine is to
2234  * update the relcache entry without clobbering that data; so wholesale
2235  * replacement is not appropriate.
2236  */
2237  if (!IsSystemRelation(relation))
2238  {
2239  HeapTuple tuple;
2241 
2242  tuple = SearchSysCache1(INDEXRELID,
2243  ObjectIdGetDatum(RelationGetRelid(relation)));
2244  if (!HeapTupleIsValid(tuple))
2245  elog(ERROR, "cache lookup failed for index %u",
2246  RelationGetRelid(relation));
2247  index = (Form_pg_index) GETSTRUCT(tuple);
2248 
2249  /*
2250  * Basically, let's just copy all the bool fields. There are one or
2251  * two of these that can't actually change in the current code, but
2252  * it's not worth it to track exactly which ones they are. None of
2253  * the array fields are allowed to change, though.
2254  */
2255  relation->rd_index->indisunique = index->indisunique;
2256  relation->rd_index->indisprimary = index->indisprimary;
2257  relation->rd_index->indisexclusion = index->indisexclusion;
2258  relation->rd_index->indimmediate = index->indimmediate;
2259  relation->rd_index->indisclustered = index->indisclustered;
2260  relation->rd_index->indisvalid = index->indisvalid;
2261  relation->rd_index->indcheckxmin = index->indcheckxmin;
2262  relation->rd_index->indisready = index->indisready;
2263  relation->rd_index->indislive = index->indislive;
2264 
2265  /* Copy xmin too, as that is needed to make sense of indcheckxmin */
2267  HeapTupleHeaderGetXmin(tuple->t_data));
2268 
2269  ReleaseSysCache(tuple);
2270  }
2271 
2272  /* Okay, now it's valid again */
2273  relation->rd_isvalid = true;
2274 }
2275 
2276 /*
2277  * RelationReloadNailed - reload minimal information for nailed relations.
2278  *
2279  * The structure of a nailed relation can never change (which is good, because
2280  * we rely on knowing their structure to be able to read catalog content). But
2281  * some parts, e.g. pg_class.relfrozenxid, are still important to have
2282  * accurate content for. Therefore those need to be reloaded after the arrival
2283  * of invalidations.
2284  */
2285 static void
2287 {
2288  Assert(relation->rd_isnailed);
2289 
2290  /*
2291  * Redo RelationInitPhysicalAddr in case it is a mapped relation whose
2292  * mapping changed.
2293  */
2294  RelationInitPhysicalAddr(relation);
2295 
2296  /* flag as needing to be revalidated */
2297  relation->rd_isvalid = false;
2298 
2299  /*
2300  * Can only reread catalog contents if in a transaction. If the relation
2301  * is currently open (not counting the nailed refcount), do so
2302  * immediately. Otherwise we've already marked the entry as possibly
2303  * invalid, and it'll be fixed when next opened.
2304  */
2305  if (!IsTransactionState() || relation->rd_refcnt <= 1)
2306  return;
2307 
2308  if (relation->rd_rel->relkind == RELKIND_INDEX)
2309  {
2310  /*
2311  * If it's a nailed-but-not-mapped index, then we need to re-read the
2312  * pg_class row to see if its relfilenode changed.
2313  */
2314  RelationReloadIndexInfo(relation);
2315  }
2316  else
2317  {
2318  /*
2319  * Reload a non-index entry. We can't easily do so if relcaches
2320  * aren't yet built, but that's fine because at that stage the
2321  * attributes that need to be current (like relfrozenxid) aren't yet
2322  * accessed. To ensure the entry will later be revalidated, we leave
2323  * it in invalid state, but allow use (cf. RelationIdGetRelation()).
2324  */
2326  {
2327  HeapTuple pg_class_tuple;
2328  Form_pg_class relp;
2329 
2330  /*
2331  * NB: Mark the entry as valid before starting to scan, to avoid
2332  * self-recursion when re-building pg_class.
2333  */
2334  relation->rd_isvalid = true;
2335 
2336  pg_class_tuple = ScanPgRelation(RelationGetRelid(relation),
2337  true, false);
2338  relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
2339  memcpy(relation->rd_rel, relp, CLASS_TUPLE_SIZE);
2340  heap_freetuple(pg_class_tuple);
2341 
2342  /*
2343  * Again mark as valid, to protect against concurrently arriving
2344  * invalidations.
2345  */
2346  relation->rd_isvalid = true;
2347  }
2348  }
2349 }
2350 
2351 /*
2352  * RelationDestroyRelation
2353  *
2354  * Physically delete a relation cache entry and all subsidiary data.
2355  * Caller must already have unhooked the entry from the hash table.
2356  */
2357 static void
2358 RelationDestroyRelation(Relation relation, bool remember_tupdesc)
2359 {
2361 
2362  /*
2363  * Make sure smgr and lower levels close the relation's files, if they
2364  * weren't closed already. (This was probably done by caller, but let's
2365  * just be real sure.)
2366  */
2367  RelationCloseSmgr(relation);
2368 
2369  /*
2370  * Free all the subsidiary data structures of the relcache entry, then the
2371  * entry itself.
2372  */
2373  if (relation->rd_rel)
2374  pfree(relation->rd_rel);
2375  /* can't use DecrTupleDescRefCount here */
2376  Assert(relation->rd_att->tdrefcount > 0);
2377  if (--relation->rd_att->tdrefcount == 0)
2378  {
2379  /*
2380  * If we Rebuilt a relcache entry during a transaction then its
2381  * possible we did that because the TupDesc changed as the result of
2382  * an ALTER TABLE that ran at less than AccessExclusiveLock. It's
2383  * possible someone copied that TupDesc, in which case the copy would
2384  * point to free'd memory. So if we rebuild an entry we keep the
2385  * TupDesc around until end of transaction, to be safe.
2386  */
2387  if (remember_tupdesc)
2389  else
2390  FreeTupleDesc(relation->rd_att);
2391  }
2392  FreeTriggerDesc(relation->trigdesc);
2393  list_free_deep(relation->rd_fkeylist);
2394  list_free(relation->rd_indexlist);
2395  bms_free(relation->rd_indexattr);
2396  bms_free(relation->rd_keyattr);
2397  bms_free(relation->rd_pkattr);
2398  bms_free(relation->rd_idattr);
2399  if (relation->rd_pubactions)
2400  pfree(relation->rd_pubactions);
2401  if (relation->rd_options)
2402  pfree(relation->rd_options);
2403  if (relation->rd_indextuple)
2404  pfree(relation->rd_indextuple);
2405  if (relation->rd_amcache)
2406  pfree(relation->rd_amcache);
2407  if (relation->rd_fdwroutine)
2408  pfree(relation->rd_fdwroutine);
2409  if (relation->rd_indexcxt)
2410  MemoryContextDelete(relation->rd_indexcxt);
2411  if (relation->rd_rulescxt)
2412  MemoryContextDelete(relation->rd_rulescxt);
2413  if (relation->rd_rsdesc)
2414  MemoryContextDelete(relation->rd_rsdesc->rscxt);
2415  if (relation->rd_partkeycxt)
2417  if (relation->rd_pdcxt)
2418  MemoryContextDelete(relation->rd_pdcxt);
2419  if (relation->rd_partcheckcxt)
2421  pfree(relation);
2422 }
2423 
2424 /*
2425  * RelationClearRelation
2426  *
2427  * Physically blow away a relation cache entry, or reset it and rebuild
2428  * it from scratch (that is, from catalog entries). The latter path is
2429  * used when we are notified of a change to an open relation (one with
2430  * refcount > 0).
2431  *
2432  * NB: when rebuilding, we'd better hold some lock on the relation,
2433  * else the catalog data we need to read could be changing under us.
2434  * Also, a rel to be rebuilt had better have refcnt > 0. This is because
2435  * a sinval reset could happen while we're accessing the catalogs, and
2436  * the rel would get blown away underneath us by RelationCacheInvalidate
2437  * if it has zero refcnt.
2438  *
2439  * The "rebuild" parameter is redundant in current usage because it has
2440  * to match the relation's refcnt status, but we keep it as a crosscheck
2441  * that we're doing what the caller expects.
2442  */
2443 static void
2444 RelationClearRelation(Relation relation, bool rebuild)
2445 {
2446  /*
2447  * As per notes above, a rel to be rebuilt MUST have refcnt > 0; while of
2448  * course it would be an equally bad idea to blow away one with nonzero
2449  * refcnt, since that would leave someone somewhere with a dangling
2450  * pointer. All callers are expected to have verified that this holds.
2451  */
2452  Assert(rebuild ?
2453  !RelationHasReferenceCountZero(relation) :
2454  RelationHasReferenceCountZero(relation));
2455 
2456  /*
2457  * Make sure smgr and lower levels close the relation's files, if they
2458  * weren't closed already. If the relation is not getting deleted, the
2459  * next smgr access should reopen the files automatically. This ensures
2460  * that the low-level file access state is updated after, say, a vacuum
2461  * truncation.
2462  */
2463  RelationCloseSmgr(relation);
2464 
2465  /* Free AM cached data, if any */
2466  if (relation->rd_amcache)
2467  pfree(relation->rd_amcache);
2468  relation->rd_amcache = NULL;
2469 
2470  /*
2471  * Treat nailed-in system relations separately, they always need to be
2472  * accessible, so we can't blow them away.
2473  */
2474  if (relation->rd_isnailed)
2475  {
2476  RelationReloadNailed(relation);
2477  return;
2478  }
2479 
2480  /* Mark it invalid until we've finished rebuild */
2481  relation->rd_isvalid = false;
2482 
2483  /* See RelationForgetRelation(). */
2484  if (relation->rd_droppedSubid != InvalidSubTransactionId)
2485  return;
2486 
2487  /*
2488  * Even non-system indexes should not be blown away if they are open and
2489  * have valid index support information. This avoids problems with active
2490  * use of the index support information. As with nailed indexes, we
2491  * re-read the pg_class row to handle possible physical relocation of the
2492  * index, and we check for pg_index updates too.
2493  */
2494  if ((relation->rd_rel->relkind == RELKIND_INDEX ||
2495  relation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX) &&
2496  relation->rd_refcnt > 0 &&
2497  relation->rd_indexcxt != NULL)
2498  {
2499  if (IsTransactionState())
2500  RelationReloadIndexInfo(relation);
2501  return;
2502  }
2503 
2504  /*
2505  * If we're really done with the relcache entry, blow it away. But if
2506  * someone is still using it, reconstruct the whole deal without moving
2507  * the physical RelationData record (so that the someone's pointer is
2508  * still valid).
2509  */
2510  if (!rebuild)
2511  {
2512  /* Remove it from the hash table */
2513  RelationCacheDelete(relation);
2514 
2515  /* And release storage */
2516  RelationDestroyRelation(relation, false);
2517  }
2518  else if (!IsTransactionState())
2519  {
2520  /*
2521  * If we're not inside a valid transaction, we can't do any catalog
2522  * access so it's not possible to rebuild yet. Just exit, leaving
2523  * rd_isvalid = false so that the rebuild will occur when the entry is
2524  * next opened.
2525  *
2526  * Note: it's possible that we come here during subtransaction abort,
2527  * and the reason for wanting to rebuild is that the rel is open in
2528  * the outer transaction. In that case it might seem unsafe to not
2529  * rebuild immediately, since whatever code has the rel already open
2530  * will keep on using the relcache entry as-is. However, in such a
2531  * case the outer transaction should be holding a lock that's
2532  * sufficient to prevent any significant change in the rel's schema,
2533  * so the existing entry contents should be good enough for its
2534  * purposes; at worst we might be behind on statistics updates or the
2535  * like. (See also CheckTableNotInUse() and its callers.) These same
2536  * remarks also apply to the cases above where we exit without having
2537  * done RelationReloadIndexInfo() yet.
2538  */
2539  return;
2540  }
2541  else
2542  {
2543  /*
2544  * Our strategy for rebuilding an open relcache entry is to build a
2545  * new entry from scratch, swap its contents with the old entry, and
2546  * finally delete the new entry (along with any infrastructure swapped
2547  * over from the old entry). This is to avoid trouble in case an
2548  * error causes us to lose control partway through. The old entry
2549  * will still be marked !rd_isvalid, so we'll try to rebuild it again
2550  * on next access. Meanwhile it's not any less valid than it was
2551  * before, so any code that might expect to continue accessing it
2552  * isn't hurt by the rebuild failure. (Consider for example a
2553  * subtransaction that ALTERs a table and then gets canceled partway
2554  * through the cache entry rebuild. The outer transaction should
2555  * still see the not-modified cache entry as valid.) The worst
2556  * consequence of an error is leaking the necessarily-unreferenced new
2557  * entry, and this shouldn't happen often enough for that to be a big
2558  * problem.
2559  *
2560  * When rebuilding an open relcache entry, we must preserve ref count,
2561  * rd_*Subid, and rd_toastoid state. Also attempt to preserve the
2562  * pg_class entry (rd_rel), tupledesc, rewrite-rule, partition key,
2563  * and partition descriptor substructures in place, because various
2564  * places assume that these structures won't move while they are
2565  * working with an open relcache entry. (Note: the refcount
2566  * mechanism for tupledescs might someday allow us to remove this hack
2567  * for the tupledesc.)
2568  *
2569  * Note that this process does not touch CurrentResourceOwner; which
2570  * is good because whatever ref counts the entry may have do not
2571  * necessarily belong to that resource owner.
2572  */
2573  Relation newrel;
2574  Oid save_relid = RelationGetRelid(relation);
2575  bool keep_tupdesc;
2576  bool keep_rules;
2577  bool keep_policies;
2578  bool keep_partkey;
2579 
2580  /* Build temporary entry, but don't link it into hashtable */
2581  newrel = RelationBuildDesc(save_relid, false);
2582  if (newrel == NULL)
2583  {
2584  /*
2585  * We can validly get here, if we're using a historic snapshot in
2586  * which a relation, accessed from outside logical decoding, is
2587  * still invisible. In that case it's fine to just mark the
2588  * relation as invalid and return - it'll fully get reloaded by
2589  * the cache reset at the end of logical decoding (or at the next
2590  * access). During normal processing we don't want to ignore this
2591  * case as it shouldn't happen there, as explained below.
2592  */
2593  if (HistoricSnapshotActive())
2594  return;
2595 
2596  /*
2597  * This shouldn't happen as dropping a relation is intended to be
2598  * impossible if still referenced (cf. CheckTableNotInUse()). But
2599  * if we get here anyway, we can't just delete the relcache entry,
2600  * as it possibly could get accessed later (as e.g. the error
2601  * might get trapped and handled via a subtransaction rollback).
2602  */
2603  elog(ERROR, "relation %u deleted while still in use", save_relid);
2604  }
2605 
2606  keep_tupdesc = equalTupleDescs(relation->rd_att, newrel->rd_att);
2607  keep_rules = equalRuleLocks(relation->rd_rules, newrel->rd_rules);
2608  keep_policies = equalRSDesc(relation->rd_rsdesc, newrel->rd_rsdesc);
2609  /* partkey is immutable once set up, so we can always keep it */
2610  keep_partkey = (relation->rd_partkey != NULL);
2611 
2612  /*
2613  * Perform swapping of the relcache entry contents. Within this
2614  * process the old entry is momentarily invalid, so there *must* be no
2615  * possibility of CHECK_FOR_INTERRUPTS within this sequence. Do it in
2616  * all-in-line code for safety.
2617  *
2618  * Since the vast majority of fields should be swapped, our method is
2619  * to swap the whole structures and then re-swap those few fields we
2620  * didn't want swapped.
2621  */
2622 #define SWAPFIELD(fldtype, fldname) \
2623  do { \
2624  fldtype _tmp = newrel->fldname; \
2625  newrel->fldname = relation->fldname; \
2626  relation->fldname = _tmp; \
2627  } while (0)
2628 
2629  /* swap all Relation struct fields */
2630  {
2631  RelationData tmpstruct;
2632 
2633  memcpy(&tmpstruct, newrel, sizeof(RelationData));
2634  memcpy(newrel, relation, sizeof(RelationData));
2635  memcpy(relation, &tmpstruct, sizeof(RelationData));
2636  }
2637 
2638  /* rd_smgr must not be swapped, due to back-links from smgr level */
2639  SWAPFIELD(SMgrRelation, rd_smgr);
2640  /* rd_refcnt must be preserved */
2641  SWAPFIELD(int, rd_refcnt);
2642  /* isnailed shouldn't change */
2643  Assert(newrel->rd_isnailed == relation->rd_isnailed);
2644  /* creation sub-XIDs must be preserved */
2645  SWAPFIELD(SubTransactionId, rd_createSubid);
2646  SWAPFIELD(SubTransactionId, rd_newRelfilenodeSubid);
2647  SWAPFIELD(SubTransactionId, rd_firstRelfilenodeSubid);
2648  SWAPFIELD(SubTransactionId, rd_droppedSubid);
2649  /* un-swap rd_rel pointers, swap contents instead */
2650  SWAPFIELD(Form_pg_class, rd_rel);
2651  /* ... but actually, we don't have to update newrel->rd_rel */
2652  memcpy(relation->rd_rel, newrel->rd_rel, CLASS_TUPLE_SIZE);
2653  /* preserve old tupledesc, rules, policies if no logical change */
2654  if (keep_tupdesc)
2655  SWAPFIELD(TupleDesc, rd_att);
2656  if (keep_rules)
2657  {
2658  SWAPFIELD(RuleLock *, rd_rules);
2659  SWAPFIELD(MemoryContext, rd_rulescxt);
2660  }
2661  if (keep_policies)
2662  SWAPFIELD(RowSecurityDesc *, rd_rsdesc);
2663  /* toast OID override must be preserved */
2664  SWAPFIELD(Oid, rd_toastoid);
2665  /* pgstat_info must be preserved */
2666  SWAPFIELD(struct PgStat_TableStatus *, pgstat_info);
2667  /* preserve old partition key if we have one */
2668  if (keep_partkey)
2669  {
2670  SWAPFIELD(PartitionKey, rd_partkey);
2671  SWAPFIELD(MemoryContext, rd_partkeycxt);
2672  }
2673  if (newrel->rd_pdcxt != NULL)
2674  {
2675  /*
2676  * We are rebuilding a partitioned relation with a non-zero
2677  * reference count, so we must keep the old partition descriptor
2678  * around, in case there's a PartitionDirectory with a pointer to
2679  * it. This means we can't free the old rd_pdcxt yet. (This is
2680  * necessary because RelationGetPartitionDesc hands out direct
2681  * pointers to the relcache's data structure, unlike our usual
2682  * practice which is to hand out copies. We'd have the same
2683  * problem with rd_partkey, except that we always preserve that
2684  * once created.)
2685  *
2686  * To ensure that it's not leaked completely, re-attach it to the
2687  * new reldesc, or make it a child of the new reldesc's rd_pdcxt
2688  * in the unlikely event that there is one already. (Compare hack
2689  * in RelationBuildPartitionDesc.) RelationClose will clean up
2690  * any such contexts once the reference count reaches zero.
2691  *
2692  * In the case where the reference count is zero, this code is not
2693  * reached, which should be OK because in that case there should
2694  * be no PartitionDirectory with a pointer to the old entry.
2695  *
2696  * Note that newrel and relation have already been swapped, so the
2697  * "old" partition descriptor is actually the one hanging off of
2698  * newrel.
2699  */
2700  relation->rd_partdesc = NULL; /* ensure rd_partdesc is invalid */
2701  if (relation->rd_pdcxt != NULL) /* probably never happens */
2702  MemoryContextSetParent(newrel->rd_pdcxt, relation->rd_pdcxt);
2703  else
2704  relation->rd_pdcxt = newrel->rd_pdcxt;
2705  /* drop newrel's pointers so we don't destroy it below */
2706  newrel->rd_partdesc = NULL;
2707  newrel->rd_pdcxt = NULL;
2708  }
2709 
2710 #undef SWAPFIELD
2711 
2712  /* And now we can throw away the temporary entry */
2713  RelationDestroyRelation(newrel, !keep_tupdesc);
2714  }
2715 }
2716 
2717 /*
2718  * RelationFlushRelation
2719  *
2720  * Rebuild the relation if it is open (refcount > 0), else blow it away.
2721  * This is used when we receive a cache invalidation event for the rel.
2722  */
2723 static void
2725 {
2726  if (relation->rd_createSubid != InvalidSubTransactionId ||
2728  {
2729  /*
2730  * New relcache entries are always rebuilt, not flushed; else we'd
2731  * forget the "new" status of the relation. Ditto for the
2732  * new-relfilenode status.
2733  *
2734  * The rel could have zero refcnt here, so temporarily increment the
2735  * refcnt to ensure it's safe to rebuild it. We can assume that the
2736  * current transaction has some lock on the rel already.
2737  */
2739  RelationClearRelation(relation, true);
2741  }
2742  else
2743  {
2744  /*
2745  * Pre-existing rels can be dropped from the relcache if not open.
2746  */
2747  bool rebuild = !RelationHasReferenceCountZero(relation);
2748 
2749  RelationClearRelation(relation, rebuild);
2750  }
2751 }
2752 
2753 /*
2754  * RelationForgetRelation - caller reports that it dropped the relation
2755  */
2756 void
2758 {
2759  Relation relation;
2760 
2761  RelationIdCacheLookup(rid, relation);
2762 
2763  if (!PointerIsValid(relation))
2764  return; /* not in cache, nothing to do */
2765 
2766  if (!RelationHasReferenceCountZero(relation))
2767  elog(ERROR, "relation %u is still open", rid);
2768 
2770  if (relation->rd_createSubid != InvalidSubTransactionId ||
2772  {
2773  /*
2774  * In the event of subtransaction rollback, we must not forget
2775  * rd_*Subid. Mark the entry "dropped" so RelationClearRelation()
2776  * invalidates it in lieu of destroying it. (If we're in a top
2777  * transaction, we could opt to destroy the entry.)
2778  */
2780  }
2781 
2782  RelationClearRelation(relation, false);
2783 }
2784 
2785 /*
2786  * RelationCacheInvalidateEntry
2787  *
2788  * This routine is invoked for SI cache flush messages.
2789  *
2790  * Any relcache entry matching the relid must be flushed. (Note: caller has
2791  * already determined that the relid belongs to our database or is a shared
2792  * relation.)
2793  *
2794  * We used to skip local relations, on the grounds that they could
2795  * not be targets of cross-backend SI update messages; but it seems
2796  * safer to process them, so that our *own* SI update messages will
2797  * have the same effects during CommandCounterIncrement for both
2798  * local and nonlocal relations.
2799  */
2800 void
2802 {
2803  Relation relation;
2804 
2805  RelationIdCacheLookup(relationId, relation);
2806 
2807  if (PointerIsValid(relation))
2808  {
2810  RelationFlushRelation(relation);
2811  }
2812 }
2813 
2814 /*
2815  * RelationCacheInvalidate
2816  * Blow away cached relation descriptors that have zero reference counts,
2817  * and rebuild those with positive reference counts. Also reset the smgr
2818  * relation cache and re-read relation mapping data.
2819  *
2820  * This is currently used only to recover from SI message buffer overflow,
2821  * so we do not touch relations having new-in-transaction relfilenodes; they
2822  * cannot be targets of cross-backend SI updates (and our own updates now go
2823  * through a separate linked list that isn't limited by the SI message
2824  * buffer size).
2825  *
2826  * We do this in two phases: the first pass deletes deletable items, and
2827  * the second one rebuilds the rebuildable items. This is essential for
2828  * safety, because hash_seq_search only copes with concurrent deletion of
2829  * the element it is currently visiting. If a second SI overflow were to
2830  * occur while we are walking the table, resulting in recursive entry to
2831  * this routine, we could crash because the inner invocation blows away
2832  * the entry next to be visited by the outer scan. But this way is OK,
2833  * because (a) during the first pass we won't process any more SI messages,
2834  * so hash_seq_search will complete safely; (b) during the second pass we
2835  * only hold onto pointers to nondeletable entries.
2836  *
2837  * The two-phase approach also makes it easy to update relfilenodes for
2838  * mapped relations before we do anything else, and to ensure that the
2839  * second pass processes nailed-in-cache items before other nondeletable
2840  * items. This should ensure that system catalogs are up to date before
2841  * we attempt to use them to reload information about other open relations.
2842  */
2843 void
2845 {
2847  RelIdCacheEnt *idhentry;
2848  Relation relation;
2849  List *rebuildFirstList = NIL;
2850  List *rebuildList = NIL;
2851  ListCell *l;
2852 
2853  /*
2854  * Reload relation mapping data before starting to reconstruct cache.
2855  */
2857 
2858  /* Phase 1 */
2859  hash_seq_init(&status, RelationIdCache);
2860 
2861  while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
2862  {
2863  relation = idhentry->reldesc;
2864 
2865  /* Must close all smgr references to avoid leaving dangling ptrs */
2866  RelationCloseSmgr(relation);
2867 
2868  /*
2869  * Ignore new relations; no other backend will manipulate them before
2870  * we commit. Likewise, before replacing a relation's relfilenode, we
2871  * shall have acquired AccessExclusiveLock and drained any applicable
2872  * pending invalidations.
2873  */
2874  if (relation->rd_createSubid != InvalidSubTransactionId ||
2876  continue;
2877 
2879 
2880  if (RelationHasReferenceCountZero(relation))
2881  {
2882  /* Delete this entry immediately */
2883  Assert(!relation->rd_isnailed);
2884  RelationClearRelation(relation, false);
2885  }
2886  else
2887  {
2888  /*
2889  * If it's a mapped relation, immediately update its rd_node in
2890  * case its relfilenode changed. We must do this during phase 1
2891  * in case the relation is consulted during rebuild of other
2892  * relcache entries in phase 2. It's safe since consulting the
2893  * map doesn't involve any access to relcache entries.
2894  */
2895  if (RelationIsMapped(relation))
2896  RelationInitPhysicalAddr(relation);
2897 
2898  /*
2899  * Add this entry to list of stuff to rebuild in second pass.
2900  * pg_class goes to the front of rebuildFirstList while
2901  * pg_class_oid_index goes to the back of rebuildFirstList, so
2902  * they are done first and second respectively. Other nailed
2903  * relations go to the front of rebuildList, so they'll be done
2904  * next in no particular order; and everything else goes to the
2905  * back of rebuildList.
2906  */
2907  if (RelationGetRelid(relation) == RelationRelationId)
2908  rebuildFirstList = lcons(relation, rebuildFirstList);
2909  else if (RelationGetRelid(relation) == ClassOidIndexId)
2910  rebuildFirstList = lappend(rebuildFirstList, relation);
2911  else if (relation->rd_isnailed)
2912  rebuildList = lcons(relation, rebuildList);
2913  else
2914  rebuildList = lappend(rebuildList, relation);
2915  }
2916  }
2917 
2918  /*
2919  * Now zap any remaining smgr cache entries. This must happen before we
2920  * start to rebuild entries, since that may involve catalog fetches which
2921  * will re-open catalog files.
2922  */
2923  smgrcloseall();
2924 
2925  /* Phase 2: rebuild the items found to need rebuild in phase 1 */
2926  foreach(l, rebuildFirstList)
2927  {
2928  relation = (Relation) lfirst(l);
2929  RelationClearRelation(relation, true);
2930  }
2931  list_free(rebuildFirstList);
2932  foreach(l, rebuildList)
2933  {
2934  relation = (Relation) lfirst(l);
2935  RelationClearRelation(relation, true);
2936  }
2937  list_free(rebuildList);
2938 }
2939 
2940 /*
2941  * RelationCloseSmgrByOid - close a relcache entry's smgr link
2942  *
2943  * Needed in some cases where we are changing a relation's physical mapping.
2944  * The link will be automatically reopened on next use.
2945  */
2946 void
2948 {
2949  Relation relation;
2950 
2951  RelationIdCacheLookup(relationId, relation);
2952 
2953  if (!PointerIsValid(relation))
2954  return; /* not in cache, nothing to do */
2955 
2956  RelationCloseSmgr(relation);
2957 }
2958 
2959 static void
2961 {
2962  if (EOXactTupleDescArray == NULL)
2963  {
2964  MemoryContext oldcxt;
2965 
2967 
2968  EOXactTupleDescArray = (TupleDesc *) palloc(16 * sizeof(TupleDesc));
2971  MemoryContextSwitchTo(oldcxt);
2972  }
2974  {
2975  int32 newlen = EOXactTupleDescArrayLen * 2;
2976 
2978 
2979  EOXactTupleDescArray = (TupleDesc *) repalloc(EOXactTupleDescArray,
2980  newlen * sizeof(TupleDesc));
2981  EOXactTupleDescArrayLen = newlen;
2982  }
2983 
2984  EOXactTupleDescArray[NextEOXactTupleDescNum++] = td;
2985 }
2986 
2987 #ifdef USE_ASSERT_CHECKING
2988 static void
2989 AssertPendingSyncConsistency(Relation relation)
2990 {
2991  bool relcache_verdict =
2992  relation->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT &&
2993  ((relation->rd_createSubid != InvalidSubTransactionId &&
2994  RELKIND_HAS_STORAGE(relation->rd_rel->relkind)) ||
2996 
2997  Assert(relcache_verdict == RelFileNodeSkippingWAL(relation->rd_node));
2998 
2999  if (relation->rd_droppedSubid != InvalidSubTransactionId)
3000  Assert(!relation->rd_isvalid &&
3001  (relation->rd_createSubid != InvalidSubTransactionId ||
3003 }
3004 
3005 /*
3006  * AssertPendingSyncs_RelationCache
3007  *
3008  * Assert that relcache.c and storage.c agree on whether to skip WAL.
3009  */
3010 void
3012 {
3014  LOCALLOCK *locallock;
3015  Relation *rels;
3016  int maxrels;
3017  int nrels;
3018  RelIdCacheEnt *idhentry;
3019  int i;
3020 
3021  /*
3022  * Open every relation that this transaction has locked. If, for some
3023  * relation, storage.c is skipping WAL and relcache.c is not skipping WAL,
3024  * a CommandCounterIncrement() typically yields a local invalidation
3025  * message that destroys the relcache entry. By recreating such entries
3026  * here, we detect the problem.
3027  */
3029  maxrels = 1;
3030  rels = palloc(maxrels * sizeof(*rels));
3031  nrels = 0;
3032  hash_seq_init(&status, GetLockMethodLocalHash());
3033  while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
3034  {
3035  Oid relid;
3036  Relation r;
3037 
3038  if (locallock->nLocks <= 0)
3039  continue;
3040  if ((LockTagType) locallock->tag.lock.locktag_type !=
3042  continue;
3043  relid = ObjectIdGetDatum(locallock->tag.lock.locktag_field2);
3044  r = RelationIdGetRelation(relid);
3045  if (!RelationIsValid(r))
3046  continue;
3047  if (nrels >= maxrels)
3048  {
3049  maxrels *= 2;
3050  rels = repalloc(rels, maxrels * sizeof(*rels));
3051  }
3052  rels[nrels++] = r;
3053  }
3054 
3055  hash_seq_init(&status, RelationIdCache);
3056  while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3057  AssertPendingSyncConsistency(idhentry->reldesc);
3058 
3059  for (i = 0; i < nrels; i++)
3060  RelationClose(rels[i]);
3062 }
3063 #endif
3064 
3065 /*
3066  * AtEOXact_RelationCache
3067  *
3068  * Clean up the relcache at main-transaction commit or abort.
3069  *
3070  * Note: this must be called *before* processing invalidation messages.
3071  * In the case of abort, we don't want to try to rebuild any invalidated
3072  * cache entries (since we can't safely do database accesses). Therefore
3073  * we must reset refcnts before handling pending invalidations.
3074  *
3075  * As of PostgreSQL 8.1, relcache refcnts should get released by the
3076  * ResourceOwner mechanism. This routine just does a debugging
3077  * cross-check that no pins remain. However, we also need to do special
3078  * cleanup when the current transaction created any relations or made use
3079  * of forced index lists.
3080  */
3081 void
3083 {
3085  RelIdCacheEnt *idhentry;
3086  int i;
3087 
3088  /*
3089  * Unless the eoxact_list[] overflowed, we only need to examine the rels
3090  * listed in it. Otherwise fall back on a hash_seq_search scan.
3091  *
3092  * For simplicity, eoxact_list[] entries are not deleted till end of
3093  * top-level transaction, even though we could remove them at
3094  * subtransaction end in some cases, or remove relations from the list if
3095  * they are cleared for other reasons. Therefore we should expect the
3096  * case that list entries are not found in the hashtable; if not, there's
3097  * nothing to do for them.
3098  */
3100  {
3101  hash_seq_init(&status, RelationIdCache);
3102  while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3103  {
3104  AtEOXact_cleanup(idhentry->reldesc, isCommit);
3105  }
3106  }
3107  else
3108  {
3109  for (i = 0; i < eoxact_list_len; i++)
3110  {
3111  idhentry = (RelIdCacheEnt *) hash_search(RelationIdCache,
3112  (void *) &eoxact_list[i],
3113  HASH_FIND,
3114  NULL);
3115  if (idhentry != NULL)
3116  AtEOXact_cleanup(idhentry->reldesc, isCommit);
3117  }
3118  }
3119 
3120  if (EOXactTupleDescArrayLen > 0)
3121  {
3122  Assert(EOXactTupleDescArray != NULL);
3123  for (i = 0; i < NextEOXactTupleDescNum; i++)
3124  FreeTupleDesc(EOXactTupleDescArray[i]);
3125  pfree(EOXactTupleDescArray);
3126  EOXactTupleDescArray = NULL;
3127  }
3128 
3129  /* Now we're out of the transaction and can clear the lists */
3130  eoxact_list_len = 0;
3131  eoxact_list_overflowed = false;
3134 }
3135 
3136 /*
3137  * AtEOXact_cleanup
3138  *
3139  * Clean up a single rel at main-transaction commit or abort
3140  *
3141  * NB: this processing must be idempotent, because EOXactListAdd() doesn't
3142  * bother to prevent duplicate entries in eoxact_list[].
3143  */
3144 static void
3145 AtEOXact_cleanup(Relation relation, bool isCommit)
3146 {
3147  bool clear_relcache = false;
3148 
3149  /*
3150  * The relcache entry's ref count should be back to its normal
3151  * not-in-a-transaction state: 0 unless it's nailed in cache.
3152  *
3153  * In bootstrap mode, this is NOT true, so don't check it --- the
3154  * bootstrap code expects relations to stay open across start/commit
3155  * transaction calls. (That seems bogus, but it's not worth fixing.)
3156  *
3157  * Note: ideally this check would be applied to every relcache entry, not
3158  * just those that have eoxact work to do. But it's not worth forcing a
3159  * scan of the whole relcache just for this. (Moreover, doing so would
3160  * mean that assert-enabled testing never tests the hash_search code path
3161  * above, which seems a bad idea.)
3162  */
3163 #ifdef USE_ASSERT_CHECKING
3165  {
3166  int expected_refcnt;
3167 
3168  expected_refcnt = relation->rd_isnailed ? 1 : 0;
3169  Assert(relation->rd_refcnt == expected_refcnt);
3170  }
3171 #endif
3172 
3173  /*
3174  * Is the relation live after this transaction ends?
3175  *
3176  * During commit, clear the relcache entry if it is preserved after
3177  * relation drop, in order not to orphan the entry. During rollback,
3178  * clear the relcache entry if the relation is created in the current
3179  * transaction since it isn't interesting any longer once we are out of
3180  * the transaction.
3181  */
3182  clear_relcache =
3183  (isCommit ?
3186 
3187  /*
3188  * Since we are now out of the transaction, reset the subids to zero. That
3189  * also lets RelationClearRelation() drop the relcache entry.
3190  */
3195 
3196  if (clear_relcache)
3197  {
3198  if (RelationHasReferenceCountZero(relation))
3199  {
3200  RelationClearRelation(relation, false);
3201  return;
3202  }
3203  else
3204  {
3205  /*
3206  * Hmm, somewhere there's a (leaked?) reference to the relation.
3207  * We daren't remove the entry for fear of dereferencing a
3208  * dangling pointer later. Bleat, and mark it as not belonging to
3209  * the current transaction. Hopefully it'll get cleaned up
3210  * eventually. This must be just a WARNING to avoid
3211  * error-during-error-recovery loops.
3212  */
3213  elog(WARNING, "cannot remove relcache entry for \"%s\" because it has nonzero refcount",
3214  RelationGetRelationName(relation));
3215  }
3216  }
3217 }
3218 
3219 /*
3220  * AtEOSubXact_RelationCache
3221  *
3222  * Clean up the relcache at sub-transaction commit or abort.
3223  *
3224  * Note: this must be called *before* processing invalidation messages.
3225  */
3226 void
3228  SubTransactionId parentSubid)
3229 {
3231  RelIdCacheEnt *idhentry;
3232  int i;
3233 
3234  /*
3235  * Unless the eoxact_list[] overflowed, we only need to examine the rels
3236  * listed in it. Otherwise fall back on a hash_seq_search scan. Same
3237  * logic as in AtEOXact_RelationCache.
3238  */
3240  {
3241  hash_seq_init(&status, RelationIdCache);
3242  while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3243  {
3244  AtEOSubXact_cleanup(idhentry->reldesc, isCommit,
3245  mySubid, parentSubid);
3246  }
3247  }
3248  else
3249  {
3250  for (i = 0; i < eoxact_list_len; i++)
3251  {
3252  idhentry = (RelIdCacheEnt *) hash_search(RelationIdCache,
3253  (void *) &eoxact_list[i],
3254  HASH_FIND,
3255  NULL);
3256  if (idhentry != NULL)
3257  AtEOSubXact_cleanup(idhentry->reldesc, isCommit,
3258  mySubid, parentSubid);
3259  }
3260  }
3261 
3262  /* Don't reset the list; we still need more cleanup later */
3263 }
3264 
3265 /*
3266  * AtEOSubXact_cleanup
3267  *
3268  * Clean up a single rel at subtransaction commit or abort
3269  *
3270  * NB: this processing must be idempotent, because EOXactListAdd() doesn't
3271  * bother to prevent duplicate entries in eoxact_list[].
3272  */
3273 static void
3274 AtEOSubXact_cleanup(Relation relation, bool isCommit,
3275  SubTransactionId mySubid, SubTransactionId parentSubid)
3276 {
3277  /*
3278  * Is it a relation created in the current subtransaction?
3279  *
3280  * During subcommit, mark it as belonging to the parent, instead, as long
3281  * as it has not been dropped. Otherwise simply delete the relcache entry.
3282  * --- it isn't interesting any longer.
3283  */
3284  if (relation->rd_createSubid == mySubid)
3285  {
3286  /*
3287  * Valid rd_droppedSubid means the corresponding relation is dropped
3288  * but the relcache entry is preserved for at-commit pending sync. We
3289  * need to drop it explicitly here not to make the entry orphan.
3290  */
3291  Assert(relation->rd_droppedSubid == mySubid ||
3293  if (isCommit && relation->rd_droppedSubid == InvalidSubTransactionId)
3294  relation->rd_createSubid = parentSubid;
3295  else if (RelationHasReferenceCountZero(relation))
3296  {
3297  /* allow the entry to be removed */
3302  RelationClearRelation(relation, false);
3303  return;
3304  }
3305  else
3306  {
3307  /*
3308  * Hmm, somewhere there's a (leaked?) reference to the relation.
3309  * We daren't remove the entry for fear of dereferencing a
3310  * dangling pointer later. Bleat, and transfer it to the parent
3311  * subtransaction so we can try again later. This must be just a
3312  * WARNING to avoid error-during-error-recovery loops.
3313  */
3314  relation->rd_createSubid = parentSubid;
3315  elog(WARNING, "cannot remove relcache entry for \"%s\" because it has nonzero refcount",
3316  RelationGetRelationName(relation));
3317  }
3318  }
3319 
3320  /*
3321  * Likewise, update or drop any new-relfilenode-in-subtransaction record
3322  * or drop record.
3323  */
3324  if (relation->rd_newRelfilenodeSubid == mySubid)
3325  {
3326  if (isCommit)
3327  relation->rd_newRelfilenodeSubid = parentSubid;
3328  else
3330  }
3331 
3332  if (relation->rd_firstRelfilenodeSubid == mySubid)
3333  {
3334  if (isCommit)
3335  relation->rd_firstRelfilenodeSubid = parentSubid;
3336  else
3338  }
3339 
3340  if (relation->rd_droppedSubid == mySubid)
3341  {
3342  if (isCommit)
3343  relation->rd_droppedSubid = parentSubid;
3344  else
3346  }
3347 }
3348 
3349 
3350 /*
3351  * RelationBuildLocalRelation
3352  * Build a relcache entry for an about-to-be-created relation,
3353  * and enter it into the relcache.
3354  */
3355 Relation
3357  Oid relnamespace,
3358  TupleDesc tupDesc,
3359  Oid relid,
3360  Oid accessmtd,
3361  Oid relfilenode,
3362  Oid reltablespace,
3363  bool shared_relation,
3364  bool mapped_relation,
3365  char relpersistence,
3366  char relkind)
3367 {
3368  Relation rel;
3369  MemoryContext oldcxt;
3370  int natts = tupDesc->natts;
3371  int i;
3372  bool has_not_null;
3373  bool nailit;
3374 
3375  AssertArg(natts >= 0);
3376 
3377  /*
3378  * check for creation of a rel that must be nailed in cache.
3379  *
3380  * XXX this list had better match the relations specially handled in
3381  * RelationCacheInitializePhase2/3.
3382  */
3383  switch (relid)
3384  {
3385  case DatabaseRelationId:
3386  case AuthIdRelationId:
3387  case AuthMemRelationId:
3388  case RelationRelationId:
3389  case AttributeRelationId:
3390  case ProcedureRelationId:
3391  case TypeRelationId:
3392  nailit = true;
3393  break;
3394  default:
3395  nailit = false;
3396  break;
3397  }
3398 
3399  /*
3400  * check that hardwired list of shared rels matches what's in the
3401  * bootstrap .bki file. If you get a failure here during initdb, you
3402  * probably need to fix IsSharedRelation() to match whatever you've done
3403  * to the set of shared relations.
3404  */
3405  if (shared_relation != IsSharedRelation(relid))
3406  elog(ERROR, "shared_relation flag for \"%s\" does not match IsSharedRelation(%u)",
3407  relname, relid);
3408 
3409  /* Shared relations had better be mapped, too */
3410  Assert(mapped_relation || !shared_relation);
3411 
3412  /*
3413  * switch to the cache context to create the relcache entry.
3414  */
3415  if (!CacheMemoryContext)
3417 
3419 
3420  /*
3421  * allocate a new relation descriptor and fill in basic state fields.
3422  */
3423  rel = (Relation) palloc0(sizeof(RelationData));
3424 
3425  /* make sure relation is marked as having no open file yet */
3426  rel->rd_smgr = NULL;
3427 
3428  /* mark it nailed if appropriate */
3429  rel->rd_isnailed = nailit;
3430 
3431  rel->rd_refcnt = nailit ? 1 : 0;
3432 
3433  /* it's being created in this transaction */
3438 
3439  /*
3440  * create a new tuple descriptor from the one passed in. We do this
3441  * partly to copy it into the cache context, and partly because the new
3442  * relation can't have any defaults or constraints yet; they have to be
3443  * added in later steps, because they require additions to multiple system
3444  * catalogs. We can copy attnotnull constraints here, however.
3445  */
3446  rel->rd_att = CreateTupleDescCopy(tupDesc);
3447  rel->rd_att->tdrefcount = 1; /* mark as refcounted */
3448  has_not_null = false;
3449  for (i = 0; i < natts; i++)
3450  {
3451  Form_pg_attribute satt = TupleDescAttr(tupDesc, i);
3452  Form_pg_attribute datt = TupleDescAttr(rel->rd_att, i);
3453 
3454  datt->attidentity = satt->attidentity;
3455  datt->attgenerated = satt->attgenerated;
3456  datt->attnotnull = satt->attnotnull;
3457  has_not_null |= satt->attnotnull;
3458  }
3459 
3460  if (has_not_null)
3461  {
3462  TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
3463 
3464  constr->has_not_null = true;
3465  rel->rd_att->constr = constr;
3466  }
3467 
3468  /*
3469  * initialize relation tuple form (caller may add/override data later)
3470  */
3472 
3473  namestrcpy(&rel->rd_rel->relname, relname);
3474  rel->rd_rel->relnamespace = relnamespace;
3475 
3476  rel->rd_rel->relkind = relkind;
3477  rel->rd_rel->relnatts = natts;
3478  rel->rd_rel->reltype = InvalidOid;
3479  /* needed when bootstrapping: */
3480  rel->rd_rel->relowner = BOOTSTRAP_SUPERUSERID;
3481 
3482  /* set up persistence and relcache fields dependent on it */
3483  rel->rd_rel->relpersistence = relpersistence;
3484  switch (relpersistence)
3485  {
3486  case RELPERSISTENCE_UNLOGGED:
3487  case RELPERSISTENCE_PERMANENT:
3489  rel->rd_islocaltemp = false;
3490  break;
3491  case RELPERSISTENCE_TEMP:
3492  Assert(isTempOrTempToastNamespace(relnamespace));
3494  rel->rd_islocaltemp = true;
3495  break;
3496  default:
3497  elog(ERROR, "invalid relpersistence: %c", relpersistence);
3498  break;
3499  }
3500 
3501  /* if it's a materialized view, it's not populated initially */
3502  if (relkind == RELKIND_MATVIEW)
3503  rel->rd_rel->relispopulated = false;
3504  else
3505  rel->rd_rel->relispopulated = true;
3506 
3507  /* set replica identity -- system catalogs and non-tables don't have one */
3508  if (!IsCatalogNamespace(relnamespace) &&
3509  (relkind == RELKIND_RELATION ||
3510  relkind == RELKIND_MATVIEW ||
3511  relkind == RELKIND_PARTITIONED_TABLE))
3512  rel->rd_rel->relreplident = REPLICA_IDENTITY_DEFAULT;
3513  else
3514  rel->rd_rel->relreplident = REPLICA_IDENTITY_NOTHING;
3515 
3516  /*
3517  * Insert relation physical and logical identifiers (OIDs) into the right
3518  * places. For a mapped relation, we set relfilenode to zero and rely on
3519  * RelationInitPhysicalAddr to consult the map.
3520  */
3521  rel->rd_rel->relisshared = shared_relation;
3522 
3523  RelationGetRelid(rel) = relid;
3524 
3525  for (i = 0; i < natts; i++)
3526  TupleDescAttr(rel->rd_att, i)->attrelid = relid;
3527 
3528  rel->rd_rel->reltablespace = reltablespace;
3529 
3530  if (mapped_relation)
3531  {
3532  rel->rd_rel->relfilenode = InvalidOid;
3533  /* Add it to the active mapping information */
3534  RelationMapUpdateMap(relid, relfilenode, shared_relation, true);
3535  }
3536  else
3537  rel->rd_rel->relfilenode = relfilenode;
3538 
3539  RelationInitLockInfo(rel); /* see lmgr.c */
3540 
3542 
3543  rel->rd_rel->relam = accessmtd;
3544 
3545  if (relkind == RELKIND_RELATION ||
3546  relkind == RELKIND_SEQUENCE ||
3547  relkind == RELKIND_TOASTVALUE ||
3548  relkind == RELKIND_MATVIEW)
3550 
3551  /*
3552  * Okay to insert into the relcache hash table.
3553  *
3554  * Ordinarily, there should certainly not be an existing hash entry for
3555  * the same OID; but during bootstrap, when we create a "real" relcache
3556  * entry for one of the bootstrap relations, we'll be overwriting the
3557  * phony one created with formrdesc. So allow that to happen for nailed
3558  * rels.
3559  */
3560  RelationCacheInsert(rel, nailit);
3561 
3562  /*
3563  * Flag relation as needing eoxact cleanup (to clear rd_createSubid). We
3564  * can't do this before storing relid in it.
3565  */
3566  EOXactListAdd(rel);
3567 
3568  /*
3569  * done building relcache entry.
3570  */
3571  MemoryContextSwitchTo(oldcxt);
3572 
3573  /* It's fully valid */
3574  rel->rd_isvalid = true;
3575 
3576  /*
3577  * Caller expects us to pin the returned entry.
3578  */
3580 
3581  return rel;
3582 }
3583 
3584 
3585 /*
3586  * RelationSetNewRelfilenode
3587  *
3588  * Assign a new relfilenode (physical file name), and possibly a new
3589  * persistence setting, to the relation.
3590  *
3591  * This allows a full rewrite of the relation to be done with transactional
3592  * safety (since the filenode assignment can be rolled back). Note however
3593  * that there is no simple way to access the relation's old data for the
3594  * remainder of the current transaction. This limits the usefulness to cases
3595  * such as TRUNCATE or rebuilding an index from scratch.
3596  *
3597  * Caller must already hold exclusive lock on the relation.
3598  */
3599 void
3600 RelationSetNewRelfilenode(Relation relation, char persistence)
3601 {
3602  Oid newrelfilenode;
3603  Relation pg_class;
3604  HeapTuple tuple;
3605  Form_pg_class classform;
3606  MultiXactId minmulti = InvalidMultiXactId;
3607  TransactionId freezeXid = InvalidTransactionId;
3608  RelFileNode newrnode;
3609 
3610  /* Allocate a new relfilenode */
3611  newrelfilenode = GetNewRelFileNode(relation->rd_rel->reltablespace, NULL,
3612  persistence);
3613 
3614  /*
3615  * Get a writable copy of the pg_class tuple for the given relation.
3616  */
3617  pg_class = table_open(RelationRelationId, RowExclusiveLock);
3618 
3619  tuple = SearchSysCacheCopy1(RELOID,
3620  ObjectIdGetDatum(RelationGetRelid(relation)));
3621  if (!HeapTupleIsValid(tuple))
3622  elog(ERROR, "could not find tuple for relation %u",
3623  RelationGetRelid(relation));
3624  classform = (Form_pg_class) GETSTRUCT(tuple);
3625 
3626  /*
3627  * Schedule unlinking of the old storage at transaction commit.
3628  */
3629  RelationDropStorage(relation);
3630 
3631  /*
3632  * Create storage for the main fork of the new relfilenode. If it's a
3633  * table-like object, call into the table AM to do so, which'll also
3634  * create the table's init fork if needed.
3635  *
3636  * NOTE: If relevant for the AM, any conflict in relfilenode value will be
3637  * caught here, if GetNewRelFileNode messes up for any reason.
3638  */
3639  newrnode = relation->rd_node;
3640  newrnode.relNode = newrelfilenode;
3641 
3642  switch (relation->rd_rel->relkind)
3643  {
3644  case RELKIND_INDEX:
3645  case RELKIND_SEQUENCE:
3646  {
3647  /* handle these directly, at least for now */
3648  SMgrRelation srel;
3649 
3650  srel = RelationCreateStorage(newrnode, persistence);
3651  smgrclose(srel);
3652  }
3653  break;
3654 
3655  case RELKIND_RELATION:
3656  case RELKIND_TOASTVALUE:
3657  case RELKIND_MATVIEW:
3658  table_relation_set_new_filenode(relation, &newrnode,
3659  persistence,
3660  &freezeXid, &minmulti);
3661  break;
3662 
3663  default:
3664  /* we shouldn't be called for anything else */
3665  elog(ERROR, "relation \"%s\" does not have storage",
3666  RelationGetRelationName(relation));
3667  break;
3668  }
3669 
3670  /*
3671  * If we're dealing with a mapped index, pg_class.relfilenode doesn't
3672  * change; instead we have to send the update to the relation mapper.
3673  *
3674  * For mapped indexes, we don't actually change the pg_class entry at all;
3675  * this is essential when reindexing pg_class itself. That leaves us with
3676  * possibly-inaccurate values of relpages etc, but those will be fixed up
3677  * later.
3678  */
3679  if (RelationIsMapped(relation))
3680  {
3681  /* This case is only supported for indexes */
3682  Assert(relation->rd_rel->relkind == RELKIND_INDEX);
3683 
3684  /* Since we're not updating pg_class, these had better not change */
3685  Assert(classform->relfrozenxid == freezeXid);
3686  Assert(classform->relminmxid == minmulti);
3687  Assert(classform->relpersistence == persistence);
3688 
3689  /*
3690  * In some code paths it's possible that the tuple update we'd
3691  * otherwise do here is the only thing that would assign an XID for
3692  * the current transaction. However, we must have an XID to delete
3693  * files, so make sure one is assigned.
3694  */
3695  (void) GetCurrentTransactionId();
3696 
3697  /* Do the deed */
3699  newrelfilenode,
3700  relation->rd_rel->relisshared,
3701  false);
3702 
3703  /* Since we're not updating pg_class, must trigger inval manually */
3704  CacheInvalidateRelcache(relation);
3705  }
3706  else
3707  {
3708  /* Normal case, update the pg_class entry */
3709  classform->relfilenode = newrelfilenode;
3710 
3711  /* relpages etc. never change for sequences */
3712  if (relation->rd_rel->relkind != RELKIND_SEQUENCE)
3713  {
3714  classform->relpages = 0; /* it's empty until further notice */
3715  classform->reltuples = -1;
3716  classform->relallvisible = 0;
3717  }
3718  classform->relfrozenxid = freezeXid;
3719  classform->relminmxid = minmulti;
3720  classform->relpersistence = persistence;
3721 
3722  CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
3723  }
3724 
3725  heap_freetuple(tuple);
3726 
3727  table_close(pg_class, RowExclusiveLock);
3728 
3729  /*
3730  * Make the pg_class row change or relation map change visible. This will
3731  * cause the relcache entry to get updated, too.
3732  */
3734 
3735  RelationAssumeNewRelfilenode(relation);
3736 }
3737 
3738 /*
3739  * RelationAssumeNewRelfilenode
3740  *
3741  * Code that modifies pg_class.reltablespace or pg_class.relfilenode must call
3742  * this. The call shall precede any code that might insert WAL records whose
3743  * replay would modify bytes in the new RelFileNode, and the call shall follow
3744  * any WAL modifying bytes in the prior RelFileNode. See struct RelationData.
3745  * Ideally, call this as near as possible to the CommandCounterIncrement()
3746  * that makes the pg_class change visible (before it or after it); that
3747  * minimizes the chance of future development adding a forbidden WAL insertion
3748  * between RelationAssumeNewRelfilenode() and CommandCounterIncrement().
3749  */
3750 void
3752 {
3755  relation->rd_firstRelfilenodeSubid = relation->rd_newRelfilenodeSubid;
3756 
3757  /* Flag relation as needing eoxact cleanup (to clear these fields) */
3758  EOXactListAdd(relation);
3759 }
3760 
3761 
3762 /*
3763  * RelationCacheInitialize
3764  *
3765  * This initializes the relation descriptor cache. At the time
3766  * that this is invoked, we can't do database access yet (mainly
3767  * because the transaction subsystem is not up); all we are doing
3768  * is making an empty cache hashtable. This must be done before
3769  * starting the initialization transaction, because otherwise
3770  * AtEOXact_RelationCache would crash if that transaction aborts
3771  * before we can get the relcache set up.
3772  */
3773 
3774 #define INITRELCACHESIZE 400
3775 
3776 void
3778 {
3779  HASHCTL ctl;
3780 
3781  /*
3782  * make sure cache memory context exists
3783  */
3784  if (!CacheMemoryContext)
3786 
3787  /*
3788  * create hashtable that indexes the relcache
3789  */
3790  ctl.keysize = sizeof(Oid);
3791  ctl.entrysize = sizeof(RelIdCacheEnt);
3792  RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
3793  &ctl, HASH_ELEM | HASH_BLOBS);
3794 
3795  /*
3796  * relation mapper needs to be initialized too
3797  */
3799 }
3800 
3801 /*
3802  * RelationCacheInitializePhase2
3803  *
3804  * This is called to prepare for access to shared catalogs during startup.
3805  * We must at least set up nailed reldescs for pg_database, pg_authid,
3806  * pg_auth_members, and pg_shseclabel. Ideally we'd like to have reldescs
3807  * for their indexes, too. We attempt to load this information from the
3808  * shared relcache init file. If that's missing or broken, just make
3809  * phony entries for the catalogs themselves.
3810  * RelationCacheInitializePhase3 will clean up as needed.
3811  */
3812 void
3814 {
3815  MemoryContext oldcxt;
3816 
3817  /*
3818  * relation mapper needs initialized too
3819  */
3821 
3822  /*
3823  * In bootstrap mode, the shared catalogs aren't there yet anyway, so do
3824  * nothing.
3825  */
3827  return;
3828 
3829  /*
3830  * switch to cache memory context
3831  */
3833 
3834  /*
3835  * Try to load the shared relcache cache file. If unsuccessful, bootstrap
3836  * the cache with pre-made descriptors for the critical shared catalogs.
3837  */
3838  if (!load_relcache_init_file(true))
3839  {
3840  formrdesc("pg_database", DatabaseRelation_Rowtype_Id, true,
3841  Natts_pg_database, Desc_pg_database);
3842  formrdesc("pg_authid", AuthIdRelation_Rowtype_Id, true,
3843  Natts_pg_authid, Desc_pg_authid);
3844  formrdesc("pg_auth_members", AuthMemRelation_Rowtype_Id, true,
3845  Natts_pg_auth_members, Desc_pg_auth_members);
3846  formrdesc("pg_shseclabel", SharedSecLabelRelation_Rowtype_Id, true,
3847  Natts_pg_shseclabel, Desc_pg_shseclabel);
3848  formrdesc("pg_subscription", SubscriptionRelation_Rowtype_Id, true,
3849  Natts_pg_subscription, Desc_pg_subscription);
3850 
3851 #define NUM_CRITICAL_SHARED_RELS 5 /* fix if you change list above */
3852  }
3853 
3854  MemoryContextSwitchTo(oldcxt);
3855 }
3856 
3857 /*
3858  * RelationCacheInitializePhase3
3859  *
3860  * This is called as soon as the catcache and transaction system
3861  * are functional and we have determined MyDatabaseId. At this point
3862  * we can actually read data from the database's system catalogs.
3863  * We first try to read pre-computed relcache entries from the local
3864  * relcache init file. If that's missing or broken, make phony entries
3865  * for the minimum set of nailed-in-cache relations. Then (unless
3866  * bootstrapping) make sure we have entries for the critical system
3867  * indexes. Once we've done all this, we have enough infrastructure to
3868  * open any system catalog or use any catcache. The last step is to
3869  * rewrite the cache files if needed.
3870  */
3871 void
3873 {
3875  RelIdCacheEnt *idhentry;
3876  MemoryContext oldcxt;
3877  bool needNewCacheFile = !criticalSharedRelcachesBuilt;
3878 
3879  /*
3880  * relation mapper needs initialized too
3881  */
3883 
3884  /*
3885  * switch to cache memory context
3886  */
3888 
3889  /*
3890  * Try to load the local relcache cache file. If unsuccessful, bootstrap
3891  * the cache with pre-made descriptors for the critical "nailed-in" system
3892  * catalogs.
3893  */
3894  if (IsBootstrapProcessingMode() ||
3895  !load_relcache_init_file(false))
3896  {
3897  needNewCacheFile = true;
3898 
3899  formrdesc("pg_class", RelationRelation_Rowtype_Id, false,
3900  Natts_pg_class, Desc_pg_class);
3901  formrdesc("pg_attribute", AttributeRelation_Rowtype_Id, false,
3902  Natts_pg_attribute, Desc_pg_attribute);
3903  formrdesc("pg_proc", ProcedureRelation_Rowtype_Id, false,
3904  Natts_pg_proc, Desc_pg_proc);
3905  formrdesc("pg_type", TypeRelation_Rowtype_Id, false,
3906  Natts_pg_type, Desc_pg_type);
3907 
3908 #define NUM_CRITICAL_LOCAL_RELS 4 /* fix if you change list above */
3909  }
3910 
3911  MemoryContextSwitchTo(oldcxt);
3912 
3913  /* In bootstrap mode, the faked-up formrdesc info is all we'll have */
3915  return;
3916 
3917  /*
3918  * If we didn't get the critical system indexes loaded into relcache, do
3919  * so now. These are critical because the catcache and/or opclass cache
3920  * depend on them for fetches done during relcache load. Thus, we have an
3921  * infinite-recursion problem. We can break the recursion by doing
3922  * heapscans instead of indexscans at certain key spots. To avoid hobbling
3923  * performance, we only want to do that until we have the critical indexes
3924  * loaded into relcache. Thus, the flag criticalRelcachesBuilt is used to
3925  * decide whether to do heapscan or indexscan at the key spots, and we set
3926  * it true after we've loaded the critical indexes.
3927  *
3928  * The critical indexes are marked as "nailed in cache", partly to make it
3929  * easy for load_relcache_init_file to count them, but mainly because we
3930  * cannot flush and rebuild them once we've set criticalRelcachesBuilt to
3931  * true. (NOTE: perhaps it would be possible to reload them by
3932  * temporarily setting criticalRelcachesBuilt to false again. For now,
3933  * though, we just nail 'em in.)
3934  *
3935  * RewriteRelRulenameIndexId and TriggerRelidNameIndexId are not critical
3936  * in the same way as the others, because the critical catalogs don't
3937  * (currently) have any rules or triggers, and so these indexes can be
3938  * rebuilt without inducing recursion. However they are used during
3939  * relcache load when a rel does have rules or triggers, so we choose to
3940  * nail them for performance reasons.
3941  */
3943  {
3945  RelationRelationId);
3947  AttributeRelationId);
3949  IndexRelationId);
3951  OperatorClassRelationId);
3953  AccessMethodProcedureRelationId);
3955  RewriteRelationId);
3957  TriggerRelationId);
3958 
3959 #define NUM_CRITICAL_LOCAL_INDEXES 7 /* fix if you change list above */
3960 
3961  criticalRelcachesBuilt = true;
3962  }
3963 
3964  /*
3965  * Process critical shared indexes too.
3966  *
3967  * DatabaseNameIndexId isn't critical for relcache loading, but rather for
3968  * initial lookup of MyDatabaseId, without which we'll never find any
3969  * non-shared catalogs at all. Autovacuum calls InitPostgres with a
3970  * database OID, so it instead depends on DatabaseOidIndexId. We also
3971  * need to nail up some indexes on pg_authid and pg_auth_members for use
3972  * during client authentication. SharedSecLabelObjectIndexId isn't
3973  * critical for the core system, but authentication hooks might be
3974  * interested in it.
3975  */
3977  {
3979  DatabaseRelationId);
3981  DatabaseRelationId);
3983  AuthIdRelationId);
3985  AuthIdRelationId);
3987  AuthMemRelationId);
3989  SharedSecLabelRelationId);
3990 
3991 #define NUM_CRITICAL_SHARED_INDEXES 6 /* fix if you change list above */
3992 
3994  }
3995 
3996  /*
3997  * Now, scan all the relcache entries and update anything that might be
3998  * wrong in the results from formrdesc or the relcache cache file. If we
3999  * faked up relcache entries using formrdesc, then read the real pg_class
4000  * rows and replace the fake entries with them. Also, if any of the
4001  * relcache entries have rules, triggers, or security policies, load that
4002  * info the hard way since it isn't recorded in the cache file.
4003  *
4004  * Whenever we access the catalogs to read data, there is a possibility of
4005  * a shared-inval cache flush causing relcache entries to be removed.
4006  * Since hash_seq_search only guarantees to still work after the *current*
4007  * entry is removed, it's unsafe to continue the hashtable scan afterward.
4008  * We handle this by restarting the scan from scratch after each access.
4009  * This is theoretically O(N^2), but the number of entries that actually
4010  * need to be fixed is small enough that it doesn't matter.
4011  */
4012  hash_seq_init(&status, RelationIdCache);
4013 
4014  while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
4015  {
4016  Relation relation = idhentry->reldesc;
4017  bool restart = false;
4018 
4019  /*
4020  * Make sure *this* entry doesn't get flushed while we work with it.
4021  */
4023 
4024  /*
4025  * If it's a faked-up entry, read the real pg_class tuple.
4026  */
4027  if (relation->rd_rel->relowner == InvalidOid)
4028  {
4029  HeapTuple htup;
4030  Form_pg_class relp;
4031 
4032  htup = SearchSysCache1(RELOID,
4033  ObjectIdGetDatum(RelationGetRelid(relation)));
4034  if (!HeapTupleIsValid(htup))
4035  elog(FATAL, "cache lookup failed for relation %u",
4036  RelationGetRelid(relation));
4037  relp = (Form_pg_class) GETSTRUCT(htup);
4038 
4039  /*
4040  * Copy tuple to relation->rd_rel. (See notes in
4041  * AllocateRelationDesc())
4042  */
4043  memcpy((char *) relation->rd_rel, (char *) relp, CLASS_TUPLE_SIZE);
4044 
4045  /* Update rd_options while we have the tuple */
4046  if (relation->rd_options)
4047  pfree(relation->rd_options);
4048  RelationParseRelOptions(relation, htup);
4049 
4050  /*
4051  * Check the values in rd_att were set up correctly. (We cannot
4052  * just copy them over now: formrdesc must have set up the rd_att
4053  * data correctly to start with, because it may already have been
4054  * copied into one or more catcache entries.)
4055  */
4056  Assert(relation->rd_att->tdtypeid == relp->reltype);
4057  Assert(relation->rd_att->tdtypmod == -1);
4058 
4059  ReleaseSysCache(htup);
4060 
4061  /* relowner had better be OK now, else we'll loop forever */
4062  if (relation->rd_rel->relowner == InvalidOid)
4063  elog(ERROR, "invalid relowner in pg_class entry for \"%s\"",
4064  RelationGetRelationName(relation));
4065 
4066  restart = true;
4067  }
4068 
4069  /*
4070  * Fix data that isn't saved in relcache cache file.
4071  *
4072  * relhasrules or relhastriggers could possibly be wrong or out of
4073  * date. If we don't actually find any rules or triggers, clear the
4074  * local copy of the flag so that we don't get into an infinite loop
4075  * here. We don't make any attempt to fix the pg_class entry, though.
4076  */
4077  if (relation->rd_rel->relhasrules && relation->rd_rules == NULL)
4078  {
4079  RelationBuildRuleLock(relation);
4080  if (relation->rd_rules == NULL)
4081  relation->rd_rel->relhasrules = false;
4082  restart = true;
4083  }
4084  if (relation->rd_rel->relhastriggers && relation->trigdesc == NULL)
4085  {
4086  RelationBuildTriggers(relation);
4087  if (relation->trigdesc == NULL)
4088  relation->rd_rel->relhastriggers = false;
4089  restart = true;
4090  }
4091 
4092  /*
4093  * Re-load the row security policies if the relation has them, since
4094  * they are not preserved in the cache. Note that we can never NOT
4095  * have a policy while relrowsecurity is true,
4096  * RelationBuildRowSecurity will create a single default-deny policy
4097  * if there is no policy defined in pg_policy.
4098  */
4099  if (relation->rd_rel->relrowsecurity && relation->rd_rsdesc == NULL)
4100  {
4101  RelationBuildRowSecurity(relation);
4102 
4103  Assert(relation->rd_rsdesc != NULL);
4104  restart = true;
4105  }
4106 
4107  /* Reload tableam data if needed */
4108  if (relation->rd_tableam == NULL &&
4109  (relation->rd_rel->relkind == RELKIND_RELATION ||
4110  relation->rd_rel->relkind == RELKIND_SEQUENCE ||
4111  relation->rd_rel->relkind == RELKIND_TOASTVALUE ||
4112  relation->rd_rel->relkind == RELKIND_MATVIEW))
4113  {
4115  Assert(relation->rd_tableam != NULL);
4116 
4117  restart = true;
4118  }
4119 
4120  /* Release hold on the relation */
4122 
4123  /* Now, restart the hashtable scan if needed */
4124  if (restart)
4125  {
4126  hash_seq_term(&status);
4127  hash_seq_init(&status, RelationIdCache);
4128  }
4129  }
4130 
4131  /*
4132  * Lastly, write out new relcache cache files if needed. We don't bother
4133  * to distinguish cases where only one of the two needs an update.
4134  */
4135  if (needNewCacheFile)
4136  {
4137  /*
4138  * Force all the catcaches to finish initializing and thereby open the
4139  * catalogs and indexes they use. This will preload the relcache with
4140  * entries for all the most important system catalogs and indexes, so
4141  * that the init files will be most useful for future backends.
4142  */
4144 
4145  /* now write the files */
4147  write_relcache_init_file(false);
4148  }
4149 }
4150 
4151 /*
4152  * Load one critical system index into the relcache
4153  *
4154  * indexoid is the OID of the target index, heapoid is the OID of the catalog
4155  * it belongs to.
4156  */
4157 static void
4158 load_critical_index(Oid indexoid, Oid heapoid)
4159 {
4160  Relation ird;
4161 
4162  /*
4163  * We must lock the underlying catalog before locking the index to avoid
4164  * deadlock, since RelationBuildDesc might well need to read the catalog,
4165  * and if anyone else is exclusive-locking this catalog and index they'll
4166  * be doing it in that order.
4167  */
4168  LockRelationOid(heapoid, AccessShareLock);
4169  LockRelationOid(indexoid, AccessShareLock);
4170  ird = RelationBuildDesc(indexoid, true);
4171  if (ird == NULL)
4172  elog(PANIC, "could not open critical system index %u", indexoid);
4173  ird->rd_isnailed = true;
4174  ird->rd_refcnt = 1;
4177 
4178  (void) RelationGetIndexAttOptions(ird, false);
4179 }
4180 
4181 /*
4182  * GetPgClassDescriptor -- get a predefined tuple descriptor for pg_class
4183  * GetPgIndexDescriptor -- get a predefined tuple descriptor for pg_index
4184  *
4185  * We need this kluge because we have to be able to access non-fixed-width
4186  * fields of pg_class and pg_index before we have the standard catalog caches
4187  * available. We use predefined data that's set up in just the same way as
4188  * the bootstrapped reldescs used by formrdesc(). The resulting tupdesc is
4189  * not 100% kosher: it does not have the correct rowtype OID in tdtypeid, nor
4190  * does it have a TupleConstr field. But it's good enough for the purpose of
4191  * extracting fields.
4192  */
4193 static TupleDesc
4195 {
4196  TupleDesc result;
4197  MemoryContext oldcxt;
4198  int i;
4199 
4201 
4202  result = CreateTemplateTupleDesc(natts);
4203  result->tdtypeid = RECORDOID; /* not right, but we don't care */
4204  result->tdtypmod = -1;
4205 
4206  for (i = 0; i < natts; i++)
4207  {
4208  memcpy(TupleDescAttr(result, i), &attrs[i], ATTRIBUTE_FIXED_PART_SIZE);
4209  /* make sure attcacheoff is valid */
4210  TupleDescAttr(result, i)->attcacheoff = -1;
4211  }
4212 
4213  /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
4214  TupleDescAttr(result, 0)->attcacheoff = 0;
4215 
4216  /* Note: we don't bother to set up a TupleConstr entry */
4217 
4218  MemoryContextSwitchTo(oldcxt);
4219 
4220  return result;
4221 }
4222 
4223 static TupleDesc
4225 {
4226  static TupleDesc pgclassdesc = NULL;
4227 
4228  /* Already done? */
4229  if (pgclassdesc == NULL)
4230  pgclassdesc = BuildHardcodedDescriptor(Natts_pg_class,
4231  Desc_pg_class);
4232 
4233  return pgclassdesc;
4234 }
4235 
4236 static TupleDesc
4238 {
4239  static TupleDesc pgindexdesc = NULL;
4240 
4241  /* Already done? */
4242  if (pgindexdesc == NULL)
4243  pgindexdesc = BuildHardcodedDescriptor(Natts_pg_index,
4244  Desc_pg_index);
4245 
4246  return pgindexdesc;
4247 }
4248 
4249 /*
4250  * Load any default attribute value definitions for the relation.
4251  */
4252 static void
4254 {
4255  AttrDefault *attrdef = relation->rd_att->constr->defval;
4256  int ndef = relation->rd_att->constr->num_defval;
4257  Relation adrel;
4258  SysScanDesc adscan;
4259  ScanKeyData skey;
4260  HeapTuple htup;
4261  Datum val;
4262  bool isnull;
4263  int found;
4264  int i;
4265 
4266  ScanKeyInit(&skey,
4267  Anum_pg_attrdef_adrelid,
4268  BTEqualStrategyNumber, F_OIDEQ,
4269  ObjectIdGetDatum(RelationGetRelid(relation)));
4270 
4271  adrel = table_open(AttrDefaultRelationId, AccessShareLock);
4272  adscan = systable_beginscan(adrel, AttrDefaultIndexId, true,
4273  NULL, 1, &skey);
4274  found = 0;
4275 
4276  while (HeapTupleIsValid(htup = systable_getnext(adscan)))
4277  {
4278  Form_pg_attrdef adform = (Form_pg_attrdef) GETSTRUCT(htup);
4279  Form_pg_attribute attr = TupleDescAttr(relation->rd_att, adform->adnum - 1);
4280 
4281  for (i = 0; i < ndef; i++)
4282  {
4283  if (adform->adnum != attrdef[i].adnum)
4284  continue;
4285  if (attrdef[i].adbin != NULL)
4286  elog(WARNING, "multiple attrdef records found for attr %s of rel %s",
4287  NameStr(attr->attname),
4288  RelationGetRelationName(relation));
4289  else
4290  found++;
4291 
4292  val = fastgetattr(htup,
4293  Anum_pg_attrdef_adbin,
4294  adrel->rd_att, &isnull);
4295  if (isnull)
4296  elog(WARNING, "null adbin for attr %s of rel %s",
4297  NameStr(attr->attname),
4298  RelationGetRelationName(relation));
4299  else
4300  {
4301  /* detoast and convert to cstring in caller's context */
4302  char *s = TextDatumGetCString(val);
4303 
4305  pfree(s);
4306  }
4307  break;
4308  }
4309 
4310  if (i >= ndef)
4311  elog(WARNING, "unexpected attrdef record found for attr %d of rel %s",
4312  adform->adnum, RelationGetRelationName(relation));
4313  }
4314 
4315  systable_endscan(adscan);
4316  table_close(adrel, AccessShareLock);
4317 }
4318 
4319 /*
4320  * Load any check constraints for the relation.
4321  */
4322 static void
4324 {
4325  ConstrCheck *check = relation->rd_att->constr->check;
4326  int ncheck = relation->rd_att->constr->num_check;
4327  Relation conrel;
4328  SysScanDesc conscan;
4329  ScanKeyData skey[1];
4330  HeapTuple htup;
4331  int found = 0;
4332 
4333  ScanKeyInit(&skey[0],
4334  Anum_pg_constraint_conrelid,
4335  BTEqualStrategyNumber, F_OIDEQ,
4336  ObjectIdGetDatum(RelationGetRelid(relation)));
4337 
4338  conrel = table_open(ConstraintRelationId, AccessShareLock);
4339  conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
4340  NULL, 1, skey);
4341 
4342  while (HeapTupleIsValid(htup = systable_getnext(conscan)))
4343  {
4345  Datum val;
4346  bool isnull;
4347  char *s;
4348 
4349  /* We want check constraints only */
4350  if (conform->contype != CONSTRAINT_CHECK)
4351  continue;
4352 
4353  if (found >= ncheck)
4354  elog(ERROR, "unexpected constraint record found for rel %s",
4355  RelationGetRelationName(relation));
4356 
4357  check[found].ccvalid = conform->convalidated;
4358  check[found].ccnoinherit = conform->connoinherit;
4360  NameStr(conform->conname));
4361 
4362  /* Grab and test conbin is actually set */
4363  val = fastgetattr(htup,
4364  Anum_pg_constraint_conbin,
4365  conrel->rd_att, &isnull);
4366  if (isnull)
4367  elog(ERROR, "null conbin for rel %s",
4368  RelationGetRelationName(relation));
4369 
4370  /* detoast and convert to cstring in caller's context */
4371  s = TextDatumGetCString(val);
4372  check[found].ccbin = MemoryContextStrdup(CacheMemoryContext, s);
4373  pfree(s);
4374 
4375  found++;
4376  }
4377 
4378  systable_endscan(conscan);
4379  table_close(conrel, AccessShareLock);
4380 
4381  if (found != ncheck)
4382  elog(ERROR, "%d constraint record(s) missing for rel %s",
4383  ncheck - found, RelationGetRelationName(relation));
4384 
4385  /* Sort the records so that CHECKs are applied in a deterministic order */
4386  if (ncheck > 1)
4387  qsort(check, ncheck, sizeof(ConstrCheck), CheckConstraintCmp);
4388 }
4389 
4390 /*
4391  * qsort comparator to sort ConstrCheck entries by name
4392  */
4393 static int
4394 CheckConstraintCmp(const void *a, const void *b)
4395 {
4396  const ConstrCheck *ca = (const ConstrCheck *) a;
4397  const ConstrCheck *cb = (const ConstrCheck *) b;
4398 
4399  return strcmp(ca->ccname, cb->ccname);
4400 }
4401 
4402 /*
4403  * RelationGetFKeyList -- get a list of foreign key info for the relation
4404  *
4405  * Returns a list of ForeignKeyCacheInfo structs, one per FK constraining
4406  * the given relation. This data is a direct copy of relevant fields from
4407  * pg_constraint. The list items are in no particular order.
4408  *
4409  * CAUTION: the returned list is part of the relcache's data, and could
4410  * vanish in a relcache entry reset. Callers must inspect or copy it
4411  * before doing anything that might trigger a cache flush, such as
4412  * system catalog accesses. copyObject() can be used if desired.
4413  * (We define it this way because current callers want to filter and
4414  * modify the list entries anyway, so copying would be a waste of time.)
4415  */
4416 List *
4418 {
4419  List *result;
4420  Relation conrel;
4421  SysScanDesc conscan;
4422  ScanKeyData skey;
4423  HeapTuple htup;
4424  List *oldlist;
4425  MemoryContext oldcxt;
4426 
4427  /* Quick exit if we already computed the list. */
4428  if (relation->rd_fkeyvalid)
4429  return relation->rd_fkeylist;
4430 
4431  /* Fast path: non-partitioned tables without triggers can't have FKs */
4432  if (!relation->rd_rel->relhastriggers &&
4433  relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
4434  return NIL;
4435 
4436  /*
4437  * We build the list we intend to return (in the caller's context) while
4438  * doing the scan. After successfully completing the scan, we copy that
4439  * list into the relcache entry. This avoids cache-context memory leakage
4440  * if we get some sort of error partway through.
4441  */
4442  result = NIL;
4443 
4444  /* Prepare to scan pg_constraint for entries having conrelid = this rel. */
4445  ScanKeyInit(&skey,
4446  Anum_pg_constraint_conrelid,
4447  BTEqualStrategyNumber, F_OIDEQ,
4448  ObjectIdGetDatum(RelationGetRelid(relation)));
4449 
4450  conrel = table_open(ConstraintRelationId, AccessShareLock);
4451  conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
4452  NULL, 1, &skey);
4453 
4454  while (HeapTupleIsValid(htup = systable_getnext(conscan)))
4455  {
4456  Form_pg_constraint constraint = (Form_pg_constraint) GETSTRUCT(htup);
4457  ForeignKeyCacheInfo *info;
4458 
4459  /* consider only foreign keys */
4460  if (constraint->contype != CONSTRAINT_FOREIGN)
4461  continue;
4462 
4463  info = makeNode(ForeignKeyCacheInfo);
4464  info->conoid = constraint->oid;
4465  info->conrelid = constraint->conrelid;
4466  info->confrelid = constraint->confrelid;
4467 
4468  DeconstructFkConstraintRow(htup, &info->nkeys,
4469  info->conkey,
4470  info->confkey,
4471  info->conpfeqop,
4472  NULL, NULL);
4473 
4474  /* Add FK's node to the result list */
4475  result = lappend(result, info);
4476  }
4477 
4478  systable_endscan(conscan);
4479  table_close(conrel, AccessShareLock);
4480 
4481  /* Now save a copy of the completed list in the relcache entry. */
4483  oldlist = relation->rd_fkeylist;
4484  relation->rd_fkeylist = copyObject(result);
4485  relation->rd_fkeyvalid = true;
4486  MemoryContextSwitchTo(oldcxt);
4487 
4488  /* Don't leak the old list, if there is one */
4489  list_free_deep(oldlist);
4490 
4491  return result;
4492 }
4493 
4494 /*
4495  * RelationGetIndexList -- get a list of OIDs of indexes on this relation
4496  *
4497  * The index list is created only if someone requests it. We scan pg_index
4498  * to find relevant indexes, and add the list to the relcache entry so that
4499  * we won't have to compute it again. Note that shared cache inval of a
4500  * relcache entry will delete the old list and set rd_indexvalid to false,
4501  * so that we must recompute the index list on next request. This handles
4502  * creation or deletion of an index.
4503  *
4504  * Indexes that are marked not indislive are omitted from the returned list.
4505  * Such indexes are expected to be dropped momentarily, and should not be
4506  * touched at all by any caller of this function.
4507  *
4508  * The returned list is guaranteed to be sorted in order by OID. This is
4509  * needed by the executor, since for index types that we obtain exclusive
4510  * locks on when updating the index, all backends must lock the indexes in
4511  * the same order or we will get deadlocks (see ExecOpenIndices()). Any
4512  * consistent ordering would do, but ordering by OID is easy.
4513  *
4514  * Since shared cache inval causes the relcache's copy of the list to go away,
4515  * we return a copy of the list palloc'd in the caller's context. The caller
4516  * may list_free() the returned list after scanning it. This is necessary
4517  * since the caller will typically be doing syscache lookups on the relevant
4518  * indexes, and syscache lookup could cause SI messages to be processed!
4519  *
4520  * In exactly the same way, we update rd_pkindex, which is the OID of the
4521  * relation's primary key index if any, else InvalidOid; and rd_replidindex,
4522  * which is the pg_class OID of an index to be used as the relation's
4523  * replication identity index, or InvalidOid if there is no such index.
4524  */
4525 List *
4527 {
4528  Relation indrel;
4529  SysScanDesc indscan;
4530  ScanKeyData skey;
4531  HeapTuple htup;
4532  List *result;
4533  List *oldlist;
4534  char replident = relation->rd_rel->relreplident;
4535  Oid pkeyIndex = InvalidOid;
4536  Oid candidateIndex = InvalidOid;
4537  MemoryContext oldcxt;
4538 
4539  /* Quick exit if we already computed the list. */
4540  if (relation->rd_indexvalid)
4541  return list_copy(relation->rd_indexlist);
4542 
4543  /*
4544  * We build the list we intend to return (in the caller's context) while
4545  * doing the scan. After successfully completing the scan, we copy that
4546  * list into the relcache entry. This avoids cache-context memory leakage
4547  * if we get some sort of error partway through.
4548  */
4549  result = NIL;
4550 
4551  /* Prepare to scan pg_index for entries having indrelid = this rel. */
4552  ScanKeyInit(&skey,
4553  Anum_pg_index_indrelid,
4554  BTEqualStrategyNumber, F_OIDEQ,
4555  ObjectIdGetDatum(RelationGetRelid(relation)));
4556 
4557  indrel = table_open(IndexRelationId, AccessShareLock);
4558  indscan = systable_beginscan(indrel, IndexIndrelidIndexId, true,
4559  NULL, 1, &skey);
4560 
4561  while (HeapTupleIsValid(htup = systable_getnext(indscan)))
4562  {
4564 
4565  /*
4566  * Ignore any indexes that are currently being dropped. This will
4567  * prevent them from being searched, inserted into, or considered in
4568  * HOT-safety decisions. It's unsafe to touch such an index at all
4569  * since its catalog entries could disappear at any instant.
4570  */
4571  if (!index->indislive)
4572  continue;
4573 
4574  /* add index's OID to result list */
4575  result = lappend_oid(result, index->indexrelid);
4576 
4577  /*
4578  * Invalid, non-unique, non-immediate or predicate indexes aren't
4579  * interesting for either oid indexes or replication identity indexes,
4580  * so don't check them.
4581  */
4582  if (!index->indisvalid || !index->indisunique ||
4583  !index->indimmediate ||
4584  !heap_attisnull(htup, Anum_pg_index_indpred, NULL))
4585  continue;
4586 
4587  /* remember primary key index if any */
4588  if (index->indisprimary)
4589  pkeyIndex = index->indexrelid;
4590 
4591  /* remember explicitly chosen replica index */
4592  if (index->indisreplident)
4593  candidateIndex = index->indexrelid;
4594  }
4595 
4596  systable_endscan(indscan);
4597 
4598  table_close(indrel, AccessShareLock);
4599 
4600  /* Sort the result list into OID order, per API spec. */
4601  list_sort(result, list_oid_cmp);
4602 
4603  /* Now save a copy of the completed list in the relcache entry. */
4605  oldlist = relation->rd_indexlist;
4606  relation->rd_indexlist = list_copy(result);
4607  relation->rd_pkindex = pkeyIndex;
4608  if (replident == REPLICA_IDENTITY_DEFAULT && OidIsValid(pkeyIndex))
4609  relation->rd_replidindex = pkeyIndex;
4610  else if (replident == REPLICA_IDENTITY_INDEX && OidIsValid(candidateIndex))
4611  relation->rd_replidindex = candidateIndex;
4612  else
4613  relation->rd_replidindex = InvalidOid;
4614  relation->rd_indexvalid = true;
4615  MemoryContextSwitchTo(oldcxt);
4616 
4617  /* Don't leak the old list, if there is one */
4618  list_free(oldlist);
4619 
4620  return result;
4621 }
4622 
4623 /*
4624  * RelationGetStatExtList
4625  * get a list of OIDs of statistics objects on this relation
4626  *
4627  * The statistics list is created only if someone requests it, in a way
4628  * similar to RelationGetIndexList(). We scan pg_statistic_ext to find
4629  * relevant statistics, and add the list to the relcache entry so that we
4630  * won't have to compute it again. Note that shared cache inval of a
4631  * relcache entry will delete the old list and set rd_statvalid to 0,
4632  * so that we must recompute the statistics list on next request. This
4633  * handles creation or deletion of a statistics object.
4634  *
4635  * The returned list is guaranteed to be sorted in order by OID, although
4636  * this is not currently needed.
4637  *
4638  * Since shared cache inval causes the relcache's copy of the list to go away,
4639  * we return a copy of the list palloc'd in the caller's context. The caller
4640  * may list_free() the returned list after scanning it. This is necessary
4641  * since the caller will typically be doing syscache lookups on the relevant
4642  * statistics, and syscache lookup could cause SI messages to be processed!
4643  */
4644 List *
4646 {
4647  Relation indrel;
4648  SysScanDesc indscan;
4649  ScanKeyData skey;
4650  HeapTuple htup;
4651  List *result;
4652  List *oldlist;
4653  MemoryContext oldcxt;
4654 
4655  /* Quick exit if we already computed the list. */
4656  if (relation->rd_statvalid != 0)
4657  return list_copy(relation->rd_statlist);
4658 
4659  /*
4660  * We build the list we intend to return (in the caller's context) while
4661  * doing the scan. After successfully completing the scan, we copy that
4662  * list into the relcache entry. This avoids cache-context memory leakage
4663  * if we get some sort of error partway through.
4664  */
4665  result = NIL;
4666 
4667  /*
4668  * Prepare to scan pg_statistic_ext for entries having stxrelid = this
4669  * rel.
4670  */
4671  ScanKeyInit(&skey,
4672  Anum_pg_statistic_ext_stxrelid,
4673  BTEqualStrategyNumber, F_OIDEQ,
4674  ObjectIdGetDatum(RelationGetRelid(relation)));
4675 
4676  indrel = table_open(StatisticExtRelationId, AccessShareLock);
4677  indscan = systable_beginscan(indrel, StatisticExtRelidIndexId, true,
4678  NULL, 1, &skey);
4679 
4680  while (HeapTupleIsValid(htup = systable_getnext(indscan)))
4681  {
4682  Oid oid = ((Form_pg_statistic_ext) GETSTRUCT(htup))->oid;
4683 
4684  result = lappend_oid(result, oid);
4685  }
4686 
4687  systable_endscan(indscan);
4688 
4689  table_close(indrel, AccessShareLock);
4690 
4691  /* Sort the result list into OID order, per API spec. */
4692  list_sort(result, list_oid_cmp);
4693 
4694  /* Now save a copy of the completed list in the relcache entry. */
4696  oldlist = relation->rd_statlist;
4697  relation->rd_statlist = list_copy(result);
4698 
4699  relation->rd_statvalid = true;
4700  MemoryContextSwitchTo(oldcxt);
4701 
4702  /* Don't leak the old list, if there is one */
4703  list_free(oldlist);
4704 
4705  return result;
4706 }
4707 
4708 /*
4709  * RelationGetPrimaryKeyIndex -- get OID of the relation's primary key index
4710  *
4711  * Returns InvalidOid if there is no such index.
4712  */
4713 Oid
4715 {
4716  List *ilist;
4717 
4718  if (!relation->rd_indexvalid)
4719  {
4720  /* RelationGetIndexList does the heavy lifting. */
4721  ilist = RelationGetIndexList(relation);
4722  list_free(ilist);
4723  Assert(relation->rd_indexvalid);
4724  }
4725 
4726  return relation->rd_pkindex;
4727 }
4728 
4729 /*
4730  * RelationGetReplicaIndex -- get OID of the relation's replica identity index
4731  *
4732  * Returns InvalidOid if there is no such index.
4733  */
4734 Oid
4736 {
4737  List *ilist;
4738 
4739  if (!relation->rd_indexvalid)
4740  {
4741  /* RelationGetIndexList does the heavy lifting. */
4742  ilist = RelationGetIndexList(relation);
4743  list_free(ilist);
4744  Assert(relation->rd_indexvalid);
4745  }
4746 
4747  return relation->rd_replidindex;
4748 }
4749 
4750 /*
4751  * RelationGetIndexExpressions -- get the index expressions for an index
4752  *
4753  * We cache the result of transforming pg_index.indexprs into a node tree.
4754  * If the rel is not an index or has no expressional columns, we return NIL.
4755  * Otherwise, the returned tree is copied into the caller's memory context.
4756  * (We don't want to return a pointer to the relcache copy, since it could
4757  * disappear due to relcache invalidation.)
4758  */
4759 List *
4761 {
4762  List *result;
4763  Datum exprsDatum;
4764  bool isnull;
4765  char *exprsString;
4766  MemoryContext oldcxt;
4767 
4768  /* Quick exit if we already computed the result. */
4769  if (relation->rd_indexprs)
4770  return copyObject(relation->rd_indexprs);
4771 
4772  /* Quick exit if there is nothing to do. */
4773  if (relation->rd_indextuple == NULL ||
4774  heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
4775  return NIL;
4776 
4777  /*
4778  * We build the tree we intend to return in the caller's context. After
4779  * successfully completing the work, we copy it into the relcache entry.
4780  * This avoids problems if we get some sort of error partway through.
4781  */
4782  exprsDatum = heap_getattr(relation->rd_indextuple,
4783  Anum_pg_index_indexprs,
4785  &isnull);
4786  Assert(!isnull);
4787  exprsString = TextDatumGetCString(exprsDatum);
4788  result = (List *) stringToNode(exprsString);
4789  pfree(exprsString);
4790 
4791  /*
4792  * Run the expressions through eval_const_expressions. This is not just an
4793  * optimization, but is necessary, because the planner will be comparing
4794  * them to similarly-processed qual clauses, and may fail to detect valid
4795  * matches without this. We must not use canonicalize_qual, however,
4796  * since these aren't qual expressions.
4797  */
4798  result = (List *) eval_const_expressions(NULL, (Node *) result);
4799 
4800  /* May as well fix opfuncids too */
4801  fix_opfuncids((Node *) result);
4802 
4803  /* Now save a copy of the completed tree in the relcache entry. */
4804  oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
4805  relation->rd_indexprs = copyObject(result);
4806  MemoryContextSwitchTo(oldcxt);
4807 
4808  return result;
4809 }
4810 
4811 /*
4812  * RelationGetDummyIndexExpressions -- get dummy expressions for an index
4813  *
4814  * Return a list of dummy expressions (just Const nodes) with the same
4815  * types/typmods/collations as the index's real expressions. This is
4816  * useful in situations where we don't want to run any user-defined code.
4817  */
4818 List *
4820 {
4821  List *result;
4822  Datum exprsDatum;
4823  bool isnull;
4824  char *exprsString;
4825  List *rawExprs;
4826  ListCell *lc;
4827 
4828  /* Quick exit if there is nothing to do. */
4829  if (relation->rd_indextuple == NULL ||
4830  heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
4831  return NIL;
4832 
4833  /* Extract raw node tree(s) from index tuple. */
4834  exprsDatum = heap_getattr(relation->rd_indextuple,
4835  Anum_pg_index_indexprs,
4837  &isnull);
4838  Assert(!isnull);
4839  exprsString = TextDatumGetCString(exprsDatum);
4840  rawExprs = (List *) stringToNode(exprsString);
4841  pfree(exprsString);
4842 
4843  /* Construct null Consts; the typlen and typbyval are arbitrary. */
4844  result = NIL;
4845  foreach(lc, rawExprs)
4846  {
4847  Node *rawExpr = (Node *) lfirst(lc);
4848 
4849  result = lappend(result,
4850  makeConst(exprType(rawExpr),
4851  exprTypmod(rawExpr),
4852  exprCollation(rawExpr),
4853  1,
4854  (Datum) 0,
4855  true,
4856  true));
4857  }
4858 
4859  return result;
4860 }
4861 
4862 /*
4863  * RelationGetIndexPredicate -- get the index predicate for an index
4864  *
4865  * We cache the result of transforming pg_index.indpred into an implicit-AND
4866  * node tree (suitable for use in planning).
4867  * If the rel is not an index or has no predicate, we return NIL.
4868  * Otherwise, the returned tree is copied into the caller's memory context.
4869  * (We don't want to return a pointer to the relcache copy, since it could
4870  * disappear due to relcache invalidation.)
4871  */
4872 List *
4874 {
4875  List *result;
4876  Datum predDatum;
4877  bool isnull;
4878  char *predString;
4879  MemoryContext oldcxt;
4880 
4881  /* Quick exit if we already computed the result. */
4882  if (relation->rd_indpred)
4883  return copyObject(relation->rd_indpred);
4884 
4885  /* Quick exit if there is nothing to do. */
4886  if (relation->rd_indextuple == NULL ||
4887  heap_attisnull(relation->rd_indextuple, Anum_pg_index_indpred, NULL))
4888  return NIL;
4889 
4890  /*
4891  * We build the tree we intend to return in the caller's context. After
4892  * successfully completing the work, we copy it into the relcache entry.
4893  * This avoids problems if we get some sort of error partway through.
4894  */
4895  predDatum = heap_getattr(relation->rd_indextuple,
4896  Anum_pg_index_indpred,
4898  &isnull);
4899  Assert(!isnull);
4900  predString = TextDatumGetCString(predDatum);
4901  result = (List *) stringToNode(predString);
4902  pfree(predString);
4903 
4904  /*
4905  * Run the expression through const-simplification and canonicalization.
4906  * This is not just an optimization, but is necessary, because the planner
4907  * will be comparing it to similarly-processed qual clauses, and may fail
4908  * to detect valid matches without this. This must match the processing
4909  * done to qual clauses in preprocess_expression()! (We can skip the
4910  * stuff involving subqueries, however, since we don't allow any in index
4911  * predicates.)
4912  */
4913  result = (List *) eval_const_expressions(NULL, (Node *) result);
4914 
4915  result = (List *) canonicalize_qual((Expr *) result, false);
4916 
4917  /* Also convert to implicit-AND format */
4918  result = make_ands_implicit((Expr *) result);
4919 
4920  /* May as well fix opfuncids too */
4921  fix_opfuncids((Node *) result);
4922 
4923  /* Now save a copy of the completed tree in the relcache entry. */
4924  oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
4925  relation->rd_indpred = copyObject(result);
4926  MemoryContextSwitchTo(oldcxt);
4927 
4928  return result;
4929 }
4930 
4931 /*
4932  * RelationGetIndexAttrBitmap -- get a bitmap of index attribute numbers
4933  *
4934  * The result has a bit set for each attribute used anywhere in the index
4935  * definitions of all the indexes on this relation. (This includes not only
4936  * simple index keys, but attributes used in expressions and partial-index
4937  * predicates.)
4938  *
4939  * Depending on attrKind, a bitmap covering the attnums for all index columns,
4940  * for all potential foreign key columns, or for all columns in the configured
4941  * replica identity index is returned.
4942  *
4943  * Attribute numbers are offset by FirstLowInvalidHeapAttributeNumber so that
4944  * we can include system attributes (e.g., OID) in the bitmap representation.
4945  *
4946  * Caller had better hold at least RowExclusiveLock on the target relation
4947  * to ensure it is safe (deadlock-free) for us to take locks on the relation's
4948  * indexes. Note that since the introduction of CREATE INDEX CONCURRENTLY,
4949  * that lock level doesn't guarantee a stable set of indexes, so we have to
4950  * be prepared to retry here in case of a change in the set of indexes.
4951  *
4952  * The returned result is palloc'd in the caller's memory context and should
4953  * be bms_free'd when not needed anymore.
4954  */
4955 Bitmapset *
4957 {
4958  Bitmapset *indexattrs; /* indexed columns */
4959  Bitmapset *uindexattrs; /* columns in unique indexes */
4960  Bitmapset *pkindexattrs; /* columns in the primary index */
4961  Bitmapset *idindexattrs; /* columns in the replica identity */
4962  List *indexoidlist;
4963  List *newindexoidlist;
4964  Oid relpkindex;
4965  Oid relreplindex;
4966  ListCell *l;
4967  MemoryContext oldcxt;
4968 
4969  /* Quick exit if we already computed the result. */
4970  if (relation->rd_indexattr != NULL)
4971  {
4972  switch (attrKind)
4973  {
4974  case INDEX_ATTR_BITMAP_ALL:
4975  return bms_copy(relation->rd_indexattr);
4976  case INDEX_ATTR_BITMAP_KEY:
4977  return bms_copy(relation->rd_keyattr);
4979  return bms_copy(relation->rd_pkattr);
4981  return bms_copy(relation->rd_idattr);
4982  default:
4983  elog(ERROR, "unknown attrKind %u", attrKind);
4984  }
4985  }
4986 
4987  /* Fast path if definitely no indexes */
4988  if (!RelationGetForm(relation)->relhasindex)
4989  return NULL;
4990 
4991  /*
4992  * Get cached list of index OIDs. If we have to start over, we do so here.
4993  */
4994 restart:
4995  indexoidlist = RelationGetIndexList(relation);
4996 
4997  /* Fall out if no indexes (but relhasindex was set) */
4998  if (indexoidlist == NIL)
4999  return NULL;
5000 
5001  /*
5002  * Copy the rd_pkindex and rd_replidindex values computed by
5003  * RelationGetIndexList before proceeding. This is needed because a
5004  * relcache flush could occur inside index_open below, resetting the
5005  * fields managed by RelationGetIndexList. We need to do the work with
5006  * stable values of these fields.
5007  */
5008  relpkindex = relation->rd_pkindex;
5009  relreplindex = relation->rd_replidindex;
5010 
5011  /*
5012  * For each index, add referenced attributes to indexattrs.
5013  *
5014  * Note: we consider all indexes returned by RelationGetIndexList, even if
5015  * they are not indisready or indisvalid. This is important because an
5016  * index for which CREATE INDEX CONCURRENTLY has just started must be
5017  * included in HOT-safety decisions (see README.HOT). If a DROP INDEX
5018  * CONCURRENTLY is far enough along that we should ignore the index, it
5019  * won't be returned at all by RelationGetIndexList.
5020  */
5021  indexattrs = NULL;
5022  uindexattrs = NULL;
5023  pkindexattrs = NULL;
5024  idindexattrs = NULL;
5025  foreach(l, indexoidlist)
5026  {
5027  Oid indexOid = lfirst_oid(l);
5028  Relation indexDesc;
5029  Datum datum;
5030  bool isnull;
5031  Node *indexExpressions;
5032  Node *indexPredicate;
5033  int i;
5034  bool isKey; /* candidate key */
5035  bool isPK; /* primary key */
5036  bool isIDKey; /* replica identity index */
5037 
5038  indexDesc = index_open(indexOid, AccessShareLock);
5039 
5040  /*
5041  * Extract index expressions and index predicate. Note: Don't use
5042  * RelationGetIndexExpressions()/RelationGetIndexPredicate(), because
5043  * those might run constant expressions evaluation, which needs a
5044  * snapshot, which we might not have here. (Also, it's probably more
5045  * sound to collect the bitmaps before any transformations that might
5046  * eliminate columns, but the practical impact of this is limited.)
5047  */
5048 
5049  datum = heap_getattr(indexDesc->rd_indextuple, Anum_pg_index_indexprs,
5050  GetPgIndexDescriptor(), &isnull);
5051  if (!isnull)
5052  indexExpressions = stringToNode(TextDatumGetCString(datum));
5053  else
5054  indexExpressions = NULL;
5055 
5056  datum = heap_getattr(indexDesc->rd_indextuple, Anum_pg_index_indpred,
5057  GetPgIndexDescriptor(), &isnull);
5058  if (!isnull)
5059  indexPredicate = stringToNode(TextDatumGetCString(datum));
5060  else
5061  indexPredicate = NULL;
5062 
5063  /* Can this index be referenced by a foreign key? */
5064  isKey = indexDesc->rd_index->indisunique &&
5065  indexExpressions == NULL &&
5066  indexPredicate == NULL;
5067 
5068  /* Is this a primary key? */
5069  isPK = (indexOid == relpkindex);
5070 
5071  /* Is this index the configured (or default) replica identity? */
5072  isIDKey = (indexOid == relreplindex);
5073 
5074  /* Collect simple attribute references */
5075  for (i = 0; i < indexDesc->rd_index->indnatts; i++)
5076  {
5077  int attrnum = indexDesc->rd_index->indkey.values[i];
5078 
5079  /*
5080  * Since we have covering indexes with non-key columns, we must
5081  * handle them accurately here. non-key columns must be added into
5082  * indexattrs, since they are in index, and HOT-update shouldn't
5083  * miss them. Obviously, non-key columns couldn't be referenced by
5084  * foreign key or identity key. Hence we do not include them into
5085  * uindexattrs, pkindexattrs and idindexattrs bitmaps.
5086  */
5087  if (attrnum != 0)
5088  {
5089  indexattrs = bms_add_member(indexattrs,
5091 
5092  if (isKey && i < indexDesc->rd_index->indnkeyatts)
5093  uindexattrs = bms_add_member(uindexattrs,
5095 
5096  if (isPK && i < indexDesc->rd_index->indnkeyatts)
5097  pkindexattrs = bms_add_member(pkindexattrs,
5099 
5100  if (isIDKey && i < indexDesc->rd_index->indnkeyatts)
5101  idindexattrs = bms_add_member(idindexattrs,
5103  }
5104  }
5105 
5106  /* Collect all attributes used in expressions, too */
5107  pull_varattnos(indexExpressions, 1, &indexattrs);
5108 
5109  /* Collect all attributes in the index predicate, too */
5110  pull_varattnos(indexPredicate, 1, &indexattrs);
5111 
5112  index_close(indexDesc, AccessShareLock);
5113  }
5114 
5115  /*
5116  * During one of the index_opens in the above loop, we might have received
5117  * a relcache flush event on this relcache entry, which might have been
5118  * signaling a change in the rel's index list. If so, we'd better start
5119  * over to ensure we deliver up-to-date attribute bitmaps.
5120  */
5121  newindexoidlist = RelationGetIndexList(relation);
5122  if (equal(indexoidlist, newindexoidlist) &&
5123  relpkindex == relation->rd_pkindex &&
5124  relreplindex == relation->rd_replidindex)
5125  {
5126  /* Still the same index set, so proceed */
5127  list_free(newindexoidlist);
5128  list_free(indexoidlist);
5129  }
5130  else
5131  {
5132  /* Gotta do it over ... might as well not leak memory */
5133  list_free(newindexoidlist);
5134  list_free(indexoidlist);
5135  bms_free(uindexattrs);
5136  bms_free(pkindexattrs);
5137  bms_free(idindexattrs);
5138  bms_free(indexattrs);
5139 
5140  goto restart;
5141  }
5142 
5143  /* Don't leak the old values of these bitmaps, if any */
5144  bms_free(relation->rd_indexattr);
5145  relation->rd_indexattr = NULL;
5146  bms_free(relation->rd_keyattr);
5147  relation->rd_keyattr = NULL;
5148  bms_free(relation->rd_pkattr);
5149  relation->rd_pkattr = NULL;
5150  bms_free(relation->rd_idattr);
5151  relation->rd_idattr = NULL;
5152 
5153  /*
5154  * Now save copies of the bitmaps in the relcache entry. We intentionally
5155  * set rd_indexattr last, because that's the one that signals validity of
5156  * the values; if we run out of memory before making that copy, we won't
5157  * leave the relcache entry looking like the other ones are valid but
5158  * empty.
5159  */
5161  relation->rd_keyattr = bms_copy(uindexattrs);
5162  relation->rd_pkattr = bms_copy(pkindexattrs);
5163  relation->rd_idattr = bms_copy(idindexattrs);
5164  relation->rd_indexattr = bms_copy(indexattrs);
5165  MemoryContextSwitchTo(oldcxt);
5166 
5167  /* We return our original working copy for caller to play with */
5168  switch (attrKind)
5169  {
5170  case INDEX_ATTR_BITMAP_ALL:
5171  return indexattrs;
5172  case INDEX_ATTR_BITMAP_KEY:
5173  return uindexattrs;
5175  return pkindexattrs;
5177  return idindexattrs;
5178  default:
5179  elog(ERROR, "unknown attrKind %u", attrKind);
5180  return NULL;
5181  }
5182 }
5183 
5184 /*
5185  * RelationGetExclusionInfo -- get info about index's exclusion constraint
5186  *
5187  * This should be called only for an index that is known to have an
5188  * associated exclusion constraint. It returns arrays (palloc'd in caller's
5189  * context) of the exclusion operator OIDs, their underlying functions'
5190  * OIDs, and their strategy numbers in the index's opclasses. We cache
5191  * all this information since it requires a fair amount of work to get.
5192  */
5193 void
5195  Oid **operators,
5196  Oid **procs,
5197  uint16 **strategies)
5198 {
5199  int indnkeyatts;
5200  Oid *ops;
5201  Oid *funcs;
5202  uint16 *strats;
5203  Relation conrel;
5204  SysScanDesc conscan;
5205  ScanKeyData skey[1];
5206  HeapTuple htup;
5207  bool found;
5208  MemoryContext oldcxt;
5209  int i;
5210 
5211  indnkeyatts = IndexRelationGetNumberOfKeyAttributes(indexRelation);
5212 
5213  /* Allocate result space in caller context */
5214  *operators = ops = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
5215  *procs = funcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
5216  *strategies = strats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
5217 
5218  /* Quick exit if we have the data cached already */
5219  if (indexRelation->rd_exclstrats != NULL)
5220  {
5221  memcpy(ops, indexRelation->rd_exclops, sizeof(Oid) * indnkeyatts);
5222  memcpy(funcs, indexRelation->rd_exclprocs, sizeof(Oid) * indnkeyatts);
5223  memcpy(strats, indexRelation->rd_exclstrats, sizeof(uint16) * indnkeyatts);
5224  return;
5225  }
5226 
5227  /*
5228  * Search pg_constraint for the constraint associated with the index. To
5229  * make this not too painfully slow, we use the index on conrelid; that
5230  * will hold the parent relation's OID not the index's own OID.
5231  *
5232  * Note: if we wanted to rely on the constraint name matching the index's
5233  * name, we could just do a direct lookup using pg_constraint's unique
5234  * index. For the moment it doesn't seem worth requiring that.
5235  */
5236  ScanKeyInit(&skey[0],
5237  Anum_pg_constraint_conrelid,
5238  BTEqualStrategyNumber, F_OIDEQ,
5239  ObjectIdGetDatum(indexRelation->rd_index->indrelid));
5240 
5241  conrel = table_open(ConstraintRelationId, AccessShareLock);
5242  conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
5243  NULL, 1, skey);
5244  found = false;
5245 
5246  while (HeapTupleIsValid(htup = systable_getnext(conscan)))
5247  {
5249  Datum val;
5250  bool isnull;
5251  ArrayType *arr;
5252  int nelem;
5253 
5254  /* We want the exclusion constraint owning the index */
5255  if (conform->contype != CONSTRAINT_EXCLUSION ||
5256  conform->conindid != RelationGetRelid(indexRelation))
5257  continue;
5258 
5259  /* There should be only one */
5260  if (found)
5261  elog(ERROR, "unexpected exclusion constraint record found for rel %s",
5262  RelationGetRelationName(indexRelation));
5263  found = true;
5264 
5265  /* Extract the operator OIDS from conexclop */
5266  val = fastgetattr(htup,
5267  Anum_pg_constraint_conexclop,
5268  conrel->rd_att, &isnull);
5269  if (isnull)
5270  elog(ERROR, "null conexclop for rel %s",
5271  RelationGetRelationName(indexRelation));
5272 
5273  arr = DatumGetArrayTypeP(val); /* ensure not toasted */
5274  nelem = ARR_DIMS(arr)[0];
5275  if (ARR_NDIM(arr) != 1 ||
5276  nelem != indnkeyatts ||
5277  ARR_HASNULL(arr) ||
5278  ARR_ELEMTYPE(arr) != OIDOID)
5279  elog(ERROR, "conexclop is not a 1-D Oid array");
5280 
5281  memcpy(ops, ARR_DATA_PTR(arr), sizeof(Oid) * indnkeyatts);
5282  }
5283 
5284  systable_endscan(conscan);
5285  table_close(conrel, AccessShareLock);
5286 
5287  if (!found)
5288  elog(ERROR, "exclusion constraint record missing for rel %s",
5289  RelationGetRelationName(indexRelation));
5290 
5291  /* We need the func OIDs and strategy numbers too */
5292  for (i = 0; i < indnkeyatts; i++)
5293  {
5294  funcs[i] = get_opcode(ops[i]);
5295  strats[i] = get_op_opfamily_strategy(ops[i],
5296  indexRelation->rd_opfamily[i]);
5297  /* shouldn't fail, since it was checked at index creation */
5298  if (strats[i] == InvalidStrategy)
5299  elog(ERROR, "could not find strategy for operator %u in family %u",
5300  ops[i], indexRelation->rd_opfamily[i]);
5301  }
5302 
5303  /* Save a copy of the results in the relcache entry. */
5304  oldcxt = MemoryContextSwitchTo(indexRelation->rd_indexcxt);
5305  indexRelation->rd_exclops = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
5306  indexRelation->rd_exclprocs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
5307  indexRelation->rd_exclstrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
5308  memcpy(indexRelation->rd_exclops, ops, sizeof(Oid) * indnkeyatts);
5309  memcpy(indexRelation->rd_exclprocs, funcs, sizeof(Oid) * indnkeyatts);
5310  memcpy(indexRelation->rd_exclstrats, strats, sizeof(uint16) * indnkeyatts);
5311  MemoryContextSwitchTo(oldcxt);
5312 }
5313 
5314 /*
5315  * Get publication actions for the given relation.
5316  */
5317 struct PublicationActions *
5319 {
5320  List *puboids;
5321  ListCell *lc;
5322  MemoryContext oldcxt;
5323  PublicationActions *pubactions = palloc0(sizeof(PublicationActions));
5324 
5325  /*
5326  * If not publishable, it publishes no actions. (pgoutput_change() will
5327  * ignore it.)
5328  */
5329  if (!is_publishable_relation(relation))
5330  return pubactions;
5331 
5332  if (relation->rd_pubactions)
5333  return memcpy(pubactions, relation->rd_pubactions,
5334  sizeof(PublicationActions));
5335 
5336  /* Fetch the publication membership info. */
5337  puboids = GetRelationPublications(RelationGetRelid(relation));
5338  if (relation->rd_rel->relispartition)
5339  {
5340  /* Add publications that the ancestors are in too. */
5341  List *ancestors = get_partition_ancestors(RelationGetRelid(relation));
5342  ListCell *lc;
5343 
5344  foreach(lc, ancestors)
5345  {
5346  Oid ancestor = lfirst_oid(lc);
5347 
5348  puboids = list_concat_unique_oid(puboids,
5349  GetRelationPublications(ancestor));
5350  }
5351  }
5352  puboids = list_concat_unique_oid(puboids, GetAllTablesPublications());
5353 
5354  foreach(lc, puboids)
5355  {
5356  Oid pubid = lfirst_oid(lc);
5357  HeapTuple tup;
5358  Form_pg_publication pubform;
5359 
5361 
5362  if (!HeapTupleIsValid(tup))
5363  elog(ERROR, "cache lookup failed for publication %u", pubid);
5364 
5365  pubform = (Form_pg_publication) GETSTRUCT(tup);
5366 
5367  pubactions->pubinsert |= pubform->pubinsert;
5368  pubactions->pubupdate |= pubform->pubupdate;
5369  pubactions->pubdelete |= pubform->pubdelete;
5370  pubactions->pubtruncate |= pubform->pubtruncate;
5371 
5372  ReleaseSysCache(tup);
5373 
5374  /*
5375  * If we know everything is replicated, there is no point to check for
5376  * other publications.
5377  */
5378  if (pubactions->pubinsert && pubactions->pubupdate &&
5379  pubactions->pubdelete && pubactions->pubtruncate)
5380  break;
5381  }
5382 
5383  if (relation->rd_pubactions)
5384  {
5385  pfree(relation->rd_pubactions);
5386  relation->rd_pubactions = NULL;
5387  }
5388 
5389  /* Now save copy of the actions in the relcache entry. */
5391  relation->rd_pubactions = palloc(sizeof(PublicationActions));
5392  memcpy(relation->rd_pubactions, pubactions, sizeof(PublicationActions));
5393  MemoryContextSwitchTo(oldcxt);
5394 
5395  return pubactions;
5396 }
5397 
5398 /*
5399  * RelationGetIndexRawAttOptions -- get AM/opclass-specific options for the index
5400  */
5401 Datum *
5403 {
5404  Oid indexrelid = RelationGetRelid(indexrel);
5405  int16 natts = RelationGetNumberOfAttributes(indexrel);
5406  Datum *options = NULL;
5407  int16 attnum;
5408 
5409  for (attnum = 1; attnum <= natts; attnum++)
5410  {
5411  if (indexrel->rd_indam->amoptsprocnum == 0)
5412  continue;
5413 
5414  if (!OidIsValid(index_getprocid(indexrel, attnum,
5415  indexrel->rd_indam->amoptsprocnum)))
5416  continue;
5417 
5418  if (!options)
5419  options = palloc0(sizeof(Datum) * natts);
5420 
5421  options[attnum - 1] = get_attoptions(indexrelid, attnum);
5422  }
5423 
5424  return options;
5425 }
5426 
5427 static bytea **
5428 CopyIndexAttOptions(bytea **srcopts, int natts)
5429 {
5430  bytea **opts = palloc(sizeof(*opts) * natts);
5431 
5432  for (int i = 0; i < natts; i++)
5433  {
5434  bytea *opt = srcopts[i];
5435 
5436  opts[i] = !opt ? NULL : (bytea *)
5437  DatumGetPointer(datumCopy(PointerGetDatum(opt), false, -1));
5438  }
5439 
5440  return opts;
5441 }
5442 
5443 /*
5444  * RelationGetIndexAttOptions
5445  * get AM/opclass-specific options for an index parsed into a binary form
5446  */
5447 bytea **
5449 {
5450  MemoryContext oldcxt;
5451  bytea **opts = relation->rd_opcoptions;
5452  Oid relid = RelationGetRelid(relation);
5453  int natts = RelationGetNumberOfAttributes(relation); /* XXX
5454  * IndexRelationGetNumberOfKeyAttributes */
5455  int i;
5456 
5457  /* Try to copy cached options. */
5458  if (opts)
5459  return copy ? CopyIndexAttOptions(opts, natts) : opts;
5460 
5461  /* Get and parse opclass options. */
5462  opts = palloc0(sizeof(*opts) * natts);
5463 
5464  for (i = 0; i < natts; i++)
5465  {
5467  {
5468  Datum attoptions = get_attoptions(relid, i + 1);
5469 
5470  opts[i] = index_opclass_options(relation, i + 1, attoptions, false);
5471 
5472  if (attoptions != (Datum) 0)
5473  pfree(DatumGetPointer(attoptions));
5474  }
5475  }
5476 
5477  /* Copy parsed options to the cache. */
5478  oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
5479  relation->rd_opcoptions = CopyIndexAttOptions(opts, natts);
5480  MemoryContextSwitchTo(oldcxt);
5481 
5482  if (copy)
5483  return opts;
5484 
5485  for (i = 0; i < natts; i++)
5486  {
5487  if (opts[i])
5488  pfree(opts[i]);
5489  }
5490 
5491  pfree(opts);
5492 
5493  return relation->rd_opcoptions;
5494 }
5495 
5496 /*
5497  * Routines to support ereport() reports of relation-related errors
5498  *
5499  * These could have been put into elog.c, but it seems like a module layering
5500  * violation to have elog.c calling relcache or syscache stuff --- and we
5501  * definitely don't want elog.h including rel.h. So we put them here.
5502  */
5503 
5504 /*
5505  * errtable --- stores schema_name and table_name of a table
5506  * within the current errordata.
5507  */
5508 int
5510 {
5514 
5515  return 0; /* return value does not matter */
5516 }
5517 
5518 /*
5519  * errtablecol --- stores schema_name, table_name and column_name
5520  * of a table column within the current errordata.
5521  *
5522  * The column is specified by attribute number --- for most callers, this is
5523  * easier and less error-prone than getting the column name for themselves.
5524  */
5525 int
5527 {
5529  const char *colname;
5530 
5531  /* Use reldesc if it's a user attribute, else consult the catalogs */
5532  if (attnum > 0 && attnum <= reldesc->natts)
5533  colname = NameStr(TupleDescAttr(reldesc, attnum - 1)->attname);
5534  else
5535  colname = get_attname(RelationGetRelid(rel), attnum, false);
5536 
5537  return errtablecolname(rel, colname);
5538 }
5539 
5540 /*
5541  * errtablecolname --- stores schema_name, table_name and column_name
5542  * of a table column within the current errordata, where the column name is
5543  * given directly rather than extracted from the relation's catalog data.
5544  *
5545  * Don't use this directly unless errtablecol() is inconvenient for some
5546  * reason. This might possibly be needed during intermediate states in ALTER
5547  * TABLE, for instance.
5548  */
5549 int
5550 errtablecolname(Relation rel, const char *colname)
5551 {
5552  errtable(rel);
5554 
5555  return 0; /* return value does not matter */
5556 }
5557 
5558 /*
5559  * errtableconstraint --- stores schema_name, table_name and constraint_name
5560  * of a table-related constraint within the current errordata.
5561  */
5562 int
5563 errtableconstraint(Relation rel, const char *conname)
5564 {
5565  errtable(rel);
5567 
5568  return 0; /* return value does not matter */
5569 }
5570 
5571 
5572 /*
5573  * load_relcache_init_file, write_relcache_init_file
5574  *
5575  * In late 1992, we started regularly having databases with more than
5576  * a thousand classes in them. With this number of classes, it became
5577  * critical to do indexed lookups on the system catalogs.
5578  *
5579  * Bootstrapping these lookups is very hard. We want to be able to
5580  * use an index on pg_attribute, for example, but in order to do so,
5581  * we must have read pg_attribute for the attributes in the index,
5582  * which implies that we need to use the index.
5583  *
5584  * In order to get around the problem, we do the following:
5585  *
5586  * + When the database system is initialized (at initdb time), we
5587  * don't use indexes. We do sequential scans.
5588  *
5589  * + When the backend is started up in normal mode, we load an image
5590  * of the appropriate relation descriptors, in internal format,
5591  * from an initialization file in the data/base/... directory.
5592  *
5593  * + If the initialization file isn't there, then we create the
5594  * relation descriptors using sequential scans and write 'em to
5595  * the initialization file for use by subsequent backends.
5596  *
5597  * As of Postgres 9.0, there is one local initialization file in each
5598  * database, plus one shared initialization file for shared catalogs.
5599  *
5600  * We could dispense with the initialization files and just build the
5601  * critical reldescs the hard way on every backend startup, but that
5602  * slows down backend startup noticeably.
5603  *
5604  * We can in fact go further, and save more relcache entries than
5605  * just the ones that are absolutely critical; this allows us to speed
5606  * up backend startup by not having to build such entries the hard way.
5607  * Presently, all the catalog and index entries that are referred to
5608  * by catcaches are stored in the initialization files.
5609  *
5610  * The same mechanism that detects when catcache and relcache entries
5611  * need to be invalidated (due to catalog updates) also arranges to
5612  * unlink the initialization files when the contents may be out of date.
5613  * The files will then be rebuilt during the next backend startup.
5614  */
5615 
5616 /*
5617  * load_relcache_init_file -- attempt to load cache from the shared
5618  * or local cache init file
5619  *
5620  * If successful, return true and set criticalRelcachesBuilt or
5621  * criticalSharedRelcachesBuilt to true.
5622  * If not successful, return false.
5623  *
5624  * NOTE: we assume we are already switched into CacheMemoryContext.
5625  */
5626 static bool
5628 {
5629  FILE *fp;
5630  char initfilename[MAXPGPATH];
5631  Relation *rels;
5632  int relno,
5633  num_rels,
5634  max_rels,
5635  nailed_rels,
5636  nailed_indexes,
5637  magic;
5638  int i;
5639 
5640  if (shared)
5641  snprintf(initfilename, sizeof(initfilename), "global/%s",
5643  else
5644  snprintf(initfilename, sizeof(initfilename), "%s/%s",
5646 
5647  fp = AllocateFile(initfilename, PG_BINARY_R);
5648  if (fp == NULL)
5649  return false;
5650 
5651  /*
5652  * Read the index relcache entries from the file. Note we will not enter
5653  * any of them into the cache if the read fails partway through; this
5654  * helps to guard against broken init files.
5655  */
5656  max_rels = 100;
5657  rels = (Relation *) palloc(max_rels * sizeof(Relation));
5658  num_rels = 0;
5659  nailed_rels = nailed_indexes = 0;
5660 
5661  /* check for correct magic number (compatible version) */
5662  if (fread(&magic, 1, sizeof(magic), fp) != sizeof(magic))
5663  goto read_failed;
5664  if (magic != RELCACHE_INIT_FILEMAGIC)
5665  goto read_failed;
5666 
5667  for (relno = 0;; relno++)
5668  {
5669  Size len;
5670  size_t nread;
5671  Relation rel;
5672  Form_pg_class relform;
5673  bool has_not_null;
5674 
5675  /* first read the relation descriptor length */
5676  nread = fread(&len, 1, sizeof(len), fp);
5677  if (nread != sizeof(len))
5678  {
5679  if (nread == 0)
5680  break; /* end of file */
5681  goto read_failed;
5682  }
5683 
5684  /* safety check for incompatible relcache layout */
5685  if (len != sizeof(RelationData))
5686  goto read_failed;
5687 
5688  /* allocate another relcache header */
5689  if (num_rels >= max_rels)
5690  {
5691  max_rels *= 2;
5692  rels = (Relation *) repalloc(rels, max_rels * sizeof(Relation));
5693  }
5694 
5695  rel = rels[num_rels++] = (Relation) palloc(len);
5696 
5697  /* then, read the Relation structure */
5698  if (fread(rel, 1, len, fp) != len)
5699  goto read_failed;
5700 
5701  /* next read the relation tuple form */
5702  if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
5703  goto read_failed;
5704 
5705  relform = (Form_pg_class) palloc(len);
5706  if (fread(relform, 1, len, fp) != len)
5707  goto read_failed;
5708 
5709  rel->rd_rel = relform;
5710 
5711  /* initialize attribute tuple forms */
5712  rel->rd_att = CreateTemplateTupleDesc(relform->relnatts);
5713  rel->rd_att->tdrefcount = 1; /* mark as refcounted */
5714 
5715  rel->rd_att->tdtypeid = relform->reltype ? relform->reltype : RECORDOID;
5716  rel->rd_att->tdtypmod = -1; /* just to be sure */
5717 
5718  /* next read all the attribute tuple form data entries */
5719  has_not_null = false;
5720  for (i = 0; i < relform->relnatts; i++)
5721  {
5722  Form_pg_attribute attr = TupleDescAttr(rel->rd_att, i);
5723 
5724  if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
5725  goto read_failed;
5726  if (len != ATTRIBUTE_FIXED_PART_SIZE)
5727  goto read_failed;
5728  if (fread(attr, 1, len, fp) != len)
5729  goto read_failed;
5730 
5731  has_not_null |= attr->attnotnull;
5732  }
5733 
5734  /* next read the access method specific field */
5735  if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
5736  goto read_failed;
5737  if (len > 0)
5738  {
5739  rel->rd_options = palloc(len);
5740  if (fread(rel->rd_options, 1, len, fp) != len)
5741  goto read_failed;
5742  if (len != VARSIZE(rel->rd_options))
5743  goto read_failed; /* sanity check */
5744  }
5745  else
5746  {
5747  rel->rd_options = NULL;
5748  }
5749 
5750  /* mark not-null status */
5751  if (has_not_null)
5752  {
5753  TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
5754 
5755  constr->has_not_null = true;
5756  rel->rd_att->constr = constr;
5757  }
5758 
5759  /*
5760  * If it's an index, there's more to do. Note we explicitly ignore
5761  * partitioned indexes here.
5762  */
5763  if (rel->rd_rel->relkind == RELKIND_INDEX)
5764  {
5765  MemoryContext indexcxt;
5766  Oid *opfamily;
5767  Oid *opcintype;
5768  RegProcedure *support;
5769  int nsupport;
5770  int16 *indoption;
5771  Oid *indcollation;
5772 
5773  /* Count nailed indexes to ensure we have 'em all */
5774  if (rel->rd_isnailed)
5775  nailed_indexes++;
5776 
5777  /* next, read the pg_index tuple */
5778  if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
5779  goto read_failed;
5780 
5781  rel->rd_indextuple = (HeapTuple) palloc(len);
5782  if (fread(rel->rd_indextuple, 1, len, fp) != len)
5783  goto read_failed;
5784 
5785  /* Fix up internal pointers in the tuple -- see heap_copytuple */
5786  rel->rd_indextuple->t_data = (HeapTupleHeader) ((char *) rel->rd_indextuple + HEAPTUPLESIZE);
5788 
5789  /*
5790  * prepare index info context --- parameters should match
5791  * RelationInitIndexAccessInfo
5792  */
5794  "index info",
5796  rel->rd_indexcxt = indexcxt;
5799 
5800  /*
5801  * Now we can fetch the index AM's API struct. (We can't store
5802  * that in the init file, since it contains function pointers that
5803  * might vary across server executions. Fortunately, it should be
5804  * safe to call the amhandler even while bootstrapping indexes.)
5805  */
5806  InitIndexAmRoutine(rel);
5807 
5808  /* next, read the vector of opfamily OIDs */
5809  if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
5810  goto read_failed;
5811 
5812  opfamily = (Oid *) MemoryContextAlloc(indexcxt, len);
5813  if (fread(opfamily, 1, len, fp) != len)
5814  goto read_failed;
5815 
5816  rel->rd_opfamily = opfamily;
5817 
5818  /* next, read the vector of opcintype OIDs */
5819  if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
5820  goto read_failed;
5821 
5822  opcintype = (Oid *) MemoryContextAlloc(indexcxt, len);
5823  if (fread(opcintype, 1, len, fp) != len)
5824  goto read_failed;
5825 
5826  rel->rd_opcintype = opcintype;
5827 
5828  /* next, read the vector of support procedure OIDs */
5829  if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
5830  goto read_failed;
5831  support = (RegProcedure *) MemoryContextAlloc(indexcxt, len);
5832  if (fread(support, 1, len, fp) != len)
5833  goto read_failed;
5834 
5835  rel->rd_support = support;
5836 
5837  /* next, read the vector of collation OIDs */
5838  if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
5839  goto read_failed;
5840 
5841  indcollation = (Oid *) MemoryContextAlloc(indexcxt, len);
5842  if (fread(indcollation, 1, len, fp) != len)
5843  goto read_failed;
5844 
5845  rel->rd_indcollation = indcollation;
5846 
5847  /* finally, read the vector of indoption values */
5848  if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
5849  goto read_failed;
5850 
5851  indoption = (int16 *) MemoryContextAlloc(indexcxt, len);
5852  if (fread(indoption, 1, len, fp) != len)
5853  goto read_failed;
5854 
5855  rel->rd_indoption = indoption;
5856 
5857  /* finally, read the vector of opcoptions values */
5858  rel->rd_opcoptions = (bytea **)
5859  MemoryContextAllocZero(indexcxt, sizeof(*rel->rd_opcoptions) * relform->relnatts);
5860 
5861  for (i = 0; i < relform->relnatts; i++)
5862  {
5863  if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
5864  goto read_failed;
5865 
5866  if (len > 0)
5867  {
5868  rel->rd_opcoptions[i] = (bytea *) MemoryContextAlloc(indexcxt, len);
5869  if (fread(rel->rd_opcoptions[i], 1, len, fp) != len)
5870  goto read_failed;
5871  }
5872  }
5873 
5874  /* set up zeroed fmgr-info vector */
5875  nsupport = relform->relnatts * rel->rd_indam->amsupport;
5876  rel->rd_supportinfo = (FmgrInfo *)
5877  MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
5878  }
5879  else
5880  {
5881  /* Count nailed rels to ensure we have 'em all */
5882  if (rel->rd_isnailed)
5883  nailed_rels++;
5884 
5885  /* Load table AM data */
5886  if (rel->rd_rel->relkind == RELKIND_RELATION ||
5887  rel->rd_rel->relkind == RELKIND_SEQUENCE ||
5888  rel->rd_rel->relkind == RELKIND_TOASTVALUE ||
5889  rel->rd_rel->relkind == RELKIND_MATVIEW)
5891 
5892  Assert(rel->rd_index == NULL);
5893  Assert(rel->rd_indextuple == NULL);
5894  Assert(rel->rd_indexcxt == NULL);
5895  Assert(rel->rd_indam == NULL);
5896  Assert(rel->rd_opfamily == NULL);
5897  Assert(rel->rd_opcintype == NULL);
5898  Assert(rel->rd_support == NULL);
5899  Assert(rel->rd_supportinfo == NULL);
5900  Assert(rel->rd_indoption == NULL);
5901  Assert(rel->rd_indcollation == NULL);
5902  Assert(rel->rd_opcoptions == NULL);
5903  }
5904 
5905  /*
5906  * Rules and triggers are not saved (mainly because the internal
5907  * format is complex and subject to change). They must be rebuilt if
5908  * needed by RelationCacheInitializePhase3. This is not expected to
5909  * be a big performance hit since few system catalogs have such. Ditto
5910  * for RLS policy data, partition info, index expressions, predicates,
5911  * exclusion info, and FDW info.
5912  */
5913  rel->rd_rules = NULL;
5914  rel->rd_rulescxt = NULL;
5915  rel->trigdesc = NULL;
5916  rel->rd_rsdesc = NULL;
5917  rel->rd_partkey = NULL;
5918  rel->rd_partkeycxt = NULL;
5919  rel->rd_partdesc = NULL;
5920  rel->rd_pdcxt = NULL;
5921  rel->rd_partcheck = NIL;
5922  rel->rd_partcheckvalid = false;
5923  rel->rd_partcheckcxt = NULL;
5924  rel->rd_indexprs = NIL;
5925  rel->rd_indpred = NIL;
5926  rel->rd_exclops = NULL;
5927  rel->rd_exclprocs = NULL;
5928  rel->rd_exclstrats = NULL;
5929  rel->rd_fdwroutine = NULL;
5930 
5931  /*
5932  * Reset transient-state fields in the relcache entry
5933  */
5934  rel->rd_smgr = NULL;
5935  if (rel->rd_isnailed)
5936  rel->rd_refcnt = 1;
5937  else
5938  rel->rd_refcnt = 0;
5939  rel->rd_indexvalid = false;
5940  rel->rd_indexlist = NIL;
5941  rel->rd_pkindex<