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