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