]> granicus.if.org Git - postgresql/blob - src/include/utils/rel.h
Fix hstore_to_json_loose's detection of valid JSON number values.
[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-2014, 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         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 */
110
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 */
115
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 */
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         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;
214 } AutoVacOpts;
215
216 typedef struct StdRdOptions
217 {
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
222                                                                                  * relation */
223 } StdRdOptions;
224
225 #define HEAP_MIN_FILLFACTOR                     10
226 #define HEAP_DEFAULT_FILLFACTOR         100
227
228 /*
229  * RelationGetFillFactor
230  *              Returns the relation's fillfactor.  Note multiple eval of argument!
231  */
232 #define RelationGetFillFactor(relation, defaultff) \
233         ((relation)->rd_options ? \
234          ((StdRdOptions *) (relation)->rd_options)->fillfactor : (defaultff))
235
236 /*
237  * RelationGetTargetPageUsage
238  *              Returns the relation's desired space usage per page in bytes.
239  */
240 #define RelationGetTargetPageUsage(relation, defaultff) \
241         (BLCKSZ * RelationGetFillFactor(relation, defaultff) / 100)
242
243 /*
244  * RelationGetTargetPageFreeSpace
245  *              Returns the relation's desired freespace per page in bytes.
246  */
247 #define RelationGetTargetPageFreeSpace(relation, defaultff) \
248         (BLCKSZ * (100 - RelationGetFillFactor(relation, defaultff)) / 100)
249
250 /*
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!
254  */
255 #define RelationIsUsedAsCatalogTable(relation)  \
256         ((relation)->rd_options ?                               \
257          ((StdRdOptions *) (relation)->rd_options)->user_catalog_table : false)
258
259
260 /*
261  * ViewOptions
262  *              Contents of rd_options for views
263  */
264 typedef struct ViewOptions
265 {
266         int32           vl_len_;                /* varlena header (do not touch directly!) */
267         bool            security_barrier;
268         int                     check_option_offset;
269 } ViewOptions;
270
271 /*
272  * RelationIsSecurityView
273  *              Returns whether the relation is security view, or not.  Note multiple
274  *              eval of argument!
275  */
276 #define RelationIsSecurityView(relation)        \
277         ((relation)->rd_options ?                               \
278          ((ViewOptions *) (relation)->rd_options)->security_barrier : false)
279
280 /*
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!
284  */
285 #define RelationHasCheckOption(relation)                                                                        \
286         ((relation)->rd_options &&                                                                                              \
287          ((ViewOptions *) (relation)->rd_options)->check_option_offset != 0)
288
289 /*
290  * RelationHasLocalCheckOption
291  *              Returns true if the relation is a view defined with the local check
292  *              option.  Note multiple eval of argument!
293  */
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)
300
301 /*
302  * RelationHasCascadedCheckOption
303  *              Returns true if the relation is a view defined with the cascaded check
304  *              option.  Note multiple eval of argument!
305  */
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)
312
313
314 /*
315  * RelationIsValid
316  *              True iff relation descriptor is valid.
317  */
318 #define RelationIsValid(relation) PointerIsValid(relation)
319
320 #define InvalidRelation ((Relation) NULL)
321
322 /*
323  * RelationHasReferenceCountZero
324  *              True iff relation reference count is zero.
325  *
326  * Note:
327  *              Assumes relation descriptor is valid.
328  */
329 #define RelationHasReferenceCountZero(relation) \
330                 ((bool)((relation)->rd_refcnt == 0))
331
332 /*
333  * RelationGetForm
334  *              Returns pg_class tuple for a relation.
335  *
336  * Note:
337  *              Assumes relation descriptor is valid.
338  */
339 #define RelationGetForm(relation) ((relation)->rd_rel)
340
341 /*
342  * RelationGetRelid
343  *              Returns the OID of the relation
344  */
345 #define RelationGetRelid(relation) ((relation)->rd_id)
346
347 /*
348  * RelationGetNumberOfAttributes
349  *              Returns the number of attributes in a relation.
350  */
351 #define RelationGetNumberOfAttributes(relation) ((relation)->rd_rel->relnatts)
352
353 /*
354  * RelationGetDescr
355  *              Returns tuple descriptor for a relation.
356  */
357 #define RelationGetDescr(relation) ((relation)->rd_att)
358
359 /*
360  * RelationGetRelationName
361  *              Returns the rel's name.
362  *
363  * Note that the name is only unique within the containing namespace.
364  */
365 #define RelationGetRelationName(relation) \
366         (NameStr((relation)->rd_rel->relname))
367
368 /*
369  * RelationGetNamespace
370  *              Returns the rel's namespace OID.
371  */
372 #define RelationGetNamespace(relation) \
373         ((relation)->rd_rel->relnamespace)
374
375 /*
376  * RelationIsMapped
377  *              True if the relation uses the relfilenode map.
378  *
379  * NB: this is only meaningful for relkinds that have storage, else it
380  * will misleadingly say "true".
381  */
382 #define RelationIsMapped(relation) \
383         ((relation)->rd_rel->relfilenode == InvalidOid)
384
385 /*
386  * RelationOpenSmgr
387  *              Open the relation at the smgr level, if not already done.
388  */
389 #define RelationOpenSmgr(relation) \
390         do { \
391                 if ((relation)->rd_smgr == NULL) \
392                         smgrsetowner(&((relation)->rd_smgr), smgropen((relation)->rd_node, (relation)->rd_backend)); \
393         } while (0)
394
395 /*
396  * RelationCloseSmgr
397  *              Close the relation at the smgr level, if not already done.
398  *
399  * Note: smgrclose should unhook from owner pointer, hence the Assert.
400  */
401 #define RelationCloseSmgr(relation) \
402         do { \
403                 if ((relation)->rd_smgr != NULL) \
404                 { \
405                         smgrclose((relation)->rd_smgr); \
406                         Assert((relation)->rd_smgr == NULL); \
407                 } \
408         } while (0)
409
410 /*
411  * RelationGetTargetBlock
412  *              Fetch relation's current insertion target block.
413  *
414  * Returns InvalidBlockNumber if there is no current target block.  Note
415  * that the target block status is discarded on any smgr-level invalidation.
416  */
417 #define RelationGetTargetBlock(relation) \
418         ( (relation)->rd_smgr != NULL ? (relation)->rd_smgr->smgr_targblock : InvalidBlockNumber )
419
420 /*
421  * RelationSetTargetBlock
422  *              Set relation's current insertion target block.
423  */
424 #define RelationSetTargetBlock(relation, targblock) \
425         do { \
426                 RelationOpenSmgr(relation); \
427                 (relation)->rd_smgr->smgr_targblock = (targblock); \
428         } while (0)
429
430 /*
431  * RelationNeedsWAL
432  *              True if relation needs WAL.
433  */
434 #define RelationNeedsWAL(relation) \
435         ((relation)->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT)
436
437 /*
438  * RelationUsesLocalBuffers
439  *              True if relation's pages are stored in local buffers.
440  */
441 #define RelationUsesLocalBuffers(relation) \
442         ((relation)->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
443
444 /*
445  * RELATION_IS_LOCAL
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.
449  *
450  * Beware of multiple eval of argument
451  */
452 #define RELATION_IS_LOCAL(relation) \
453         ((relation)->rd_islocaltemp || \
454          (relation)->rd_createSubid != InvalidSubTransactionId)
455
456 /*
457  * RELATION_IS_OTHER_TEMP
458  *              Test for a temporary relation that belongs to some other session.
459  *
460  * Beware of multiple eval of argument
461  */
462 #define RELATION_IS_OTHER_TEMP(relation) \
463         ((relation)->rd_rel->relpersistence == RELPERSISTENCE_TEMP && \
464          !(relation)->rd_islocaltemp)
465
466
467 /*
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.
472  */
473 #define RelationIsScannable(relation) ((relation)->rd_rel->relispopulated)
474
475 /*
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.
480  */
481 #define RelationIsPopulated(relation) ((relation)->rd_rel->relispopulated)
482
483 /*
484  * RelationIsAccessibleInLogicalDecoding
485  *              True if we need to log enough information to have access via
486  *              decoding snapshot.
487  */
488 #define RelationIsAccessibleInLogicalDecoding(relation) \
489         (XLogLogicalInfoActive() && \
490          RelationNeedsWAL(relation) && \
491          (IsCatalogRelation(relation) || RelationIsUsedAsCatalogTable(relation)))
492
493 /*
494  * RelationIsLogicallyLogged
495  *              True if we need to log enough information to extract the data from the
496  *              WAL stream.
497  *
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...
503  */
504 #define RelationIsLogicallyLogged(relation) \
505         (XLogLogicalInfoActive() && \
506          RelationNeedsWAL(relation) && \
507          !IsCatalogRelation(relation))
508
509 /* routines in utils/cache/relcache.c */
510 extern void RelationIncrementReferenceCount(Relation rel);
511 extern void RelationDecrementReferenceCount(Relation rel);
512
513 #endif   /* REL_H */