rel.h 18 KB

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