2
0

rel.h 24 KB

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