1 /*------------------------------------------------------------------------- 2 * 3 * rel.h 4 * POSTGRES relation descriptor (a/k/a relcache entry) definitions. 5 * 6 * 7 * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group 8 * Portions Copyright (c) 1994, Regents of the University of California 9 * 10 * src/include/utils/rel.h 11 * 12 *------------------------------------------------------------------------- 13 */ 14 #ifndef REL_H 15 #define REL_H 16 17 #include "access/tupdesc.h" 18 #include "access/xlog.h" 19 #include "catalog/pg_class.h" 20 #include "catalog/pg_index.h" 21 #include "catalog/pg_publication.h" 22 #include "fmgr.h" 23 #include "nodes/bitmapset.h" 24 #include "rewrite/prs2lock.h" 25 #include "storage/block.h" 26 #include "storage/relfilenode.h" 27 #include "utils/relcache.h" 28 #include "utils/reltrigger.h" 29 30 31 /* 32 * LockRelId and LockInfo really belong to lmgr.h, but it's more convenient 33 * to declare them here so we can have a LockInfoData field in a Relation. 34 */ 35 36 typedef struct LockRelId 37 { 38 Oid relId; /* a relation identifier */ 39 Oid dbId; /* a database identifier */ 40 } LockRelId; 41 42 typedef struct LockInfoData 43 { 44 LockRelId lockRelId; 45 } LockInfoData; 46 47 typedef LockInfoData *LockInfo; 48 49 /* 50 * Here are the contents of a relation cache entry. 51 */ 52 53 typedef struct RelationData 54 { 55 RelFileNode rd_node; /* relation physical identifier */ 56 /* use "struct" here to avoid needing to include smgr.h: */ 57 struct SMgrRelationData *rd_smgr; /* cached file handle, or NULL */ 58 int rd_refcnt; /* reference count */ 59 BackendId rd_backend; /* owning backend id, if temporary relation */ 60 bool rd_islocaltemp; /* rel is a temp rel of this session */ 61 bool rd_isnailed; /* rel is nailed in cache */ 62 bool rd_isvalid; /* relcache entry is valid */ 63 char rd_indexvalid; /* state of rd_indexlist: 0 = not valid, 1 = 64 * valid, 2 = temporarily forced */ 65 bool rd_statvalid; /* is rd_statlist valid? */ 66 67 /*---------- 68 * rd_createSubid is the ID of the highest subtransaction the rel has 69 * survived into; or zero if the rel was not created in the current top 70 * transaction. This can be now be relied on, whereas previously it could 71 * be "forgotten" in earlier releases. Likewise, rd_newRelfilenodeSubid is 72 * the ID of the highest subtransaction the relfilenode change has 73 * survived into, or zero if not changed in the current transaction (or we 74 * have forgotten changing it). rd_newRelfilenodeSubid can be forgotten 75 * when a relation has multiple new relfilenodes within a single 76 * transaction, with one of them occurring in a subsequently aborted 77 * subtransaction, e.g. 78 * BEGIN; 79 * TRUNCATE t; 80 * SAVEPOINT save; 81 * TRUNCATE t; 82 * ROLLBACK TO save; 83 * -- rd_newRelfilenodeSubid is now forgotten 84 */ 85 SubTransactionId rd_createSubid; /* rel was created in current xact */ 86 SubTransactionId rd_newRelfilenodeSubid; /* new relfilenode assigned in 87 * current xact */ 88 89 Form_pg_class rd_rel; /* RELATION tuple */ 90 TupleDesc rd_att; /* tuple descriptor */ 91 Oid rd_id; /* relation's object id */ 92 LockInfoData rd_lockInfo; /* lock mgr's info for locking relation */ 93 RuleLock *rd_rules; /* rewrite rules */ 94 MemoryContext rd_rulescxt; /* private memory cxt for rd_rules, if any */ 95 TriggerDesc *trigdesc; /* Trigger info, or NULL if rel has none */ 96 /* use "struct" here to avoid needing to include rowsecurity.h: */ 97 struct RowSecurityDesc *rd_rsdesc; /* row security policies, or NULL */ 98 99 /* data managed by RelationGetFKeyList: */ 100 List *rd_fkeylist; /* list of ForeignKeyCacheInfo (see below) */ 101 bool rd_fkeyvalid; /* true if list has been computed */ 102 103 MemoryContext rd_partkeycxt; /* private context for rd_partkey, if any */ 104 struct PartitionKeyData *rd_partkey; /* partition key, or NULL */ 105 MemoryContext rd_pdcxt; /* private context for rd_partdesc, if any */ 106 struct PartitionDescData *rd_partdesc; /* partitions, or NULL */ 107 List *rd_partcheck; /* partition CHECK quals */ 108 109 /* data managed by RelationGetIndexList: */ 110 List *rd_indexlist; /* list of OIDs of indexes on relation */ 111 Oid rd_oidindex; /* OID of unique index on OID, if any */ 112 Oid rd_pkindex; /* OID of primary key, if any */ 113 Oid rd_replidindex; /* OID of replica identity index, if any */ 114 115 /* data managed by RelationGetStatExtList: */ 116 List *rd_statlist; /* list of OIDs of extended stats */ 117 118 /* data managed by RelationGetIndexAttrBitmap: */ 119 Bitmapset *rd_indexattr; /* columns used in non-projection indexes */ 120 Bitmapset *rd_projindexattr; /* columns used in projection indexes */ 121 Bitmapset *rd_keyattr; /* cols that can be ref'd by foreign keys */ 122 Bitmapset *rd_pkattr; /* cols included in primary key */ 123 Bitmapset *rd_idattr; /* included in replica identity index */ 124 Bitmapset *rd_projidx; /* Oids of projection indexes */ 125 126 PublicationActions *rd_pubactions; /* publication actions */ 127 128 /* 129 * rd_options is set whenever rd_rel is loaded into the relcache entry. 130 * Note that you can NOT look into rd_rel for this data. NULL means "use 131 * defaults". 132 */ 133 bytea *rd_options; /* parsed pg_class.reloptions */ 134 135 /* These are non-NULL only for an index relation: */ 136 Form_pg_index rd_index; /* pg_index tuple describing this index */ 137 /* use "struct" here to avoid needing to include htup.h: */ 138 struct HeapTupleData *rd_indextuple; /* all of pg_index tuple */ 139 140 /* 141 * index access support info (used only for an index relation) 142 * 143 * Note: only default support procs for each opclass are cached, namely 144 * those with lefttype and righttype equal to the opclass's opcintype. The 145 * arrays are indexed by support function number, which is a sufficient 146 * identifier given that restriction. 147 * 148 * Note: rd_amcache is available for index AMs to cache private data about 149 * an index. This must be just a cache since it may get reset at any time 150 * (in particular, it will get reset by a relcache inval message for the 151 * index). If used, it must point to a single memory chunk palloc'd in 152 * rd_indexcxt. A relcache reset will include freeing that chunk and 153 * setting rd_amcache = NULL. 154 */ 155 Oid rd_amhandler; /* OID of index AM's handler function */ 156 MemoryContext rd_indexcxt; /* private memory cxt for this stuff */ 157 /* use "struct" here to avoid needing to include amapi.h: */ 158 struct IndexAmRoutine *rd_amroutine; /* index AM's API struct */ 159 Oid *rd_opfamily; /* OIDs of op families for each index col */ 160 Oid *rd_opcintype; /* OIDs of opclass declared input data types */ 161 RegProcedure *rd_support; /* OIDs of support procedures */ 162 FmgrInfo *rd_supportinfo; /* lookup info for support procedures */ 163 int16 *rd_indoption; /* per-column AM-specific flags */ 164 List *rd_indexprs; /* index expression trees, if any */ 165 List *rd_indpred; /* index predicate tree, if any */ 166 Oid *rd_exclops; /* OIDs of exclusion operators, if any */ 167 Oid *rd_exclprocs; /* OIDs of exclusion ops' procs, if any */ 168 uint16 *rd_exclstrats; /* exclusion ops' strategy numbers, if any */ 169 void *rd_amcache; /* available for use by index AM */ 170 Oid *rd_indcollation; /* OIDs of index collations */ 171 172 /* 173 * foreign-table support 174 * 175 * rd_fdwroutine must point to a single memory chunk palloc'd in 176 * CacheMemoryContext. It will be freed and reset to NULL on a relcache 177 * reset. 178 */ 179 180 /* use "struct" here to avoid needing to include fdwapi.h: */ 181 struct FdwRoutine *rd_fdwroutine; /* cached function pointers, or NULL */ 182 183 /* 184 * Hack for CLUSTER, rewriting ALTER TABLE, etc: when writing a new 185 * version of a table, we need to make any toast pointers inserted into it 186 * have the existing toast table's OID, not the OID of the transient toast 187 * table. If rd_toastoid isn't InvalidOid, it is the OID to place in 188 * toast pointers inserted into this rel. (Note it's set on the new 189 * version of the main heap, not the toast table itself.) This also 190 * causes toast_save_datum() to try to preserve toast value OIDs. 191 */ 192 Oid rd_toastoid; /* Real TOAST table's OID, or InvalidOid */ 193 194 /* use "struct" here to avoid needing to include pgstat.h: */ 195 struct PgStat_TableStatus *pgstat_info; /* statistics collection area */ 196 197 /* placed here to avoid ABI break before v12: */ 198 bool rd_partcheckvalid; /* true if list has been computed */ 199 MemoryContext rd_partcheckcxt; /* private cxt for rd_partcheck, if any */ 200 } RelationData; 201 202 203 /* 204 * ForeignKeyCacheInfo 205 * Information the relcache can cache about foreign key constraints 206 * 207 * This is basically just an image of relevant columns from pg_constraint. 208 * We make it a subclass of Node so that copyObject() can be used on a list 209 * of these, but we also ensure it is a "flat" object without substructure, 210 * so that list_free_deep() is sufficient to free such a list. 211 * The per-FK-column arrays can be fixed-size because we allow at most 212 * INDEX_MAX_KEYS columns in a foreign key constraint. 213 * 214 * Currently, we mostly cache fields of interest to the planner, but the set 215 * of fields has already grown the constraint OID for other uses. 216 */ 217 typedef struct ForeignKeyCacheInfo 218 { 219 NodeTag type; 220 Oid conoid; /* oid of the constraint itself */ 221 Oid conrelid; /* relation constrained by the foreign key */ 222 Oid confrelid; /* relation referenced by the foreign key */ 223 int nkeys; /* number of columns in the foreign key */ 224 /* these arrays each have nkeys valid entries: */ 225 AttrNumber conkey[INDEX_MAX_KEYS]; /* cols in referencing table */ 226 AttrNumber confkey[INDEX_MAX_KEYS]; /* cols in referenced table */ 227 Oid conpfeqop[INDEX_MAX_KEYS]; /* PK = FK operator OIDs */ 228 } ForeignKeyCacheInfo; 229 230 /* 231 * Options common for all indexes 232 */ 233 typedef struct GenericIndexOpts 234 { 235 int32 vl_len_; 236 bool recheck_on_update; 237 } GenericIndexOpts; 238 239 /* 240 * StdRdOptions 241 * Standard contents of rd_options for heaps and generic indexes. 242 * 243 * RelationGetFillFactor() and RelationGetTargetPageFreeSpace() can only 244 * be applied to relations that use this format or a superset for 245 * private options data. 246 */ 247 /* autovacuum-related reloptions. */ 248 typedef struct AutoVacOpts 249 { 250 bool enabled; 251 int vacuum_threshold; 252 int analyze_threshold; 253 int vacuum_cost_delay; 254 int vacuum_cost_limit; 255 int freeze_min_age; 256 int freeze_max_age; 257 int freeze_table_age; 258 int multixact_freeze_min_age; 259 int multixact_freeze_max_age; 260 int multixact_freeze_table_age; 261 int log_min_duration; 262 float8 vacuum_scale_factor; 263 float8 analyze_scale_factor; 264 } AutoVacOpts; 265 266 typedef struct StdRdOptions 267 { 268 int32 vl_len_; /* varlena header (do not touch directly!) */ 269 int fillfactor; /* page fill factor in percent (0..100) */ 270 /* fraction of newly inserted tuples prior to trigger index cleanup */ 271 float8 vacuum_cleanup_index_scale_factor; 272 int toast_tuple_target; /* target for tuple toasting */ 273 AutoVacOpts autovacuum; /* autovacuum-related options */ 274 bool user_catalog_table; /* use as an additional catalog relation */ 275 int parallel_workers; /* max number of parallel workers */ 276 } StdRdOptions; 277 278 #define HEAP_MIN_FILLFACTOR 10 279 #define HEAP_DEFAULT_FILLFACTOR 100 280 281 /* 282 * RelationGetToastTupleTarget 283 * Returns the relation's toast_tuple_target. Note multiple eval of argument! 284 */ 285 #define RelationGetToastTupleTarget(relation, defaulttarg) \ 286 ((relation)->rd_options ? \ 287 ((StdRdOptions *) (relation)->rd_options)->toast_tuple_target : (defaulttarg)) 288 289 /* 290 * RelationGetFillFactor 291 * Returns the relation's fillfactor. Note multiple eval of argument! 292 */ 293 #define RelationGetFillFactor(relation, defaultff) \ 294 ((relation)->rd_options ? \ 295 ((StdRdOptions *) (relation)->rd_options)->fillfactor : (defaultff)) 296 297 /* 298 * RelationGetTargetPageUsage 299 * Returns the relation's desired space usage per page in bytes. 300 */ 301 #define RelationGetTargetPageUsage(relation, defaultff) \ 302 (BLCKSZ * RelationGetFillFactor(relation, defaultff) / 100) 303 304 /* 305 * RelationGetTargetPageFreeSpace 306 * Returns the relation's desired freespace per page in bytes. 307 */ 308 #define RelationGetTargetPageFreeSpace(relation, defaultff) \ 309 (BLCKSZ * (100 - RelationGetFillFactor(relation, defaultff)) / 100) 310 311 /* 312 * RelationIsUsedAsCatalogTable 313 * Returns whether the relation should be treated as a catalog table 314 * from the pov of logical decoding. Note multiple eval of argument! 315 */ 316 #define RelationIsUsedAsCatalogTable(relation) \ 317 ((relation)->rd_options && \ 318 ((relation)->rd_rel->relkind == RELKIND_RELATION || \ 319 (relation)->rd_rel->relkind == RELKIND_MATVIEW) ? \ 320 ((StdRdOptions *) (relation)->rd_options)->user_catalog_table : false) 321 322 /* 323 * RelationGetParallelWorkers 324 * Returns the relation's parallel_workers reloption setting. 325 * Note multiple eval of argument! 326 */ 327 #define RelationGetParallelWorkers(relation, defaultpw) \ 328 ((relation)->rd_options ? \ 329 ((StdRdOptions *) (relation)->rd_options)->parallel_workers : (defaultpw)) 330 331 332 /* 333 * ViewOptions 334 * Contents of rd_options for views 335 */ 336 typedef struct ViewOptions 337 { 338 int32 vl_len_; /* varlena header (do not touch directly!) */ 339 bool security_barrier; 340 int check_option_offset; 341 } ViewOptions; 342 343 /* 344 * RelationIsSecurityView 345 * Returns whether the relation is security view, or not. Note multiple 346 * eval of argument! 347 */ 348 #define RelationIsSecurityView(relation) \ 349 ((relation)->rd_options ? \ 350 ((ViewOptions *) (relation)->rd_options)->security_barrier : false) 351 352 /* 353 * RelationHasCheckOption 354 * Returns true if the relation is a view defined with either the local 355 * or the cascaded check option. Note multiple eval of argument! 356 */ 357 #define RelationHasCheckOption(relation) \ 358 ((relation)->rd_options && \ 359 ((ViewOptions *) (relation)->rd_options)->check_option_offset != 0) 360 361 /* 362 * RelationHasLocalCheckOption 363 * Returns true if the relation is a view defined with the local check 364 * option. Note multiple eval of argument! 365 */ 366 #define RelationHasLocalCheckOption(relation) \ 367 ((relation)->rd_options && \ 368 ((ViewOptions *) (relation)->rd_options)->check_option_offset != 0 ? \ 369 strcmp((char *) (relation)->rd_options + \ 370 ((ViewOptions *) (relation)->rd_options)->check_option_offset, \ 371 "local") == 0 : false) 372 373 /* 374 * RelationHasCascadedCheckOption 375 * Returns true if the relation is a view defined with the cascaded check 376 * option. Note multiple eval of argument! 377 */ 378 #define RelationHasCascadedCheckOption(relation) \ 379 ((relation)->rd_options && \ 380 ((ViewOptions *) (relation)->rd_options)->check_option_offset != 0 ? \ 381 strcmp((char *) (relation)->rd_options + \ 382 ((ViewOptions *) (relation)->rd_options)->check_option_offset, \ 383 "cascaded") == 0 : false) 384 385 386 /* 387 * RelationIsValid 388 * True iff relation descriptor is valid. 389 */ 390 #define RelationIsValid(relation) PointerIsValid(relation) 391 392 #define InvalidRelation ((Relation) NULL) 393 394 /* 395 * RelationHasReferenceCountZero 396 * True iff relation reference count is zero. 397 * 398 * Note: 399 * Assumes relation descriptor is valid. 400 */ 401 #define RelationHasReferenceCountZero(relation) \ 402 ((bool)((relation)->rd_refcnt == 0)) 403 404 /* 405 * RelationGetForm 406 * Returns pg_class tuple for a relation. 407 * 408 * Note: 409 * Assumes relation descriptor is valid. 410 */ 411 #define RelationGetForm(relation) ((relation)->rd_rel) 412 413 /* 414 * RelationGetRelid 415 * Returns the OID of the relation 416 */ 417 #define RelationGetRelid(relation) ((relation)->rd_id) 418 419 /* 420 * RelationGetNumberOfAttributes 421 * Returns the total number of attributes in a relation. 422 */ 423 #define RelationGetNumberOfAttributes(relation) ((relation)->rd_rel->relnatts) 424 425 /* 426 * IndexRelationGetNumberOfAttributes 427 * Returns the number of attributes in an index. 428 */ 429 #define IndexRelationGetNumberOfAttributes(relation) \ 430 ((relation)->rd_index->indnatts) 431 432 /* 433 * IndexRelationGetNumberOfKeyAttributes 434 * Returns the number of key attributes in an index. 435 */ 436 #define IndexRelationGetNumberOfKeyAttributes(relation) \ 437 ((relation)->rd_index->indnkeyatts) 438 439 /* 440 * RelationGetDescr 441 * Returns tuple descriptor for a relation. 442 */ 443 #define RelationGetDescr(relation) ((relation)->rd_att) 444 445 /* 446 * RelationGetRelationName 447 * Returns the rel's name. 448 * 449 * Note that the name is only unique within the containing namespace. 450 */ 451 #define RelationGetRelationName(relation) \ 452 (NameStr((relation)->rd_rel->relname)) 453 454 /* 455 * RelationGetNamespace 456 * Returns the rel's namespace OID. 457 */ 458 #define RelationGetNamespace(relation) \ 459 ((relation)->rd_rel->relnamespace) 460 461 /* 462 * RelationIsMapped 463 * True if the relation uses the relfilenode map. 464 * 465 * NB: this is only meaningful for relkinds that have storage, else it 466 * will misleadingly say "true". 467 */ 468 #define RelationIsMapped(relation) \ 469 ((relation)->rd_rel->relfilenode == InvalidOid) 470 471 /* 472 * RelationOpenSmgr 473 * Open the relation at the smgr level, if not already done. 474 */ 475 #define RelationOpenSmgr(relation) \ 476 do { \ 477 if ((relation)->rd_smgr == NULL) \ 478 smgrsetowner(&((relation)->rd_smgr), smgropen((relation)->rd_node, (relation)->rd_backend)); \ 479 } while (0) 480 481 /* 482 * RelationCloseSmgr 483 * Close the relation at the smgr level, if not already done. 484 * 485 * Note: smgrclose should unhook from owner pointer, hence the Assert. 486 */ 487 #define RelationCloseSmgr(relation) \ 488 do { \ 489 if ((relation)->rd_smgr != NULL) \ 490 { \ 491 smgrclose((relation)->rd_smgr); \ 492 Assert((relation)->rd_smgr == NULL); \ 493 } \ 494 } while (0) 495 496 /* 497 * RelationGetTargetBlock 498 * Fetch relation's current insertion target block. 499 * 500 * Returns InvalidBlockNumber if there is no current target block. Note 501 * that the target block status is discarded on any smgr-level invalidation. 502 */ 503 #define RelationGetTargetBlock(relation) \ 504 ( (relation)->rd_smgr != NULL ? (relation)->rd_smgr->smgr_targblock : InvalidBlockNumber ) 505 506 /* 507 * RelationSetTargetBlock 508 * Set relation's current insertion target block. 509 */ 510 #define RelationSetTargetBlock(relation, targblock) \ 511 do { \ 512 RelationOpenSmgr(relation); \ 513 (relation)->rd_smgr->smgr_targblock = (targblock); \ 514 } while (0) 515 516 /* 517 * RelationNeedsWAL 518 * True if relation needs WAL. 519 */ 520 #define RelationNeedsWAL(relation) \ 521 ((relation)->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT) 522 523 /* 524 * RelationUsesLocalBuffers 525 * True if relation's pages are stored in local buffers. 526 */ 527 #define RelationUsesLocalBuffers(relation) \ 528 ((relation)->rd_rel->relpersistence == RELPERSISTENCE_TEMP) 529 530 /* 531 * RELATION_IS_LOCAL 532 * If a rel is either temp or newly created in the current transaction, 533 * it can be assumed to be accessible only to the current backend. 534 * This is typically used to decide that we can skip acquiring locks. 535 * 536 * Beware of multiple eval of argument 537 */ 538 #define RELATION_IS_LOCAL(relation) \ 539 ((relation)->rd_islocaltemp || \ 540 (relation)->rd_createSubid != InvalidSubTransactionId) 541 542 /* 543 * RELATION_IS_OTHER_TEMP 544 * Test for a temporary relation that belongs to some other session. 545 * 546 * Beware of multiple eval of argument 547 */ 548 #define RELATION_IS_OTHER_TEMP(relation) \ 549 ((relation)->rd_rel->relpersistence == RELPERSISTENCE_TEMP && \ 550 !(relation)->rd_islocaltemp) 551 552 553 /* 554 * RelationIsScannable 555 * Currently can only be false for a materialized view which has not been 556 * populated by its query. This is likely to get more complicated later, 557 * so use a macro which looks like a function. 558 */ 559 #define RelationIsScannable(relation) ((relation)->rd_rel->relispopulated) 560 561 /* 562 * RelationIsPopulated 563 * Currently, we don't physically distinguish the "populated" and 564 * "scannable" properties of matviews, but that may change later. 565 * Hence, use the appropriate one of these macros in code tests. 566 */ 567 #define RelationIsPopulated(relation) ((relation)->rd_rel->relispopulated) 568 569 /* 570 * RelationIsAccessibleInLogicalDecoding 571 * True if we need to log enough information to have access via 572 * decoding snapshot. 573 */ 574 #define RelationIsAccessibleInLogicalDecoding(relation) \ 575 (XLogLogicalInfoActive() && \ 576 RelationNeedsWAL(relation) && \ 577 (IsCatalogRelation(relation) || RelationIsUsedAsCatalogTable(relation))) 578 579 /* 580 * RelationIsLogicallyLogged 581 * True if we need to log enough information to extract the data from the 582 * WAL stream. 583 * 584 * We don't log information for unlogged tables (since they don't WAL log 585 * anyway) and for system tables (their content is hard to make sense of, and 586 * it would complicate decoding slightly for little gain). Note that we *do* 587 * log information for user defined catalog tables since they presumably are 588 * interesting to the user... 589 */ 590 #define RelationIsLogicallyLogged(relation) \ 591 (XLogLogicalInfoActive() && \ 592 RelationNeedsWAL(relation) && \ 593 !IsCatalogRelation(relation)) 594 595 /* 596 * RelationGetPartitionKey 597 * Returns the PartitionKey of a relation 598 */ 599 #define RelationGetPartitionKey(relation) ((relation)->rd_partkey) 600 601 /* 602 * RelationGetPartitionDesc 603 * Returns partition descriptor for a relation. 604 */ 605 #define RelationGetPartitionDesc(relation) ((relation)->rd_partdesc) 606 607 /* routines in utils/cache/relcache.c */ 608 extern void RelationIncrementReferenceCount(Relation rel); 609 extern void RelationDecrementReferenceCount(Relation rel); 610 extern List *RelationGetRepsetList(Relation rel); 611 612 #endif /* REL_H */ 613