1 /*-------------------------------------------------------------------------
4 * POSTGRES relation descriptor (a/k/a relcache entry) definitions.
7 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/include/utils/rel.h
12 *-------------------------------------------------------------------------
17 #include "access/tupdesc.h"
18 #include "catalog/pg_am.h"
19 #include "catalog/pg_class.h"
20 #include "catalog/pg_index.h"
22 #include "nodes/bitmapset.h"
23 #include "rewrite/prs2lock.h"
24 #include "storage/block.h"
25 #include "storage/relfilenode.h"
26 #include "utils/relcache.h"
27 #include "utils/reltrigger.h"
31 * LockRelId and LockInfo really belong to lmgr.h, but it's more convenient
32 * to declare them here so we can have a LockInfoData field in a Relation.
35 typedef struct LockRelId
37 Oid relId; /* a relation identifier */
38 Oid dbId; /* a database identifier */
41 typedef struct LockInfoData
46 typedef LockInfoData *LockInfo;
50 * Cached lookup information for the frequently used index access method
51 * functions, defined by the pg_am row associated with an index relation.
53 typedef struct RelationAmInfo
68 * Here are the contents of a relation cache entry.
71 typedef struct RelationData
73 RelFileNode rd_node; /* relation physical identifier */
74 /* use "struct" here to avoid needing to include smgr.h: */
75 struct SMgrRelationData *rd_smgr; /* cached file handle, or NULL */
76 int rd_refcnt; /* reference count */
77 BackendId rd_backend; /* owning backend id, if temporary relation */
78 bool rd_islocaltemp; /* rel is a temp rel of this session */
79 bool rd_isnailed; /* rel is nailed in cache */
80 bool rd_isvalid; /* relcache entry is valid */
81 char rd_indexvalid; /* state of rd_indexlist: 0 = not valid, 1 =
82 * valid, 2 = temporarily forced */
85 * rd_createSubid is the ID of the highest subtransaction the rel has
86 * survived into; or zero if the rel was not created in the current top
87 * transaction. This can be now be relied on, whereas previously it could
88 * be "forgotten" in earlier releases. Likewise, rd_newRelfilenodeSubid is
89 * the ID of the highest subtransaction the relfilenode change has
90 * survived into, or zero if not changed in the current transaction (or we
91 * have forgotten changing it). rd_newRelfilenodeSubid can be forgotten
92 * when a relation has multiple new relfilenodes within a single
93 * transaction, with one of them occuring in a subsequently aborted
94 * subtransaction, e.g. BEGIN; TRUNCATE t; SAVEPOINT save; TRUNCATE t;
95 * ROLLBACK TO save; -- rd_newRelfilenode is now forgotten
97 SubTransactionId rd_createSubid; /* rel was created in current xact */
98 SubTransactionId rd_newRelfilenodeSubid; /* new relfilenode assigned in
101 Form_pg_class rd_rel; /* RELATION tuple */
102 TupleDesc rd_att; /* tuple descriptor */
103 Oid rd_id; /* relation's object id */
104 LockInfoData rd_lockInfo; /* lock mgr's info for locking relation */
105 RuleLock *rd_rules; /* rewrite rules */
106 MemoryContext rd_rulescxt; /* private memory cxt for rd_rules, if any */
107 TriggerDesc *trigdesc; /* Trigger info, or NULL if rel has none */
108 /* use "struct" here to avoid needing to include rowsecurity.h: */
109 struct RowSecurityDesc *rd_rsdesc; /* row security policies, or NULL */
111 /* data managed by RelationGetIndexList: */
112 List *rd_indexlist; /* list of OIDs of indexes on relation */
113 Oid rd_oidindex; /* OID of unique index on OID, if any */
114 Oid rd_replidindex; /* OID of replica identity index, if any */
116 /* data managed by RelationGetIndexAttrBitmap: */
117 Bitmapset *rd_indexattr; /* identifies columns used in indexes */
118 Bitmapset *rd_keyattr; /* cols that can be ref'd by foreign keys */
119 Bitmapset *rd_idattr; /* included in replica identity index */
122 * rd_options is set whenever rd_rel is loaded into the relcache entry.
123 * Note that you can NOT look into rd_rel for this data. NULL means "use
126 bytea *rd_options; /* parsed pg_class.reloptions */
128 /* These are non-NULL only for an index relation: */
129 Form_pg_index rd_index; /* pg_index tuple describing this index */
130 /* use "struct" here to avoid needing to include htup.h: */
131 struct HeapTupleData *rd_indextuple; /* all of pg_index tuple */
132 Form_pg_am rd_am; /* pg_am tuple for index's AM */
135 * index access support info (used only for an index relation)
137 * Note: only default support procs for each opclass are cached, namely
138 * those with lefttype and righttype equal to the opclass's opcintype. The
139 * arrays are indexed by support function number, which is a sufficient
140 * identifier given that restriction.
142 * Note: rd_amcache is available for index AMs to cache private data about
143 * an index. This must be just a cache since it may get reset at any time
144 * (in particular, it will get reset by a relcache inval message for the
145 * index). If used, it must point to a single memory chunk palloc'd in
146 * rd_indexcxt. A relcache reset will include freeing that chunk and
147 * setting rd_amcache = NULL.
149 MemoryContext rd_indexcxt; /* private memory cxt for this stuff */
150 RelationAmInfo *rd_aminfo; /* lookup info for funcs found in pg_am */
151 Oid *rd_opfamily; /* OIDs of op families for each index col */
152 Oid *rd_opcintype; /* OIDs of opclass declared input data types */
153 RegProcedure *rd_support; /* OIDs of support procedures */
154 FmgrInfo *rd_supportinfo; /* lookup info for support procedures */
155 int16 *rd_indoption; /* per-column AM-specific flags */
156 List *rd_indexprs; /* index expression trees, if any */
157 List *rd_indpred; /* index predicate tree, if any */
158 Oid *rd_exclops; /* OIDs of exclusion operators, if any */
159 Oid *rd_exclprocs; /* OIDs of exclusion ops' procs, if any */
160 uint16 *rd_exclstrats; /* exclusion ops' strategy numbers, if any */
161 void *rd_amcache; /* available for use by index AM */
162 Oid *rd_indcollation; /* OIDs of index collations */
165 * foreign-table support
167 * rd_fdwroutine must point to a single memory chunk palloc'd in
168 * CacheMemoryContext. It will be freed and reset to NULL on a relcache
172 /* use "struct" here to avoid needing to include fdwapi.h: */
173 struct FdwRoutine *rd_fdwroutine; /* cached function pointers, or NULL */
176 * Hack for CLUSTER, rewriting ALTER TABLE, etc: when writing a new
177 * version of a table, we need to make any toast pointers inserted into it
178 * have the existing toast table's OID, not the OID of the transient toast
179 * table. If rd_toastoid isn't InvalidOid, it is the OID to place in
180 * toast pointers inserted into this rel. (Note it's set on the new
181 * version of the main heap, not the toast table itself.) This also
182 * causes toast_save_datum() to try to preserve toast value OIDs.
184 Oid rd_toastoid; /* Real TOAST table's OID, or InvalidOid */
186 /* use "struct" here to avoid needing to include pgstat.h: */
187 struct PgStat_TableStatus *pgstat_info; /* statistics collection area */
192 * Standard contents of rd_options for heaps and generic indexes.
194 * RelationGetFillFactor() and RelationGetTargetPageFreeSpace() can only
195 * be applied to relations that use this format or a superset for
196 * private options data.
198 /* autovacuum-related reloptions. */
199 typedef struct AutoVacOpts
202 int vacuum_threshold;
203 int analyze_threshold;
204 int vacuum_cost_delay;
205 int vacuum_cost_limit;
208 int freeze_table_age;
209 int multixact_freeze_min_age;
210 int multixact_freeze_max_age;
211 int multixact_freeze_table_age;
212 float8 vacuum_scale_factor;
213 float8 analyze_scale_factor;
216 typedef struct StdRdOptions
218 int32 vl_len_; /* varlena header (do not touch directly!) */
219 int fillfactor; /* page fill factor in percent (0..100) */
220 AutoVacOpts autovacuum; /* autovacuum-related options */
221 bool user_catalog_table; /* use as an additional catalog
225 #define HEAP_MIN_FILLFACTOR 10
226 #define HEAP_DEFAULT_FILLFACTOR 100
229 * RelationGetFillFactor
230 * Returns the relation's fillfactor. Note multiple eval of argument!
232 #define RelationGetFillFactor(relation, defaultff) \
233 ((relation)->rd_options ? \
234 ((StdRdOptions *) (relation)->rd_options)->fillfactor : (defaultff))
237 * RelationGetTargetPageUsage
238 * Returns the relation's desired space usage per page in bytes.
240 #define RelationGetTargetPageUsage(relation, defaultff) \
241 (BLCKSZ * RelationGetFillFactor(relation, defaultff) / 100)
244 * RelationGetTargetPageFreeSpace
245 * Returns the relation's desired freespace per page in bytes.
247 #define RelationGetTargetPageFreeSpace(relation, defaultff) \
248 (BLCKSZ * (100 - RelationGetFillFactor(relation, defaultff)) / 100)
251 * RelationIsUsedAsCatalogTable
252 * Returns whether the relation should be treated as a catalog table
253 * from the pov of logical decoding. Note multiple eval or argument!
255 #define RelationIsUsedAsCatalogTable(relation) \
256 ((relation)->rd_options ? \
257 ((StdRdOptions *) (relation)->rd_options)->user_catalog_table : false)
262 * Contents of rd_options for views
264 typedef struct ViewOptions
266 int32 vl_len_; /* varlena header (do not touch directly!) */
267 bool security_barrier;
268 int check_option_offset;
272 * RelationIsSecurityView
273 * Returns whether the relation is security view, or not. Note multiple
276 #define RelationIsSecurityView(relation) \
277 ((relation)->rd_options ? \
278 ((ViewOptions *) (relation)->rd_options)->security_barrier : false)
281 * RelationHasCheckOption
282 * Returns true if the relation is a view defined with either the local
283 * or the cascaded check option. Note multiple eval of argument!
285 #define RelationHasCheckOption(relation) \
286 ((relation)->rd_options && \
287 ((ViewOptions *) (relation)->rd_options)->check_option_offset != 0)
290 * RelationHasLocalCheckOption
291 * Returns true if the relation is a view defined with the local check
292 * option. Note multiple eval of argument!
294 #define RelationHasLocalCheckOption(relation) \
295 ((relation)->rd_options && \
296 ((ViewOptions *) (relation)->rd_options)->check_option_offset != 0 ? \
297 strcmp((char *) (relation)->rd_options + \
298 ((ViewOptions *) (relation)->rd_options)->check_option_offset, \
299 "local") == 0 : false)
302 * RelationHasCascadedCheckOption
303 * Returns true if the relation is a view defined with the cascaded check
304 * option. Note multiple eval of argument!
306 #define RelationHasCascadedCheckOption(relation) \
307 ((relation)->rd_options && \
308 ((ViewOptions *) (relation)->rd_options)->check_option_offset != 0 ? \
309 strcmp((char *) (relation)->rd_options + \
310 ((ViewOptions *) (relation)->rd_options)->check_option_offset, \
311 "cascaded") == 0 : false)
316 * True iff relation descriptor is valid.
318 #define RelationIsValid(relation) PointerIsValid(relation)
320 #define InvalidRelation ((Relation) NULL)
323 * RelationHasReferenceCountZero
324 * True iff relation reference count is zero.
327 * Assumes relation descriptor is valid.
329 #define RelationHasReferenceCountZero(relation) \
330 ((bool)((relation)->rd_refcnt == 0))
334 * Returns pg_class tuple for a relation.
337 * Assumes relation descriptor is valid.
339 #define RelationGetForm(relation) ((relation)->rd_rel)
343 * Returns the OID of the relation
345 #define RelationGetRelid(relation) ((relation)->rd_id)
348 * RelationGetNumberOfAttributes
349 * Returns the number of attributes in a relation.
351 #define RelationGetNumberOfAttributes(relation) ((relation)->rd_rel->relnatts)
355 * Returns tuple descriptor for a relation.
357 #define RelationGetDescr(relation) ((relation)->rd_att)
360 * RelationGetRelationName
361 * Returns the rel's name.
363 * Note that the name is only unique within the containing namespace.
365 #define RelationGetRelationName(relation) \
366 (NameStr((relation)->rd_rel->relname))
369 * RelationGetNamespace
370 * Returns the rel's namespace OID.
372 #define RelationGetNamespace(relation) \
373 ((relation)->rd_rel->relnamespace)
377 * True if the relation uses the relfilenode map.
379 * NB: this is only meaningful for relkinds that have storage, else it
380 * will misleadingly say "true".
382 #define RelationIsMapped(relation) \
383 ((relation)->rd_rel->relfilenode == InvalidOid)
387 * Open the relation at the smgr level, if not already done.
389 #define RelationOpenSmgr(relation) \
391 if ((relation)->rd_smgr == NULL) \
392 smgrsetowner(&((relation)->rd_smgr), smgropen((relation)->rd_node, (relation)->rd_backend)); \
397 * Close the relation at the smgr level, if not already done.
399 * Note: smgrclose should unhook from owner pointer, hence the Assert.
401 #define RelationCloseSmgr(relation) \
403 if ((relation)->rd_smgr != NULL) \
405 smgrclose((relation)->rd_smgr); \
406 Assert((relation)->rd_smgr == NULL); \
411 * RelationGetTargetBlock
412 * Fetch relation's current insertion target block.
414 * Returns InvalidBlockNumber if there is no current target block. Note
415 * that the target block status is discarded on any smgr-level invalidation.
417 #define RelationGetTargetBlock(relation) \
418 ( (relation)->rd_smgr != NULL ? (relation)->rd_smgr->smgr_targblock : InvalidBlockNumber )
421 * RelationSetTargetBlock
422 * Set relation's current insertion target block.
424 #define RelationSetTargetBlock(relation, targblock) \
426 RelationOpenSmgr(relation); \
427 (relation)->rd_smgr->smgr_targblock = (targblock); \
432 * True if relation needs WAL.
434 #define RelationNeedsWAL(relation) \
435 ((relation)->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT)
438 * RelationUsesLocalBuffers
439 * True if relation's pages are stored in local buffers.
441 #define RelationUsesLocalBuffers(relation) \
442 ((relation)->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
446 * If a rel is either temp or newly created in the current transaction,
447 * it can be assumed to be accessible only to the current backend.
448 * This is typically used to decide that we can skip acquiring locks.
450 * Beware of multiple eval of argument
452 #define RELATION_IS_LOCAL(relation) \
453 ((relation)->rd_islocaltemp || \
454 (relation)->rd_createSubid != InvalidSubTransactionId)
457 * RELATION_IS_OTHER_TEMP
458 * Test for a temporary relation that belongs to some other session.
460 * Beware of multiple eval of argument
462 #define RELATION_IS_OTHER_TEMP(relation) \
463 ((relation)->rd_rel->relpersistence == RELPERSISTENCE_TEMP && \
464 !(relation)->rd_islocaltemp)
468 * RelationIsScannable
469 * Currently can only be false for a materialized view which has not been
470 * populated by its query. This is likely to get more complicated later,
471 * so use a macro which looks like a function.
473 #define RelationIsScannable(relation) ((relation)->rd_rel->relispopulated)
476 * RelationIsPopulated
477 * Currently, we don't physically distinguish the "populated" and
478 * "scannable" properties of matviews, but that may change later.
479 * Hence, use the appropriate one of these macros in code tests.
481 #define RelationIsPopulated(relation) ((relation)->rd_rel->relispopulated)
484 * RelationIsAccessibleInLogicalDecoding
485 * True if we need to log enough information to have access via
488 #define RelationIsAccessibleInLogicalDecoding(relation) \
489 (XLogLogicalInfoActive() && \
490 RelationNeedsWAL(relation) && \
491 (IsCatalogRelation(relation) || RelationIsUsedAsCatalogTable(relation)))
494 * RelationIsLogicallyLogged
495 * True if we need to log enough information to extract the data from the
498 * We don't log information for unlogged tables (since they don't WAL log
499 * anyway) and for system tables (their content is hard to make sense of, and
500 * it would complicate decoding slightly for little gain). Note that we *do*
501 * log information for user defined catalog tables since they presumably are
502 * interesting to the user...
504 #define RelationIsLogicallyLogged(relation) \
505 (XLogLogicalInfoActive() && \
506 RelationNeedsWAL(relation) && \
507 !IsCatalogRelation(relation))
509 /* routines in utils/cache/relcache.c */
510 extern void RelationIncrementReferenceCount(Relation rel);
511 extern void RelationDecrementReferenceCount(Relation rel);