]> granicus.if.org Git - postgresql/blob - src/include/utils/rel.h
Add a new reloption, user_catalog_table.
[postgresql] / src / include / utils / rel.h
1 /*-------------------------------------------------------------------------
2  *
3  * rel.h
4  *        POSTGRES relation descriptor (a/k/a relcache entry) definitions.
5  *
6  *
7  * Portions Copyright (c) 1996-2013, 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 "catalog/pg_am.h"
19 #include "catalog/pg_class.h"
20 #include "catalog/pg_index.h"
21 #include "fmgr.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"
28
29
30 /*
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.
33  */
34
35 typedef struct LockRelId
36 {
37         Oid                     relId;                  /* a relation identifier */
38         Oid                     dbId;                   /* a database identifier */
39 } LockRelId;
40
41 typedef struct LockInfoData
42 {
43         LockRelId       lockRelId;
44 } LockInfoData;
45
46 typedef LockInfoData *LockInfo;
47
48
49 /*
50  * Cached lookup information for the frequently used index access method
51  * functions, defined by the pg_am row associated with an index relation.
52  */
53 typedef struct RelationAmInfo
54 {
55         FmgrInfo        aminsert;
56         FmgrInfo        ambeginscan;
57         FmgrInfo        amgettuple;
58         FmgrInfo        amgetbitmap;
59         FmgrInfo        amrescan;
60         FmgrInfo        amendscan;
61         FmgrInfo        ammarkpos;
62         FmgrInfo        amrestrpos;
63         FmgrInfo        amcanreturn;
64 } RelationAmInfo;
65
66
67 /*
68  * Here are the contents of a relation cache entry.
69  */
70
71 typedef struct RelationData
72 {
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 */
83
84         /*
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
96          */
97         SubTransactionId rd_createSubid;        /* rel was created in current xact */
98         SubTransactionId rd_newRelfilenodeSubid;        /* new relfilenode assigned in
99                                                                                                  * current xact */
100
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 */
113
114         /*
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.
118          */
119         Oid rd_replidindex;
120
121         /*
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
124          * defaults".
125          */
126         bytea      *rd_options;         /* parsed pg_class.reloptions */
127
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 */
133
134         /*
135          * index access support info (used only for an index relation)
136          *
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.
141          *
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.
148          */
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 */
163
164         /*
165          * foreign-table support
166          *
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
169          * reset.
170          */
171
172         /* use "struct" here to avoid needing to include fdwapi.h: */
173         struct FdwRoutine *rd_fdwroutine;       /* cached function pointers, or NULL */
174
175         /*
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.
183          */
184         Oid                     rd_toastoid;    /* Real TOAST table's OID, or InvalidOid */
185
186         /* use "struct" here to avoid needing to include pgstat.h: */
187         struct PgStat_TableStatus *pgstat_info;         /* statistics collection area */
188 } RelationData;
189
190 /*
191  * StdRdOptions
192  *              Standard contents of rd_options for heaps and generic indexes.
193  *
194  * RelationGetFillFactor() and RelationGetTargetPageFreeSpace() can only
195  * be applied to relations that use this format or a superset for
196  * private options data.
197  */
198  /* autovacuum-related reloptions. */
199 typedef struct AutoVacOpts
200 {
201         bool            enabled;
202         int                     vacuum_threshold;
203         int                     analyze_threshold;
204         int                     vacuum_cost_delay;
205         int                     vacuum_cost_limit;
206         int                     freeze_min_age;
207         int                     freeze_max_age;
208         int                     freeze_table_age;
209         float8          vacuum_scale_factor;
210         float8          analyze_scale_factor;
211 } AutoVacOpts;
212
213 typedef struct StdRdOptions
214 {
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 */
221 } StdRdOptions;
222
223 #define HEAP_MIN_FILLFACTOR                     10
224 #define HEAP_DEFAULT_FILLFACTOR         100
225
226 /*
227  * RelationGetFillFactor
228  *              Returns the relation's fillfactor.  Note multiple eval of argument!
229  */
230 #define RelationGetFillFactor(relation, defaultff) \
231         ((relation)->rd_options ? \
232          ((StdRdOptions *) (relation)->rd_options)->fillfactor : (defaultff))
233
234 /*
235  * RelationGetTargetPageUsage
236  *              Returns the relation's desired space usage per page in bytes.
237  */
238 #define RelationGetTargetPageUsage(relation, defaultff) \
239         (BLCKSZ * RelationGetFillFactor(relation, defaultff) / 100)
240
241 /*
242  * RelationGetTargetPageFreeSpace
243  *              Returns the relation's desired freespace per page in bytes.
244  */
245 #define RelationGetTargetPageFreeSpace(relation, defaultff) \
246         (BLCKSZ * (100 - RelationGetFillFactor(relation, defaultff)) / 100)
247
248 /*
249  * RelationIsSecurityView
250  *              Returns whether the relation is security view, or not
251  */
252 #define RelationIsSecurityView(relation)        \
253         ((relation)->rd_options ?                               \
254          ((StdRdOptions *) (relation)->rd_options)->security_barrier : false)
255
256 /*
257  * RelationHasCheckOption
258  *              Returns true if the relation is a view defined with either the local
259  *              or the cascaded check option.
260  */
261 #define RelationHasCheckOption(relation)                                                                        \
262         ((relation)->rd_options &&                                                                                              \
263          ((StdRdOptions *) (relation)->rd_options)->check_option_offset != 0)
264
265 /*
266  * RelationHasLocalCheckOption
267  *              Returns true if the relation is a view defined with the local check
268  *              option.
269  */
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)
276
277 /*
278  * RelationHasCascadedCheckOption
279  *              Returns true if the relation is a view defined with the cascaded check
280  *              option.
281  */
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)
288
289 /*
290  * RelationIsUsedAsCatalogTable
291  *              Returns whether the relation should be treated as a catalog table
292  *      from the pov of logical decoding.
293  */
294 #define RelationIsUsedAsCatalogTable(relation)  \
295         ((relation)->rd_options ?                               \
296          ((StdRdOptions *) (relation)->rd_options)->user_catalog_table : false)
297
298 /*
299  * RelationIsValid
300  *              True iff relation descriptor is valid.
301  */
302 #define RelationIsValid(relation) PointerIsValid(relation)
303
304 #define InvalidRelation ((Relation) NULL)
305
306 /*
307  * RelationHasReferenceCountZero
308  *              True iff relation reference count is zero.
309  *
310  * Note:
311  *              Assumes relation descriptor is valid.
312  */
313 #define RelationHasReferenceCountZero(relation) \
314                 ((bool)((relation)->rd_refcnt == 0))
315
316 /*
317  * RelationGetForm
318  *              Returns pg_class tuple for a relation.
319  *
320  * Note:
321  *              Assumes relation descriptor is valid.
322  */
323 #define RelationGetForm(relation) ((relation)->rd_rel)
324
325 /*
326  * RelationGetRelid
327  *              Returns the OID of the relation
328  */
329 #define RelationGetRelid(relation) ((relation)->rd_id)
330
331 /*
332  * RelationGetNumberOfAttributes
333  *              Returns the number of attributes in a relation.
334  */
335 #define RelationGetNumberOfAttributes(relation) ((relation)->rd_rel->relnatts)
336
337 /*
338  * RelationGetDescr
339  *              Returns tuple descriptor for a relation.
340  */
341 #define RelationGetDescr(relation) ((relation)->rd_att)
342
343 /*
344  * RelationGetRelationName
345  *              Returns the rel's name.
346  *
347  * Note that the name is only unique within the containing namespace.
348  */
349 #define RelationGetRelationName(relation) \
350         (NameStr((relation)->rd_rel->relname))
351
352 /*
353  * RelationGetNamespace
354  *              Returns the rel's namespace OID.
355  */
356 #define RelationGetNamespace(relation) \
357         ((relation)->rd_rel->relnamespace)
358
359 /*
360  * RelationIsMapped
361  *              True if the relation uses the relfilenode map.
362  *
363  * NB: this is only meaningful for relkinds that have storage, else it
364  * will misleadingly say "true".
365  */
366 #define RelationIsMapped(relation) \
367         ((relation)->rd_rel->relfilenode == InvalidOid)
368
369 /*
370  * RelationOpenSmgr
371  *              Open the relation at the smgr level, if not already done.
372  */
373 #define RelationOpenSmgr(relation) \
374         do { \
375                 if ((relation)->rd_smgr == NULL) \
376                         smgrsetowner(&((relation)->rd_smgr), smgropen((relation)->rd_node, (relation)->rd_backend)); \
377         } while (0)
378
379 /*
380  * RelationCloseSmgr
381  *              Close the relation at the smgr level, if not already done.
382  *
383  * Note: smgrclose should unhook from owner pointer, hence the Assert.
384  */
385 #define RelationCloseSmgr(relation) \
386         do { \
387                 if ((relation)->rd_smgr != NULL) \
388                 { \
389                         smgrclose((relation)->rd_smgr); \
390                         Assert((relation)->rd_smgr == NULL); \
391                 } \
392         } while (0)
393
394 /*
395  * RelationGetTargetBlock
396  *              Fetch relation's current insertion target block.
397  *
398  * Returns InvalidBlockNumber if there is no current target block.      Note
399  * that the target block status is discarded on any smgr-level invalidation.
400  */
401 #define RelationGetTargetBlock(relation) \
402         ( (relation)->rd_smgr != NULL ? (relation)->rd_smgr->smgr_targblock : InvalidBlockNumber )
403
404 /*
405  * RelationSetTargetBlock
406  *              Set relation's current insertion target block.
407  */
408 #define RelationSetTargetBlock(relation, targblock) \
409         do { \
410                 RelationOpenSmgr(relation); \
411                 (relation)->rd_smgr->smgr_targblock = (targblock); \
412         } while (0)
413
414 /*
415  * RelationNeedsWAL
416  *              True if relation needs WAL.
417  */
418 #define RelationNeedsWAL(relation) \
419         ((relation)->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT)
420
421 /*
422  * RelationUsesLocalBuffers
423  *              True if relation's pages are stored in local buffers.
424  */
425 #define RelationUsesLocalBuffers(relation) \
426         ((relation)->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
427
428 /*
429  * RELATION_IS_LOCAL
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.
433  *
434  * Beware of multiple eval of argument
435  */
436 #define RELATION_IS_LOCAL(relation) \
437         ((relation)->rd_islocaltemp || \
438          (relation)->rd_createSubid != InvalidSubTransactionId)
439
440 /*
441  * RELATION_IS_OTHER_TEMP
442  *              Test for a temporary relation that belongs to some other session.
443  *
444  * Beware of multiple eval of argument
445  */
446 #define RELATION_IS_OTHER_TEMP(relation) \
447         ((relation)->rd_rel->relpersistence == RELPERSISTENCE_TEMP && \
448          !(relation)->rd_islocaltemp)
449
450
451 /*
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.
456  */
457 #define RelationIsScannable(relation) ((relation)->rd_rel->relispopulated)
458
459 /*
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.
464  */
465 #define RelationIsPopulated(relation) ((relation)->rd_rel->relispopulated)
466
467 /*
468  * RelationIsAccessibleInLogicalDecoding
469  *              True if we need to log enough information to have access via
470  *              decoding snapshot.
471  */
472 #define RelationIsAccessibleInLogicalDecoding(relation) \
473         (XLogLogicalInfoActive() && \
474          RelationNeedsWAL(relation) && \
475          (IsCatalogRelation(relation) || RelationIsUsedAsCatalogTable(relation)))
476
477 /*
478  * RelationIsLogicallyLogged
479  *              True if we need to log enough information to extract the data from the
480  *              WAL stream.
481  *
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...
487  */
488 #define RelationIsLogicallyLogged(relation) \
489         (XLogLogicalInfoActive() && \
490          RelationNeedsWAL(relation) && \
491          !IsCatalogRelation(relation))
492
493 /* routines in utils/cache/relcache.c */
494 extern void RelationIncrementReferenceCount(Relation rel);
495 extern void RelationDecrementReferenceCount(Relation rel);
496
497 #endif   /* REL_H */