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