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