1 /*-------------------------------------------------------------------------
4 * POSTGRES relation descriptor (a/k/a relcache entry) definitions.
7 * Portions Copyright (c) 1996-2013, 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 List *rd_indexlist; /* list of OIDs of indexes on relation */
105 Bitmapset *rd_indexattr; /* identifies columns used in indexes */
106 Bitmapset *rd_keyattr; /* cols that can be ref'd by foreign keys */
107 Bitmapset *rd_idattr; /* included in replica identity index */
108 Oid rd_oidindex; /* OID of unique index on OID, if any */
109 LockInfoData rd_lockInfo; /* lock mgr's info for locking relation */
110 RuleLock *rd_rules; /* rewrite rules */
111 MemoryContext rd_rulescxt; /* private memory cxt for rd_rules, if any */
112 TriggerDesc *trigdesc; /* Trigger info, or NULL if rel has none */
115 * The index chosen as the relation's replication identity or
116 * InvalidOid. Only set correctly if RelationGetIndexList has been
117 * called/rd_indexvalid > 0.
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 float8 vacuum_scale_factor;
210 float8 analyze_scale_factor;
213 typedef struct StdRdOptions
215 int32 vl_len_; /* varlena header (do not touch directly!) */
216 int fillfactor; /* page fill factor in percent (0..100) */
217 AutoVacOpts autovacuum; /* autovacuum-related options */
218 bool security_barrier; /* for views */
219 int check_option_offset; /* for views */
220 bool user_catalog_table; /* use as an additional catalog relation */
223 #define HEAP_MIN_FILLFACTOR 10
224 #define HEAP_DEFAULT_FILLFACTOR 100
227 * RelationGetFillFactor
228 * Returns the relation's fillfactor. Note multiple eval of argument!
230 #define RelationGetFillFactor(relation, defaultff) \
231 ((relation)->rd_options ? \
232 ((StdRdOptions *) (relation)->rd_options)->fillfactor : (defaultff))
235 * RelationGetTargetPageUsage
236 * Returns the relation's desired space usage per page in bytes.
238 #define RelationGetTargetPageUsage(relation, defaultff) \
239 (BLCKSZ * RelationGetFillFactor(relation, defaultff) / 100)
242 * RelationGetTargetPageFreeSpace
243 * Returns the relation's desired freespace per page in bytes.
245 #define RelationGetTargetPageFreeSpace(relation, defaultff) \
246 (BLCKSZ * (100 - RelationGetFillFactor(relation, defaultff)) / 100)
249 * RelationIsSecurityView
250 * Returns whether the relation is security view, or not
252 #define RelationIsSecurityView(relation) \
253 ((relation)->rd_options ? \
254 ((StdRdOptions *) (relation)->rd_options)->security_barrier : false)
257 * RelationHasCheckOption
258 * Returns true if the relation is a view defined with either the local
259 * or the cascaded check option.
261 #define RelationHasCheckOption(relation) \
262 ((relation)->rd_options && \
263 ((StdRdOptions *) (relation)->rd_options)->check_option_offset != 0)
266 * RelationHasLocalCheckOption
267 * Returns true if the relation is a view defined with the local check
270 #define RelationHasLocalCheckOption(relation) \
271 ((relation)->rd_options && \
272 ((StdRdOptions *) (relation)->rd_options)->check_option_offset != 0 ? \
273 strcmp((char *) (relation)->rd_options + \
274 ((StdRdOptions *) (relation)->rd_options)->check_option_offset, \
275 "local") == 0 : false)
278 * RelationHasCascadedCheckOption
279 * Returns true if the relation is a view defined with the cascaded check
282 #define RelationHasCascadedCheckOption(relation) \
283 ((relation)->rd_options && \
284 ((StdRdOptions *) (relation)->rd_options)->check_option_offset != 0 ? \
285 strcmp((char *) (relation)->rd_options + \
286 ((StdRdOptions *) (relation)->rd_options)->check_option_offset, \
287 "cascaded") == 0 : false)
290 * RelationIsUsedAsCatalogTable
291 * Returns whether the relation should be treated as a catalog table
292 * from the pov of logical decoding.
294 #define RelationIsUsedAsCatalogTable(relation) \
295 ((relation)->rd_options ? \
296 ((StdRdOptions *) (relation)->rd_options)->user_catalog_table : false)
300 * True iff relation descriptor is valid.
302 #define RelationIsValid(relation) PointerIsValid(relation)
304 #define InvalidRelation ((Relation) NULL)
307 * RelationHasReferenceCountZero
308 * True iff relation reference count is zero.
311 * Assumes relation descriptor is valid.
313 #define RelationHasReferenceCountZero(relation) \
314 ((bool)((relation)->rd_refcnt == 0))
318 * Returns pg_class tuple for a relation.
321 * Assumes relation descriptor is valid.
323 #define RelationGetForm(relation) ((relation)->rd_rel)
327 * Returns the OID of the relation
329 #define RelationGetRelid(relation) ((relation)->rd_id)
332 * RelationGetNumberOfAttributes
333 * Returns the number of attributes in a relation.
335 #define RelationGetNumberOfAttributes(relation) ((relation)->rd_rel->relnatts)
339 * Returns tuple descriptor for a relation.
341 #define RelationGetDescr(relation) ((relation)->rd_att)
344 * RelationGetRelationName
345 * Returns the rel's name.
347 * Note that the name is only unique within the containing namespace.
349 #define RelationGetRelationName(relation) \
350 (NameStr((relation)->rd_rel->relname))
353 * RelationGetNamespace
354 * Returns the rel's namespace OID.
356 #define RelationGetNamespace(relation) \
357 ((relation)->rd_rel->relnamespace)
361 * True if the relation uses the relfilenode map.
363 * NB: this is only meaningful for relkinds that have storage, else it
364 * will misleadingly say "true".
366 #define RelationIsMapped(relation) \
367 ((relation)->rd_rel->relfilenode == InvalidOid)
371 * Open the relation at the smgr level, if not already done.
373 #define RelationOpenSmgr(relation) \
375 if ((relation)->rd_smgr == NULL) \
376 smgrsetowner(&((relation)->rd_smgr), smgropen((relation)->rd_node, (relation)->rd_backend)); \
381 * Close the relation at the smgr level, if not already done.
383 * Note: smgrclose should unhook from owner pointer, hence the Assert.
385 #define RelationCloseSmgr(relation) \
387 if ((relation)->rd_smgr != NULL) \
389 smgrclose((relation)->rd_smgr); \
390 Assert((relation)->rd_smgr == NULL); \
395 * RelationGetTargetBlock
396 * Fetch relation's current insertion target block.
398 * Returns InvalidBlockNumber if there is no current target block. Note
399 * that the target block status is discarded on any smgr-level invalidation.
401 #define RelationGetTargetBlock(relation) \
402 ( (relation)->rd_smgr != NULL ? (relation)->rd_smgr->smgr_targblock : InvalidBlockNumber )
405 * RelationSetTargetBlock
406 * Set relation's current insertion target block.
408 #define RelationSetTargetBlock(relation, targblock) \
410 RelationOpenSmgr(relation); \
411 (relation)->rd_smgr->smgr_targblock = (targblock); \
416 * True if relation needs WAL.
418 #define RelationNeedsWAL(relation) \
419 ((relation)->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT)
422 * RelationUsesLocalBuffers
423 * True if relation's pages are stored in local buffers.
425 #define RelationUsesLocalBuffers(relation) \
426 ((relation)->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
430 * If a rel is either temp or newly created in the current transaction,
431 * it can be assumed to be accessible only to the current backend.
432 * This is typically used to decide that we can skip acquiring locks.
434 * Beware of multiple eval of argument
436 #define RELATION_IS_LOCAL(relation) \
437 ((relation)->rd_islocaltemp || \
438 (relation)->rd_createSubid != InvalidSubTransactionId)
441 * RELATION_IS_OTHER_TEMP
442 * Test for a temporary relation that belongs to some other session.
444 * Beware of multiple eval of argument
446 #define RELATION_IS_OTHER_TEMP(relation) \
447 ((relation)->rd_rel->relpersistence == RELPERSISTENCE_TEMP && \
448 !(relation)->rd_islocaltemp)
452 * RelationIsScannable
453 * Currently can only be false for a materialized view which has not been
454 * populated by its query. This is likely to get more complicated later,
455 * so use a macro which looks like a function.
457 #define RelationIsScannable(relation) ((relation)->rd_rel->relispopulated)
460 * RelationIsPopulated
461 * Currently, we don't physically distinguish the "populated" and
462 * "scannable" properties of matviews, but that may change later.
463 * Hence, use the appropriate one of these macros in code tests.
465 #define RelationIsPopulated(relation) ((relation)->rd_rel->relispopulated)
468 * RelationIsAccessibleInLogicalDecoding
469 * True if we need to log enough information to have access via
472 #define RelationIsAccessibleInLogicalDecoding(relation) \
473 (XLogLogicalInfoActive() && \
474 RelationNeedsWAL(relation) && \
475 (IsCatalogRelation(relation) || RelationIsUsedAsCatalogTable(relation)))
478 * RelationIsLogicallyLogged
479 * True if we need to log enough information to extract the data from the
482 * We don't log information for unlogged tables (since they don't WAL log
483 * anyway) and for system tables (their content is hard to make sense of, and
484 * it would complicate decoding slightly for little gain). Note that we *do*
485 * log information for user defined catalog tables since they presumably are
486 * interesting to the user...
488 #define RelationIsLogicallyLogged(relation) \
489 (XLogLogicalInfoActive() && \
490 RelationNeedsWAL(relation) && \
491 !IsCatalogRelation(relation))
493 /* routines in utils/cache/relcache.c */
494 extern void RelationIncrementReferenceCount(Relation rel);
495 extern void RelationDecrementReferenceCount(Relation rel);