Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * tableam.h
4 : * POSTGRES table access method definitions.
5 : *
6 : *
7 : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
8 : * Portions Copyright (c) 1994, Regents of the University of California
9 : *
10 : * src/include/access/tableam.h
11 : *
12 : * NOTES
13 : * See tableam.sgml for higher level documentation.
14 : *
15 : *-------------------------------------------------------------------------
16 : */
17 : #ifndef TABLEAM_H
18 : #define TABLEAM_H
19 :
20 : #include "access/relscan.h"
21 : #include "access/sdir.h"
22 : #include "access/xact.h"
23 : #include "executor/tuptable.h"
24 : #include "storage/read_stream.h"
25 : #include "utils/rel.h"
26 : #include "utils/snapshot.h"
27 :
28 :
29 : #define DEFAULT_TABLE_ACCESS_METHOD "heap"
30 :
31 : /* GUCs */
32 : extern PGDLLIMPORT char *default_table_access_method;
33 : extern PGDLLIMPORT bool synchronize_seqscans;
34 :
35 :
36 : /* forward references in this file */
37 : typedef struct BulkInsertStateData BulkInsertStateData;
38 : typedef struct IndexInfo IndexInfo;
39 : typedef struct SampleScanState SampleScanState;
40 : typedef struct ScanKeyData ScanKeyData;
41 : typedef struct ValidateIndexState ValidateIndexState;
42 : typedef struct VacuumParams VacuumParams;
43 :
44 : /*
45 : * Bitmask values for the flags argument to the scan_begin callback.
46 : */
47 : typedef enum ScanOptions
48 : {
49 : SO_NONE = 0,
50 :
51 : /* one of SO_TYPE_* may be specified */
52 : SO_TYPE_SEQSCAN = 1 << 0,
53 : SO_TYPE_BITMAPSCAN = 1 << 1,
54 : SO_TYPE_SAMPLESCAN = 1 << 2,
55 : SO_TYPE_TIDSCAN = 1 << 3,
56 : SO_TYPE_TIDRANGESCAN = 1 << 4,
57 : SO_TYPE_ANALYZE = 1 << 5,
58 :
59 : /* several of SO_ALLOW_* may be specified */
60 : /* allow or disallow use of access strategy */
61 : SO_ALLOW_STRAT = 1 << 6,
62 : /* report location to syncscan logic? */
63 : SO_ALLOW_SYNC = 1 << 7,
64 : /* verify visibility page-at-a-time? */
65 : SO_ALLOW_PAGEMODE = 1 << 8,
66 :
67 : /* unregister snapshot at scan end? */
68 : SO_TEMP_SNAPSHOT = 1 << 9,
69 :
70 : /* set if the query doesn't modify the relation */
71 : SO_HINT_REL_READ_ONLY = 1 << 10,
72 : } ScanOptions;
73 :
74 : /*
75 : * Mask of flags that are set internally by the table scan functions and
76 : * shouldn't be passed by callers. Some of these are effectively set by callers
77 : * through parameters to table scan functions (e.g. SO_ALLOW_STRAT/allow_strat),
78 : * however, for now, retain tight control over them and don't allow users to
79 : * pass these themselves to table scan functions.
80 : */
81 : #define SO_INTERNAL_FLAGS \
82 : (SO_TYPE_SEQSCAN | SO_TYPE_BITMAPSCAN | SO_TYPE_SAMPLESCAN | \
83 : SO_TYPE_TIDSCAN | SO_TYPE_TIDRANGESCAN | SO_TYPE_ANALYZE | \
84 : SO_ALLOW_STRAT | SO_ALLOW_SYNC | SO_ALLOW_PAGEMODE | \
85 : SO_TEMP_SNAPSHOT)
86 :
87 : /*
88 : * Result codes for table_{update,delete,lock_tuple}, and for visibility
89 : * routines inside table AMs.
90 : */
91 : typedef enum TM_Result
92 : {
93 : /*
94 : * Signals that the action succeeded (i.e. update/delete performed, lock
95 : * was acquired)
96 : */
97 : TM_Ok,
98 :
99 : /* The affected tuple wasn't visible to the relevant snapshot */
100 : TM_Invisible,
101 :
102 : /* The affected tuple was already modified by the calling backend */
103 : TM_SelfModified,
104 :
105 : /*
106 : * The affected tuple was updated by another transaction. This includes
107 : * the case where tuple was moved to another partition.
108 : */
109 : TM_Updated,
110 :
111 : /* The affected tuple was deleted by another transaction */
112 : TM_Deleted,
113 :
114 : /*
115 : * The affected tuple is currently being modified by another session. This
116 : * will only be returned if table_(update/delete/lock_tuple) are
117 : * instructed not to wait.
118 : */
119 : TM_BeingModified,
120 :
121 : /* lock couldn't be acquired, action skipped. Only used by lock_tuple */
122 : TM_WouldBlock,
123 : } TM_Result;
124 :
125 : /*
126 : * Result codes for table_update(..., update_indexes*..).
127 : * Used to determine which indexes to update.
128 : */
129 : typedef enum TU_UpdateIndexes
130 : {
131 : /* No indexed columns were updated (incl. TID addressing of tuple) */
132 : TU_None,
133 :
134 : /* A non-summarizing indexed column was updated, or the TID has changed */
135 : TU_All,
136 :
137 : /* Only summarized columns were updated, TID is unchanged */
138 : TU_Summarizing,
139 : } TU_UpdateIndexes;
140 :
141 : /*
142 : * When table_tuple_update, table_tuple_delete, or table_tuple_lock fail
143 : * because the target tuple is already outdated, they fill in this struct to
144 : * provide information to the caller about what happened. When those functions
145 : * succeed, the contents of this struct should not be relied upon, except for
146 : * `traversed`, which may be set in both success and failure cases.
147 : *
148 : * ctid is the target's ctid link: it is the same as the target's TID if the
149 : * target was deleted, or the location of the replacement tuple if the target
150 : * was updated.
151 : *
152 : * xmax is the outdating transaction's XID. If the caller wants to visit the
153 : * replacement tuple, it must check that this matches before believing the
154 : * replacement is really a match. This is InvalidTransactionId if the target
155 : * was !LP_NORMAL (expected only for a TID retrieved from syscache).
156 : *
157 : * cmax is the outdating command's CID, but only when the failure code is
158 : * TM_SelfModified (i.e., something in the current transaction outdated the
159 : * tuple); otherwise cmax is zero. (We make this restriction because
160 : * HeapTupleHeaderGetCmax doesn't work for tuples outdated in other
161 : * transactions.)
162 : *
163 : * traversed indicates if an update chain was followed in order to try to lock
164 : * the target tuple. (This may be set in both success and failure cases.)
165 : */
166 : typedef struct TM_FailureData
167 : {
168 : ItemPointerData ctid;
169 : TransactionId xmax;
170 : CommandId cmax;
171 : bool traversed;
172 : } TM_FailureData;
173 :
174 : /*
175 : * State used when calling table_index_delete_tuples().
176 : *
177 : * Represents the status of table tuples, referenced by table TID and taken by
178 : * index AM from index tuples. State consists of high level parameters of the
179 : * deletion operation, plus two mutable palloc()'d arrays for information
180 : * about the status of individual table tuples. These are conceptually one
181 : * single array. Using two arrays keeps the TM_IndexDelete struct small,
182 : * which makes sorting the first array (the deltids array) fast.
183 : *
184 : * Some index AM callers perform simple index tuple deletion (by specifying
185 : * bottomup = false), and include only known-dead deltids. These known-dead
186 : * entries are all marked knowndeletable = true directly (typically these are
187 : * TIDs from LP_DEAD-marked index tuples), but that isn't strictly required.
188 : *
189 : * Callers that specify bottomup = true are "bottom-up index deletion"
190 : * callers. The considerations for the tableam are more subtle with these
191 : * callers because they ask the tableam to perform highly speculative work,
192 : * and might only expect the tableam to check a small fraction of all entries.
193 : * Caller is not allowed to specify knowndeletable = true for any entry
194 : * because everything is highly speculative. Bottom-up caller provides
195 : * context and hints to tableam -- see comments below for details on how index
196 : * AMs and tableams should coordinate during bottom-up index deletion.
197 : *
198 : * Simple index deletion callers may ask the tableam to perform speculative
199 : * work, too. This is a little like bottom-up deletion, but not too much.
200 : * The tableam will only perform speculative work when it's practically free
201 : * to do so in passing for simple deletion caller (while always performing
202 : * whatever work is needed to enable knowndeletable/LP_DEAD index tuples to
203 : * be deleted within index AM). This is the real reason why it's possible for
204 : * simple index deletion caller to specify knowndeletable = false up front
205 : * (this means "check if it's possible for me to delete corresponding index
206 : * tuple when it's cheap to do so in passing"). The index AM should only
207 : * include "extra" entries for index tuples whose TIDs point to a table block
208 : * that tableam is expected to have to visit anyway (in the event of a block
209 : * orientated tableam). The tableam isn't strictly obligated to check these
210 : * "extra" TIDs, but a block-based AM should always manage to do so in
211 : * practice.
212 : *
213 : * The final contents of the deltids/status arrays are interesting to callers
214 : * that ask tableam to perform speculative work (i.e. when _any_ items have
215 : * knowndeletable set to false up front). These index AM callers will
216 : * naturally need to consult final state to determine which index tuples are
217 : * in fact deletable.
218 : *
219 : * The index AM can keep track of which index tuple relates to which deltid by
220 : * setting idxoffnum (and/or relying on each entry being uniquely identifiable
221 : * using tid), which is important when the final contents of the array will
222 : * need to be interpreted -- the array can shrink from initial size after
223 : * tableam processing and/or have entries in a new order (tableam may sort
224 : * deltids array for its own reasons). Bottom-up callers may find that final
225 : * ndeltids is 0 on return from call to tableam, in which case no index tuple
226 : * deletions are possible. Simple deletion callers can rely on any entries
227 : * they know to be deletable appearing in the final array as deletable.
228 : */
229 : typedef struct TM_IndexDelete
230 : {
231 : ItemPointerData tid; /* table TID from index tuple */
232 : int16 id; /* Offset into TM_IndexStatus array */
233 : } TM_IndexDelete;
234 :
235 : typedef struct TM_IndexStatus
236 : {
237 : OffsetNumber idxoffnum; /* Index am page offset number */
238 : bool knowndeletable; /* Currently known to be deletable? */
239 :
240 : /* Bottom-up index deletion specific fields follow */
241 : bool promising; /* Promising (duplicate) index tuple? */
242 : int16 freespace; /* Space freed in index if deleted */
243 : } TM_IndexStatus;
244 :
245 : /*
246 : * Index AM/tableam coordination is central to the design of bottom-up index
247 : * deletion. The index AM provides hints about where to look to the tableam
248 : * by marking some entries as "promising". Index AM does this with duplicate
249 : * index tuples that are strongly suspected to be old versions left behind by
250 : * UPDATEs that did not logically modify indexed values. Index AM may find it
251 : * helpful to only mark entries as promising when they're thought to have been
252 : * affected by such an UPDATE in the recent past.
253 : *
254 : * Bottom-up index deletion casts a wide net at first, usually by including
255 : * all TIDs on a target index page. It is up to the tableam to worry about
256 : * the cost of checking transaction status information. The tableam is in
257 : * control, but needs careful guidance from the index AM. Index AM requests
258 : * that bottomupfreespace target be met, while tableam measures progress
259 : * towards that goal by tallying the per-entry freespace value for known
260 : * deletable entries. (All !bottomup callers can just set these space related
261 : * fields to zero.)
262 : */
263 : typedef struct TM_IndexDeleteOp
264 : {
265 : Relation irel; /* Target index relation */
266 : BlockNumber iblknum; /* Index block number (for error reports) */
267 : bool bottomup; /* Bottom-up (not simple) deletion? */
268 : int bottomupfreespace; /* Bottom-up space target */
269 :
270 : /* Mutable per-TID information follows (index AM initializes entries) */
271 : int ndeltids; /* Current # of deltids/status elements */
272 : TM_IndexDelete *deltids;
273 : TM_IndexStatus *status;
274 : } TM_IndexDeleteOp;
275 :
276 : /*
277 : * "options" flag bits for table_tuple_insert. Access methods may define
278 : * their own bits for internal use, as long as they don't collide with these.
279 : */
280 : /* TABLE_INSERT_SKIP_WAL was 0x0001; RelationNeedsWAL() now governs */
281 : #define TABLE_INSERT_SKIP_FSM 0x0002
282 : #define TABLE_INSERT_FROZEN 0x0004
283 : #define TABLE_INSERT_NO_LOGICAL 0x0008
284 :
285 : /* "options" flag bits for table_tuple_delete */
286 : #define TABLE_DELETE_CHANGING_PARTITION (1 << 0)
287 : #define TABLE_DELETE_NO_LOGICAL (1 << 1)
288 :
289 : /* "options" flag bits for table_tuple_update */
290 : #define TABLE_UPDATE_NO_LOGICAL (1 << 0)
291 :
292 : /* flag bits for table_tuple_lock */
293 : /* Follow tuples whose update is in progress if lock modes don't conflict */
294 : #define TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS (1 << 0)
295 : /* Follow update chain and lock latest version of tuple */
296 : #define TUPLE_LOCK_FLAG_FIND_LAST_VERSION (1 << 1)
297 :
298 :
299 : /* Typedef for callback function for table_index_build_scan */
300 : typedef void (*IndexBuildCallback) (Relation index,
301 : ItemPointer tid,
302 : Datum *values,
303 : bool *isnull,
304 : bool tupleIsAlive,
305 : void *state);
306 :
307 : /*
308 : * API struct for a table AM. Note this must be allocated in a
309 : * server-lifetime manner, typically as a static const struct, which then gets
310 : * returned by FormData_pg_am.amhandler.
311 : *
312 : * In most cases it's not appropriate to call the callbacks directly, use the
313 : * table_* wrapper functions instead.
314 : *
315 : * GetTableAmRoutine() asserts that required callbacks are filled in, remember
316 : * to update when adding a callback.
317 : */
318 : typedef struct TableAmRoutine
319 : {
320 : /* this must be set to T_TableAmRoutine */
321 : NodeTag type;
322 :
323 :
324 : /* ------------------------------------------------------------------------
325 : * Slot related callbacks.
326 : * ------------------------------------------------------------------------
327 : */
328 :
329 : /*
330 : * Return slot implementation suitable for storing a tuple of this AM.
331 : */
332 : const TupleTableSlotOps *(*slot_callbacks) (Relation rel);
333 :
334 :
335 : /* ------------------------------------------------------------------------
336 : * Table scan callbacks.
337 : * ------------------------------------------------------------------------
338 : */
339 :
340 : /*
341 : * Start a scan of `rel`. The callback has to return a TableScanDesc,
342 : * which will typically be embedded in a larger, AM specific, struct.
343 : *
344 : * If nkeys != 0, the results need to be filtered by those scan keys.
345 : *
346 : * pscan, if not NULL, will have already been initialized with
347 : * parallelscan_initialize(), and has to be for the same relation. Will
348 : * only be set coming from table_beginscan_parallel().
349 : *
350 : * `flags` is a bitmask indicating the type of scan (ScanOptions's
351 : * SO_TYPE_*, currently only one may be specified), options controlling
352 : * the scan's behaviour (ScanOptions's SO_ALLOW_*, several may be
353 : * specified, an AM may ignore unsupported ones), whether the snapshot
354 : * needs to be deallocated at scan_end (ScanOptions's SO_TEMP_SNAPSHOT),
355 : * and any number of the other ScanOptions values.
356 : */
357 : TableScanDesc (*scan_begin) (Relation rel,
358 : Snapshot snapshot,
359 : int nkeys, ScanKeyData *key,
360 : ParallelTableScanDesc pscan,
361 : uint32 flags);
362 :
363 : /*
364 : * Release resources and deallocate scan. If TableScanDesc.temp_snap,
365 : * TableScanDesc.rs_snapshot needs to be unregistered.
366 : */
367 : void (*scan_end) (TableScanDesc scan);
368 :
369 : /*
370 : * Restart relation scan. If set_params is set to true, allow_{strat,
371 : * sync, pagemode} (see scan_begin) changes should be taken into account.
372 : */
373 : void (*scan_rescan) (TableScanDesc scan, ScanKeyData *key,
374 : bool set_params, bool allow_strat,
375 : bool allow_sync, bool allow_pagemode);
376 :
377 : /*
378 : * Return next tuple from `scan`, store in slot.
379 : */
380 : bool (*scan_getnextslot) (TableScanDesc scan,
381 : ScanDirection direction,
382 : TupleTableSlot *slot);
383 :
384 : /*-----------
385 : * Optional functions to provide scanning for ranges of ItemPointers.
386 : * Implementations must either provide both of these functions, or neither
387 : * of them.
388 : *
389 : * Implementations of scan_set_tidrange must themselves handle
390 : * ItemPointers of any value. i.e, they must handle each of the following:
391 : *
392 : * 1) mintid or maxtid is beyond the end of the table; and
393 : * 2) mintid is above maxtid; and
394 : * 3) item offset for mintid or maxtid is beyond the maximum offset
395 : * allowed by the AM.
396 : *
397 : * Implementations can assume that scan_set_tidrange is always called
398 : * before scan_getnextslot_tidrange or after scan_rescan and before any
399 : * further calls to scan_getnextslot_tidrange.
400 : */
401 : void (*scan_set_tidrange) (TableScanDesc scan,
402 : ItemPointer mintid,
403 : ItemPointer maxtid);
404 :
405 : /*
406 : * Return next tuple from `scan` that's in the range of TIDs defined by
407 : * scan_set_tidrange.
408 : */
409 : bool (*scan_getnextslot_tidrange) (TableScanDesc scan,
410 : ScanDirection direction,
411 : TupleTableSlot *slot);
412 :
413 : /* ------------------------------------------------------------------------
414 : * Parallel table scan related functions.
415 : * ------------------------------------------------------------------------
416 : */
417 :
418 : /*
419 : * Estimate the size of shared memory needed for a parallel scan of this
420 : * relation. The snapshot does not need to be accounted for.
421 : */
422 : Size (*parallelscan_estimate) (Relation rel);
423 :
424 : /*
425 : * Initialize ParallelTableScanDesc for a parallel scan of this relation.
426 : * `pscan` will be sized according to parallelscan_estimate() for the same
427 : * relation.
428 : */
429 : Size (*parallelscan_initialize) (Relation rel,
430 : ParallelTableScanDesc pscan);
431 :
432 : /*
433 : * Reinitialize `pscan` for a new scan. `rel` will be the same relation as
434 : * when `pscan` was initialized by parallelscan_initialize.
435 : */
436 : void (*parallelscan_reinitialize) (Relation rel,
437 : ParallelTableScanDesc pscan);
438 :
439 :
440 : /* ------------------------------------------------------------------------
441 : * Index Scan Callbacks
442 : * ------------------------------------------------------------------------
443 : */
444 :
445 : /*
446 : * Prepare to fetch tuples from the relation, as needed when fetching
447 : * tuples for an index scan. The callback has to return an
448 : * IndexFetchTableData, which the AM will typically embed in a larger
449 : * structure with additional information.
450 : *
451 : * flags is a bitmask of ScanOptions affecting underlying table scan
452 : * behavior. See scan_begin() for more information on passing these.
453 : *
454 : * Tuples for an index scan can then be fetched via index_fetch_tuple.
455 : */
456 : struct IndexFetchTableData *(*index_fetch_begin) (Relation rel, uint32 flags);
457 :
458 : /*
459 : * Reset index fetch. Typically this will release cross index fetch
460 : * resources held in IndexFetchTableData.
461 : */
462 : void (*index_fetch_reset) (struct IndexFetchTableData *data);
463 :
464 : /*
465 : * Release resources and deallocate index fetch.
466 : */
467 : void (*index_fetch_end) (struct IndexFetchTableData *data);
468 :
469 : /*
470 : * Fetch tuple at `tid` into `slot`, after doing a visibility test
471 : * according to `snapshot`. If a tuple was found and passed the visibility
472 : * test, return true, false otherwise.
473 : *
474 : * Note that AMs that do not necessarily update indexes when indexed
475 : * columns do not change, need to return the current/correct version of
476 : * the tuple that is visible to the snapshot, even if the tid points to an
477 : * older version of the tuple.
478 : *
479 : * *call_again is false on the first call to index_fetch_tuple for a tid.
480 : * If there potentially is another tuple matching the tid, *call_again
481 : * needs to be set to true by index_fetch_tuple, signaling to the caller
482 : * that index_fetch_tuple should be called again for the same tid.
483 : *
484 : * *all_dead, if all_dead is not NULL, should be set to true by
485 : * index_fetch_tuple iff it is guaranteed that no backend needs to see
486 : * that tuple. Index AMs can use that to avoid returning that tid in
487 : * future searches.
488 : */
489 : bool (*index_fetch_tuple) (struct IndexFetchTableData *scan,
490 : ItemPointer tid,
491 : Snapshot snapshot,
492 : TupleTableSlot *slot,
493 : bool *call_again, bool *all_dead);
494 :
495 :
496 : /* ------------------------------------------------------------------------
497 : * Callbacks for non-modifying operations on individual tuples
498 : * ------------------------------------------------------------------------
499 : */
500 :
501 : /*
502 : * Fetch tuple at `tid` into `slot`, after doing a visibility test
503 : * according to `snapshot`. If a tuple was found and passed the visibility
504 : * test, returns true, false otherwise.
505 : */
506 : bool (*tuple_fetch_row_version) (Relation rel,
507 : ItemPointer tid,
508 : Snapshot snapshot,
509 : TupleTableSlot *slot);
510 :
511 : /*
512 : * Is tid valid for a scan of this relation.
513 : */
514 : bool (*tuple_tid_valid) (TableScanDesc scan,
515 : ItemPointer tid);
516 :
517 : /*
518 : * Return the latest version of the tuple at `tid`, by updating `tid` to
519 : * point at the newest version.
520 : */
521 : void (*tuple_get_latest_tid) (TableScanDesc scan,
522 : ItemPointer tid);
523 :
524 : /*
525 : * Does the tuple in `slot` satisfy `snapshot`? The slot needs to be of
526 : * the appropriate type for the AM.
527 : */
528 : bool (*tuple_satisfies_snapshot) (Relation rel,
529 : TupleTableSlot *slot,
530 : Snapshot snapshot);
531 :
532 : /* see table_index_delete_tuples() */
533 : TransactionId (*index_delete_tuples) (Relation rel,
534 : TM_IndexDeleteOp *delstate);
535 :
536 :
537 : /* ------------------------------------------------------------------------
538 : * Manipulations of physical tuples.
539 : * ------------------------------------------------------------------------
540 : */
541 :
542 : /* see table_tuple_insert() for reference about parameters */
543 : void (*tuple_insert) (Relation rel, TupleTableSlot *slot,
544 : CommandId cid, uint32 options,
545 : BulkInsertStateData *bistate);
546 :
547 : /* see table_tuple_insert_speculative() for reference about parameters */
548 : void (*tuple_insert_speculative) (Relation rel,
549 : TupleTableSlot *slot,
550 : CommandId cid,
551 : uint32 options,
552 : BulkInsertStateData *bistate,
553 : uint32 specToken);
554 :
555 : /* see table_tuple_complete_speculative() for reference about parameters */
556 : void (*tuple_complete_speculative) (Relation rel,
557 : TupleTableSlot *slot,
558 : uint32 specToken,
559 : bool succeeded);
560 :
561 : /* see table_multi_insert() for reference about parameters */
562 : void (*multi_insert) (Relation rel, TupleTableSlot **slots, int nslots,
563 : CommandId cid, uint32 options, BulkInsertStateData *bistate);
564 :
565 : /* see table_tuple_delete() for reference about parameters */
566 : TM_Result (*tuple_delete) (Relation rel,
567 : ItemPointer tid,
568 : CommandId cid,
569 : uint32 options,
570 : Snapshot snapshot,
571 : Snapshot crosscheck,
572 : bool wait,
573 : TM_FailureData *tmfd);
574 :
575 : /* see table_tuple_update() for reference about parameters */
576 : TM_Result (*tuple_update) (Relation rel,
577 : ItemPointer otid,
578 : TupleTableSlot *slot,
579 : CommandId cid,
580 : uint32 options,
581 : Snapshot snapshot,
582 : Snapshot crosscheck,
583 : bool wait,
584 : TM_FailureData *tmfd,
585 : LockTupleMode *lockmode,
586 : TU_UpdateIndexes *update_indexes);
587 :
588 : /* see table_tuple_lock() for reference about parameters */
589 : TM_Result (*tuple_lock) (Relation rel,
590 : ItemPointer tid,
591 : Snapshot snapshot,
592 : TupleTableSlot *slot,
593 : CommandId cid,
594 : LockTupleMode mode,
595 : LockWaitPolicy wait_policy,
596 : uint8 flags,
597 : TM_FailureData *tmfd);
598 :
599 : /*
600 : * Perform operations necessary to complete insertions made via
601 : * tuple_insert and multi_insert with a BulkInsertState specified. In-tree
602 : * access methods ceased to use this.
603 : *
604 : * Typically callers of tuple_insert and multi_insert will just pass all
605 : * the flags that apply to them, and each AM has to decide which of them
606 : * make sense for it, and then only take actions in finish_bulk_insert for
607 : * those flags, and ignore others.
608 : *
609 : * Optional callback.
610 : */
611 : void (*finish_bulk_insert) (Relation rel, uint32 options);
612 :
613 :
614 : /* ------------------------------------------------------------------------
615 : * DDL related functionality.
616 : * ------------------------------------------------------------------------
617 : */
618 :
619 : /*
620 : * This callback needs to create new relation storage for `rel`, with
621 : * appropriate durability behaviour for `persistence`.
622 : *
623 : * Note that only the subset of the relcache filled by
624 : * RelationBuildLocalRelation() can be relied upon and that the relation's
625 : * catalog entries will either not yet exist (new relation), or will still
626 : * reference the old relfilelocator.
627 : *
628 : * As output *freezeXid, *minmulti must be set to the values appropriate
629 : * for pg_class.{relfrozenxid, relminmxid}. For AMs that don't need those
630 : * fields to be filled they can be set to InvalidTransactionId and
631 : * InvalidMultiXactId, respectively.
632 : *
633 : * See also table_relation_set_new_filelocator().
634 : */
635 : void (*relation_set_new_filelocator) (Relation rel,
636 : const RelFileLocator *newrlocator,
637 : char persistence,
638 : TransactionId *freezeXid,
639 : MultiXactId *minmulti);
640 :
641 : /*
642 : * This callback needs to remove all contents from `rel`'s current
643 : * relfilelocator. No provisions for transactional behaviour need to be
644 : * made. Often this can be implemented by truncating the underlying
645 : * storage to its minimal size.
646 : *
647 : * See also table_relation_nontransactional_truncate().
648 : */
649 : void (*relation_nontransactional_truncate) (Relation rel);
650 :
651 : /*
652 : * See table_relation_copy_data().
653 : *
654 : * This can typically be implemented by directly copying the underlying
655 : * storage, unless it contains references to the tablespace internally.
656 : */
657 : void (*relation_copy_data) (Relation rel,
658 : const RelFileLocator *newrlocator);
659 :
660 : /* See table_relation_copy_for_cluster() */
661 : void (*relation_copy_for_cluster) (Relation OldTable,
662 : Relation NewTable,
663 : Relation OldIndex,
664 : bool use_sort,
665 : TransactionId OldestXmin,
666 : Snapshot snapshot,
667 : TransactionId *xid_cutoff,
668 : MultiXactId *multi_cutoff,
669 : double *num_tuples,
670 : double *tups_vacuumed,
671 : double *tups_recently_dead);
672 :
673 : /*
674 : * React to VACUUM command on the relation. The VACUUM can be triggered by
675 : * a user or by autovacuum. The specific actions performed by the AM will
676 : * depend heavily on the individual AM.
677 : *
678 : * On entry a transaction is already established, and the relation is
679 : * locked with a ShareUpdateExclusive lock.
680 : *
681 : * Note that neither VACUUM FULL (and CLUSTER), nor ANALYZE go through
682 : * this routine, even if (for ANALYZE) it is part of the same VACUUM
683 : * command.
684 : *
685 : * There probably, in the future, needs to be a separate callback to
686 : * integrate with autovacuum's scheduling.
687 : */
688 : void (*relation_vacuum) (Relation rel,
689 : const VacuumParams *params,
690 : BufferAccessStrategy bstrategy);
691 :
692 : /*
693 : * Prepare to analyze block `blockno` of `scan`. The scan has been started
694 : * with table_beginscan_analyze(). See also
695 : * table_scan_analyze_next_block().
696 : *
697 : * The callback may acquire resources like locks that are held until
698 : * table_scan_analyze_next_tuple() returns false. It e.g. can make sense
699 : * to hold a lock until all tuples on a block have been analyzed by
700 : * scan_analyze_next_tuple.
701 : *
702 : * The callback can return false if the block is not suitable for
703 : * sampling, e.g. because it's a metapage that could never contain tuples.
704 : *
705 : * XXX: This obviously is primarily suited for block-based AMs. It's not
706 : * clear what a good interface for non block based AMs would be, so there
707 : * isn't one yet.
708 : */
709 : bool (*scan_analyze_next_block) (TableScanDesc scan,
710 : ReadStream *stream);
711 :
712 : /*
713 : * See table_scan_analyze_next_tuple().
714 : *
715 : * Not every AM might have a meaningful concept of dead rows, in which
716 : * case it's OK to not increment *deadrows - but note that that may
717 : * influence autovacuum scheduling (see comment for relation_vacuum
718 : * callback).
719 : */
720 : bool (*scan_analyze_next_tuple) (TableScanDesc scan,
721 : double *liverows,
722 : double *deadrows,
723 : TupleTableSlot *slot);
724 :
725 : /* see table_index_build_range_scan for reference about parameters */
726 : double (*index_build_range_scan) (Relation table_rel,
727 : Relation index_rel,
728 : IndexInfo *index_info,
729 : bool allow_sync,
730 : bool anyvisible,
731 : bool progress,
732 : BlockNumber start_blockno,
733 : BlockNumber numblocks,
734 : IndexBuildCallback callback,
735 : void *callback_state,
736 : TableScanDesc scan);
737 :
738 : /* see table_index_validate_scan for reference about parameters */
739 : void (*index_validate_scan) (Relation table_rel,
740 : Relation index_rel,
741 : IndexInfo *index_info,
742 : Snapshot snapshot,
743 : ValidateIndexState *state);
744 :
745 :
746 : /* ------------------------------------------------------------------------
747 : * Miscellaneous functions.
748 : * ------------------------------------------------------------------------
749 : */
750 :
751 : /*
752 : * See table_relation_size().
753 : *
754 : * Note that currently a few callers use the MAIN_FORKNUM size to figure
755 : * out the range of potentially interesting blocks (brin, analyze). It's
756 : * probable that we'll need to revise the interface for those at some
757 : * point.
758 : */
759 : uint64 (*relation_size) (Relation rel, ForkNumber forkNumber);
760 :
761 :
762 : /*
763 : * This callback should return true if the relation requires a TOAST table
764 : * and false if it does not. It may wish to examine the relation's tuple
765 : * descriptor before making a decision, but if it uses some other method
766 : * of storing large values (or if it does not support them) it can simply
767 : * return false.
768 : */
769 : bool (*relation_needs_toast_table) (Relation rel);
770 :
771 : /*
772 : * This callback should return the OID of the table AM that implements
773 : * TOAST tables for this AM. If the relation_needs_toast_table callback
774 : * always returns false, this callback is not required.
775 : */
776 : Oid (*relation_toast_am) (Relation rel);
777 :
778 : /*
779 : * This callback is invoked when detoasting a value stored in a toast
780 : * table implemented by this AM. See table_relation_fetch_toast_slice()
781 : * for more details.
782 : */
783 : void (*relation_fetch_toast_slice) (Relation toastrel, Oid valueid,
784 : int32 attrsize,
785 : int32 sliceoffset,
786 : int32 slicelength,
787 : varlena *result);
788 :
789 :
790 : /* ------------------------------------------------------------------------
791 : * Planner related functions.
792 : * ------------------------------------------------------------------------
793 : */
794 :
795 : /*
796 : * See table_relation_estimate_size().
797 : *
798 : * While block oriented, it shouldn't be too hard for an AM that doesn't
799 : * internally use blocks to convert into a usable representation.
800 : *
801 : * This differs from the relation_size callback by returning size
802 : * estimates (both relation size and tuple count) for planning purposes,
803 : * rather than returning a currently correct estimate.
804 : */
805 : void (*relation_estimate_size) (Relation rel, int32 *attr_widths,
806 : BlockNumber *pages, double *tuples,
807 : double *allvisfrac);
808 :
809 :
810 : /* ------------------------------------------------------------------------
811 : * Executor related functions.
812 : * ------------------------------------------------------------------------
813 : */
814 :
815 : /*
816 : * Fetch the next tuple of a bitmap table scan into `slot` and return true
817 : * if a visible tuple was found, false otherwise.
818 : *
819 : * `lossy_pages` is incremented if the bitmap is lossy for the selected
820 : * page; otherwise, `exact_pages` is incremented. These are tracked for
821 : * display in EXPLAIN ANALYZE output.
822 : *
823 : * Prefetching additional data from the bitmap is left to the table AM.
824 : *
825 : * This is an optional callback.
826 : */
827 : bool (*scan_bitmap_next_tuple) (TableScanDesc scan,
828 : TupleTableSlot *slot,
829 : bool *recheck,
830 : uint64 *lossy_pages,
831 : uint64 *exact_pages);
832 :
833 : /*
834 : * Prepare to fetch tuples from the next block in a sample scan. Return
835 : * false if the sample scan is finished, true otherwise. `scan` was
836 : * started via table_beginscan_sampling().
837 : *
838 : * Typically this will first determine the target block by calling the
839 : * TsmRoutine's NextSampleBlock() callback if not NULL, or alternatively
840 : * perform a sequential scan over all blocks. The determined block is
841 : * then typically read and pinned.
842 : *
843 : * As the TsmRoutine interface is block based, a block needs to be passed
844 : * to NextSampleBlock(). If that's not appropriate for an AM, it
845 : * internally needs to perform mapping between the internal and a block
846 : * based representation.
847 : *
848 : * Note that it's not acceptable to hold deadlock prone resources such as
849 : * lwlocks until scan_sample_next_tuple() has exhausted the tuples on the
850 : * block - the tuple is likely to be returned to an upper query node, and
851 : * the next call could be off a long while. Holding buffer pins and such
852 : * is obviously OK.
853 : *
854 : * Currently it is required to implement this interface, as there's no
855 : * alternative way (contrary e.g. to bitmap scans) to implement sample
856 : * scans. If infeasible to implement, the AM may raise an error.
857 : */
858 : bool (*scan_sample_next_block) (TableScanDesc scan,
859 : SampleScanState *scanstate);
860 :
861 : /*
862 : * This callback, only called after scan_sample_next_block has returned
863 : * true, should determine the next tuple to be returned from the selected
864 : * block using the TsmRoutine's NextSampleTuple() callback.
865 : *
866 : * The callback needs to perform visibility checks, and only return
867 : * visible tuples. That obviously can mean calling NextSampleTuple()
868 : * multiple times.
869 : *
870 : * The TsmRoutine interface assumes that there's a maximum offset on a
871 : * given page, so if that doesn't apply to an AM, it needs to emulate that
872 : * assumption somehow.
873 : */
874 : bool (*scan_sample_next_tuple) (TableScanDesc scan,
875 : SampleScanState *scanstate,
876 : TupleTableSlot *slot);
877 :
878 : } TableAmRoutine;
879 :
880 :
881 : /* ----------------------------------------------------------------------------
882 : * Slot functions.
883 : * ----------------------------------------------------------------------------
884 : */
885 :
886 : /*
887 : * Returns slot callbacks suitable for holding tuples of the appropriate type
888 : * for the relation. Works for tables, views, foreign tables and partitioned
889 : * tables.
890 : */
891 : extern const TupleTableSlotOps *table_slot_callbacks(Relation relation);
892 :
893 : /*
894 : * Returns slot using the callbacks returned by table_slot_callbacks(), and
895 : * registers it on *reglist.
896 : */
897 : extern TupleTableSlot *table_slot_create(Relation relation, List **reglist);
898 :
899 :
900 : /* ----------------------------------------------------------------------------
901 : * Table scan functions.
902 : * ----------------------------------------------------------------------------
903 : */
904 :
905 : /*
906 : * A wrapper around the Table Access Method scan_begin callback, to centralize
907 : * error checking. All calls to ->scan_begin() should go through this
908 : * function.
909 : *
910 : * The caller-provided user_flags are validated against SO_INTERNAL_FLAGS to
911 : * catch callers that accidentally pass scan-type or other internal flags.
912 : */
913 : static TableScanDesc
914 488133 : table_beginscan_common(Relation rel, Snapshot snapshot, int nkeys,
915 : ScanKeyData *key, ParallelTableScanDesc pscan,
916 : uint32 flags, uint32 user_flags)
917 : {
918 : Assert((user_flags & SO_INTERNAL_FLAGS) == 0);
919 : Assert((flags & ~SO_INTERNAL_FLAGS) == 0);
920 488133 : flags |= user_flags;
921 :
922 : /*
923 : * We don't allow scans to be started while CheckXidAlive is set, except
924 : * via systable_beginscan() et al. See detailed comments in xact.c where
925 : * these variables are declared.
926 : */
927 488133 : if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
928 0 : elog(ERROR, "scan started during logical decoding");
929 :
930 488133 : return rel->rd_tableam->scan_begin(rel, snapshot, nkeys, key, pscan, flags);
931 : }
932 :
933 : /*
934 : * Start a scan of `rel`. Returned tuples pass a visibility test of
935 : * `snapshot`, and if nkeys != 0, the results are filtered by those scan keys.
936 : *
937 : * flags is a bitmask of ScanOptions. No SO_INTERNAL_FLAGS are permitted.
938 : */
939 : static inline TableScanDesc
940 140703 : table_beginscan(Relation rel, Snapshot snapshot,
941 : int nkeys, ScanKeyData *key, uint32 flags)
942 : {
943 140703 : uint32 internal_flags = SO_TYPE_SEQSCAN |
944 : SO_ALLOW_STRAT | SO_ALLOW_SYNC | SO_ALLOW_PAGEMODE;
945 :
946 140703 : return table_beginscan_common(rel, snapshot, nkeys, key, NULL,
947 : internal_flags, flags);
948 : }
949 :
950 : /*
951 : * Like table_beginscan(), but for scanning catalog. It'll automatically use a
952 : * snapshot appropriate for scanning catalog relations.
953 : */
954 : extern TableScanDesc table_beginscan_catalog(Relation relation, int nkeys,
955 : ScanKeyData *key);
956 :
957 : /*
958 : * Like table_beginscan(), but table_beginscan_strat() offers an extended API
959 : * that lets the caller control whether a nondefault buffer access strategy
960 : * can be used, and whether syncscan can be chosen (possibly resulting in the
961 : * scan not starting from block zero). Both of these default to true with
962 : * plain table_beginscan.
963 : */
964 : static inline TableScanDesc
965 270193 : table_beginscan_strat(Relation rel, Snapshot snapshot,
966 : int nkeys, ScanKeyData *key,
967 : bool allow_strat, bool allow_sync)
968 : {
969 270193 : uint32 flags = SO_TYPE_SEQSCAN | SO_ALLOW_PAGEMODE;
970 :
971 270193 : if (allow_strat)
972 270193 : flags |= SO_ALLOW_STRAT;
973 270193 : if (allow_sync)
974 34472 : flags |= SO_ALLOW_SYNC;
975 :
976 270193 : return table_beginscan_common(rel, snapshot, nkeys, key, NULL,
977 : flags, SO_NONE);
978 : }
979 :
980 : /*
981 : * table_beginscan_bm is an alternative entry point for setting up a
982 : * TableScanDesc for a bitmap heap scan. Although that scan technology is
983 : * really quite unlike a standard seqscan, there is just enough commonality to
984 : * make it worth using the same data structure.
985 : *
986 : * flags is a bitmask of ScanOptions. No SO_INTERNAL_FLAGS are permitted.
987 : */
988 : static inline TableScanDesc
989 13627 : table_beginscan_bm(Relation rel, Snapshot snapshot,
990 : int nkeys, ScanKeyData *key, uint32 flags)
991 : {
992 13627 : uint32 internal_flags = SO_TYPE_BITMAPSCAN | SO_ALLOW_PAGEMODE;
993 :
994 13627 : return table_beginscan_common(rel, snapshot, nkeys, key, NULL,
995 : internal_flags, flags);
996 : }
997 :
998 : /*
999 : * table_beginscan_sampling is an alternative entry point for setting up a
1000 : * TableScanDesc for a TABLESAMPLE scan. As with bitmap scans, it's worth
1001 : * using the same data structure although the behavior is rather different.
1002 : * In addition to the options offered by table_beginscan_strat, this call
1003 : * also allows control of whether page-mode visibility checking is used.
1004 : *
1005 : * flags is a bitmask of ScanOptions. No SO_INTERNAL_FLAGS are permitted.
1006 : */
1007 : static inline TableScanDesc
1008 94 : table_beginscan_sampling(Relation rel, Snapshot snapshot,
1009 : int nkeys, ScanKeyData *key,
1010 : bool allow_strat, bool allow_sync,
1011 : bool allow_pagemode, uint32 flags)
1012 : {
1013 94 : uint32 internal_flags = SO_TYPE_SAMPLESCAN;
1014 :
1015 94 : if (allow_strat)
1016 86 : internal_flags |= SO_ALLOW_STRAT;
1017 94 : if (allow_sync)
1018 44 : internal_flags |= SO_ALLOW_SYNC;
1019 94 : if (allow_pagemode)
1020 78 : internal_flags |= SO_ALLOW_PAGEMODE;
1021 :
1022 94 : return table_beginscan_common(rel, snapshot, nkeys, key, NULL,
1023 : internal_flags, flags);
1024 : }
1025 :
1026 : /*
1027 : * table_beginscan_tid is an alternative entry point for setting up a
1028 : * TableScanDesc for a Tid scan. As with bitmap scans, it's worth using
1029 : * the same data structure although the behavior is rather different.
1030 : */
1031 : static inline TableScanDesc
1032 474 : table_beginscan_tid(Relation rel, Snapshot snapshot)
1033 : {
1034 474 : uint32 flags = SO_TYPE_TIDSCAN;
1035 :
1036 474 : return table_beginscan_common(rel, snapshot, 0, NULL, NULL,
1037 : flags, SO_NONE);
1038 : }
1039 :
1040 : /*
1041 : * table_beginscan_analyze is an alternative entry point for setting up a
1042 : * TableScanDesc for an ANALYZE scan. As with bitmap scans, it's worth using
1043 : * the same data structure although the behavior is rather different.
1044 : */
1045 : static inline TableScanDesc
1046 10931 : table_beginscan_analyze(Relation rel)
1047 : {
1048 10931 : uint32 flags = SO_TYPE_ANALYZE;
1049 :
1050 10931 : return table_beginscan_common(rel, NULL, 0, NULL, NULL,
1051 : flags, SO_NONE);
1052 : }
1053 :
1054 : /*
1055 : * End relation scan.
1056 : */
1057 : static inline void
1058 484866 : table_endscan(TableScanDesc scan)
1059 : {
1060 484866 : scan->rs_rd->rd_tableam->scan_end(scan);
1061 484866 : }
1062 :
1063 : /*
1064 : * Restart a relation scan.
1065 : */
1066 : static inline void
1067 870603 : table_rescan(TableScanDesc scan, ScanKeyData *key)
1068 : {
1069 870603 : scan->rs_rd->rd_tableam->scan_rescan(scan, key, false, false, false, false);
1070 870603 : }
1071 :
1072 : /*
1073 : * Restart a relation scan after changing params.
1074 : *
1075 : * This call allows changing the buffer strategy, syncscan, and pagemode
1076 : * options before starting a fresh scan. Note that although the actual use of
1077 : * syncscan might change (effectively, enabling or disabling reporting), the
1078 : * previously selected startblock will be kept.
1079 : */
1080 : static inline void
1081 19 : table_rescan_set_params(TableScanDesc scan, ScanKeyData *key,
1082 : bool allow_strat, bool allow_sync, bool allow_pagemode)
1083 : {
1084 19 : scan->rs_rd->rd_tableam->scan_rescan(scan, key, true,
1085 : allow_strat, allow_sync,
1086 : allow_pagemode);
1087 19 : }
1088 :
1089 : /*
1090 : * Return next tuple from `scan`, store in slot.
1091 : */
1092 : static inline bool
1093 67735408 : table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
1094 : {
1095 67735408 : slot->tts_tableOid = RelationGetRelid(sscan->rs_rd);
1096 :
1097 : /* We don't expect actual scans using NoMovementScanDirection */
1098 : Assert(direction == ForwardScanDirection ||
1099 : direction == BackwardScanDirection);
1100 :
1101 67735408 : return sscan->rs_rd->rd_tableam->scan_getnextslot(sscan, direction, slot);
1102 : }
1103 :
1104 : /* ----------------------------------------------------------------------------
1105 : * TID Range scanning related functions.
1106 : * ----------------------------------------------------------------------------
1107 : */
1108 :
1109 : /*
1110 : * table_beginscan_tidrange is the entry point for setting up a TableScanDesc
1111 : * for a TID range scan.
1112 : *
1113 : * flags is a bitmask of ScanOptions. No SO_INTERNAL_FLAGS are permitted.
1114 : */
1115 : static inline TableScanDesc
1116 1234 : table_beginscan_tidrange(Relation rel, Snapshot snapshot,
1117 : ItemPointer mintid,
1118 : ItemPointer maxtid, uint32 flags)
1119 : {
1120 : TableScanDesc sscan;
1121 1234 : uint32 internal_flags = SO_TYPE_TIDRANGESCAN | SO_ALLOW_PAGEMODE;
1122 :
1123 1234 : sscan = table_beginscan_common(rel, snapshot, 0, NULL, NULL,
1124 : internal_flags, flags);
1125 :
1126 : /* Set the range of TIDs to scan */
1127 1234 : sscan->rs_rd->rd_tableam->scan_set_tidrange(sscan, mintid, maxtid);
1128 :
1129 1234 : return sscan;
1130 : }
1131 :
1132 : /*
1133 : * table_rescan_tidrange resets the scan position and sets the minimum and
1134 : * maximum TID range to scan for a TableScanDesc created by
1135 : * table_beginscan_tidrange.
1136 : */
1137 : static inline void
1138 140 : table_rescan_tidrange(TableScanDesc sscan, ItemPointer mintid,
1139 : ItemPointer maxtid)
1140 : {
1141 : /* Ensure table_beginscan_tidrange() was used. */
1142 : Assert((sscan->rs_flags & SO_TYPE_TIDRANGESCAN) != 0);
1143 :
1144 140 : sscan->rs_rd->rd_tableam->scan_rescan(sscan, NULL, false, false, false, false);
1145 140 : sscan->rs_rd->rd_tableam->scan_set_tidrange(sscan, mintid, maxtid);
1146 140 : }
1147 :
1148 : /*
1149 : * Fetch the next tuple from `sscan` for a TID range scan created by
1150 : * table_beginscan_tidrange(). Stores the tuple in `slot` and returns true,
1151 : * or returns false if no more tuples exist in the range.
1152 : */
1153 : static inline bool
1154 6512 : table_scan_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction,
1155 : TupleTableSlot *slot)
1156 : {
1157 : /* Ensure table_beginscan_tidrange() was used. */
1158 : Assert((sscan->rs_flags & SO_TYPE_TIDRANGESCAN) != 0);
1159 :
1160 : /* We don't expect actual scans using NoMovementScanDirection */
1161 : Assert(direction == ForwardScanDirection ||
1162 : direction == BackwardScanDirection);
1163 :
1164 6512 : return sscan->rs_rd->rd_tableam->scan_getnextslot_tidrange(sscan,
1165 : direction,
1166 : slot);
1167 : }
1168 :
1169 :
1170 : /* ----------------------------------------------------------------------------
1171 : * Parallel table scan related functions.
1172 : * ----------------------------------------------------------------------------
1173 : */
1174 :
1175 : /*
1176 : * Estimate the size of shared memory needed for a parallel scan of this
1177 : * relation.
1178 : */
1179 : extern Size table_parallelscan_estimate(Relation rel, Snapshot snapshot);
1180 :
1181 : /*
1182 : * Initialize ParallelTableScanDesc for a parallel scan of this
1183 : * relation. `pscan` needs to be sized according to parallelscan_estimate()
1184 : * for the same relation. Call this just once in the leader process; then,
1185 : * individual workers attach via table_beginscan_parallel.
1186 : */
1187 : extern void table_parallelscan_initialize(Relation rel,
1188 : ParallelTableScanDesc pscan,
1189 : Snapshot snapshot);
1190 :
1191 : /*
1192 : * Begin a parallel scan. `pscan` needs to have been initialized with
1193 : * table_parallelscan_initialize(), for the same relation. The initialization
1194 : * does not need to have happened in this backend.
1195 : *
1196 : * flags is a bitmask of ScanOptions. No SO_INTERNAL_FLAGS are permitted.
1197 : *
1198 : * Caller must hold a suitable lock on the relation.
1199 : */
1200 : extern TableScanDesc table_beginscan_parallel(Relation relation,
1201 : ParallelTableScanDesc pscan,
1202 : uint32 flags);
1203 :
1204 : /*
1205 : * Begin a parallel tid range scan. `pscan` needs to have been initialized
1206 : * with table_parallelscan_initialize(), for the same relation. The
1207 : * initialization does not need to have happened in this backend.
1208 : *
1209 : * flags is a bitmask of ScanOptions. No SO_INTERNAL_FLAGS are permitted.
1210 : *
1211 : * Caller must hold a suitable lock on the relation.
1212 : */
1213 : extern TableScanDesc table_beginscan_parallel_tidrange(Relation relation,
1214 : ParallelTableScanDesc pscan,
1215 : uint32 flags);
1216 :
1217 : /*
1218 : * Restart a parallel scan. Call this in the leader process. Caller is
1219 : * responsible for making sure that all workers have finished the scan
1220 : * beforehand.
1221 : */
1222 : static inline void
1223 152 : table_parallelscan_reinitialize(Relation rel, ParallelTableScanDesc pscan)
1224 : {
1225 152 : rel->rd_tableam->parallelscan_reinitialize(rel, pscan);
1226 152 : }
1227 :
1228 :
1229 : /* ----------------------------------------------------------------------------
1230 : * Index scan related functions.
1231 : * ----------------------------------------------------------------------------
1232 : */
1233 :
1234 : /*
1235 : * Prepare to fetch tuples from the relation, as needed when fetching tuples
1236 : * for an index scan.
1237 : *
1238 : * flags is a bitmask of ScanOptions. No SO_INTERNAL_FLAGS are permitted.
1239 : *
1240 : * Tuples for an index scan can then be fetched via table_index_fetch_tuple().
1241 : */
1242 : static inline IndexFetchTableData *
1243 17432190 : table_index_fetch_begin(Relation rel, uint32 flags)
1244 : {
1245 : Assert((flags & SO_INTERNAL_FLAGS) == 0);
1246 :
1247 : /*
1248 : * We don't allow scans to be started while CheckXidAlive is set, except
1249 : * via systable_beginscan() et al. See detailed comments in xact.c where
1250 : * these variables are declared.
1251 : */
1252 17432190 : if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
1253 0 : elog(ERROR, "scan started during logical decoding");
1254 :
1255 17432190 : return rel->rd_tableam->index_fetch_begin(rel, flags);
1256 : }
1257 :
1258 : /*
1259 : * Reset index fetch. Typically this will release cross index fetch resources
1260 : * held in IndexFetchTableData.
1261 : */
1262 : static inline void
1263 14840475 : table_index_fetch_reset(struct IndexFetchTableData *scan)
1264 : {
1265 14840475 : scan->rel->rd_tableam->index_fetch_reset(scan);
1266 14840475 : }
1267 :
1268 : /*
1269 : * Release resources and deallocate index fetch.
1270 : */
1271 : static inline void
1272 17430949 : table_index_fetch_end(struct IndexFetchTableData *scan)
1273 : {
1274 17430949 : scan->rel->rd_tableam->index_fetch_end(scan);
1275 17430949 : }
1276 :
1277 : /*
1278 : * Fetches, as part of an index scan, tuple at `tid` into `slot`, after doing
1279 : * a visibility test according to `snapshot`. If a tuple was found and passed
1280 : * the visibility test, returns true, false otherwise. Note that *tid may be
1281 : * modified when we return true (see later remarks on multiple row versions
1282 : * reachable via a single index entry).
1283 : *
1284 : * *call_again needs to be false on the first call to table_index_fetch_tuple() for
1285 : * a tid. If there potentially is another tuple matching the tid, *call_again
1286 : * will be set to true, signaling that table_index_fetch_tuple() should be called
1287 : * again for the same tid.
1288 : *
1289 : * *all_dead, if all_dead is not NULL, will be set to true by
1290 : * table_index_fetch_tuple() iff it is guaranteed that no backend needs to see
1291 : * that tuple. Index AMs can use that to avoid returning that tid in future
1292 : * searches.
1293 : *
1294 : * The difference between this function and table_tuple_fetch_row_version()
1295 : * is that this function returns the currently visible version of a row if
1296 : * the AM supports storing multiple row versions reachable via a single index
1297 : * entry (like heap's HOT). Whereas table_tuple_fetch_row_version() only
1298 : * evaluates the tuple exactly at `tid`. Outside of index entry ->table tuple
1299 : * lookups, table_tuple_fetch_row_version() is what's usually needed.
1300 : */
1301 : static inline bool
1302 24521150 : table_index_fetch_tuple(struct IndexFetchTableData *scan,
1303 : ItemPointer tid,
1304 : Snapshot snapshot,
1305 : TupleTableSlot *slot,
1306 : bool *call_again, bool *all_dead)
1307 : {
1308 24521150 : return scan->rel->rd_tableam->index_fetch_tuple(scan, tid, snapshot,
1309 : slot, call_again,
1310 : all_dead);
1311 : }
1312 :
1313 : /*
1314 : * This is a convenience wrapper around table_index_fetch_tuple() which
1315 : * returns whether there are table tuple items corresponding to an index
1316 : * entry. This likely is only useful to verify if there's a conflict in a
1317 : * unique index.
1318 : */
1319 : extern bool table_index_fetch_tuple_check(Relation rel,
1320 : ItemPointer tid,
1321 : Snapshot snapshot,
1322 : bool *all_dead);
1323 :
1324 :
1325 : /* ------------------------------------------------------------------------
1326 : * Functions for non-modifying operations on individual tuples
1327 : * ------------------------------------------------------------------------
1328 : */
1329 :
1330 :
1331 : /*
1332 : * Fetch tuple at `tid` into `slot`, after doing a visibility test according to
1333 : * `snapshot`. If a tuple was found and passed the visibility test, returns
1334 : * true, false otherwise.
1335 : *
1336 : * See table_index_fetch_tuple's comment about what the difference between
1337 : * these functions is. It is correct to use this function outside of index
1338 : * entry->table tuple lookups.
1339 : */
1340 : static inline bool
1341 2838320 : table_tuple_fetch_row_version(Relation rel,
1342 : ItemPointer tid,
1343 : Snapshot snapshot,
1344 : TupleTableSlot *slot)
1345 : {
1346 : /*
1347 : * We don't expect direct calls to table_tuple_fetch_row_version with
1348 : * valid CheckXidAlive for catalog or regular tables. See detailed
1349 : * comments in xact.c where these variables are declared.
1350 : */
1351 2838320 : if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
1352 0 : elog(ERROR, "unexpected table_tuple_fetch_row_version call during logical decoding");
1353 :
1354 2838320 : return rel->rd_tableam->tuple_fetch_row_version(rel, tid, snapshot, slot);
1355 : }
1356 :
1357 : /*
1358 : * Verify that `tid` is a potentially valid tuple identifier. That doesn't
1359 : * mean that the pointed to row needs to exist or be visible, but that
1360 : * attempting to fetch the row (e.g. with table_tuple_get_latest_tid() or
1361 : * table_tuple_fetch_row_version()) should not error out if called with that
1362 : * tid.
1363 : *
1364 : * `scan` needs to have been started via table_beginscan().
1365 : */
1366 : static inline bool
1367 252 : table_tuple_tid_valid(TableScanDesc scan, ItemPointer tid)
1368 : {
1369 252 : return scan->rs_rd->rd_tableam->tuple_tid_valid(scan, tid);
1370 : }
1371 :
1372 : /*
1373 : * Return the latest version of the tuple at `tid`, by updating `tid` to
1374 : * point at the newest version.
1375 : */
1376 : extern void table_tuple_get_latest_tid(TableScanDesc scan, ItemPointer tid);
1377 :
1378 : /*
1379 : * Return true iff tuple in slot satisfies the snapshot.
1380 : *
1381 : * This assumes the slot's tuple is valid, and of the appropriate type for the
1382 : * AM.
1383 : *
1384 : * Some AMs might modify the data underlying the tuple as a side-effect. If so
1385 : * they ought to mark the relevant buffer dirty.
1386 : */
1387 : static inline bool
1388 766933 : table_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot,
1389 : Snapshot snapshot)
1390 : {
1391 766933 : return rel->rd_tableam->tuple_satisfies_snapshot(rel, slot, snapshot);
1392 : }
1393 :
1394 : /*
1395 : * Determine which index tuples are safe to delete based on their table TID.
1396 : *
1397 : * Determines which entries from index AM caller's TM_IndexDeleteOp state
1398 : * point to vacuumable table tuples. Entries that are found by tableam to be
1399 : * vacuumable are naturally safe for index AM to delete, and so get directly
1400 : * marked as deletable. See comments above TM_IndexDelete and comments above
1401 : * TM_IndexDeleteOp for full details.
1402 : *
1403 : * Returns a snapshotConflictHorizon transaction ID that caller places in
1404 : * its index deletion WAL record. This might be used during subsequent REDO
1405 : * of the WAL record when in Hot Standby mode -- a recovery conflict for the
1406 : * index deletion operation might be required on the standby.
1407 : */
1408 : static inline TransactionId
1409 8330 : table_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
1410 : {
1411 8330 : return rel->rd_tableam->index_delete_tuples(rel, delstate);
1412 : }
1413 :
1414 :
1415 : /* ----------------------------------------------------------------------------
1416 : * Functions for manipulations of physical tuples.
1417 : * ----------------------------------------------------------------------------
1418 : */
1419 :
1420 : /*
1421 : * Insert a tuple from a slot into table AM routine.
1422 : *
1423 : * The options bitmask allows the caller to specify options that may change the
1424 : * behaviour of the AM. The AM will ignore options that it does not support.
1425 : *
1426 : * If the TABLE_INSERT_SKIP_FSM option is specified, AMs are free to not reuse
1427 : * free space in the relation. This can save some cycles when we know the
1428 : * relation is new and doesn't contain useful amounts of free space.
1429 : * TABLE_INSERT_SKIP_FSM is commonly passed directly to
1430 : * RelationGetBufferForTuple. See that method for more information.
1431 : *
1432 : * TABLE_INSERT_FROZEN should only be specified for inserts into
1433 : * relation storage created during the current subtransaction and when
1434 : * there are no prior snapshots or pre-existing portals open.
1435 : * This causes rows to be frozen, which is an MVCC violation and
1436 : * requires explicit options chosen by user.
1437 : *
1438 : * TABLE_INSERT_NO_LOGICAL force-disables the emitting of logical decoding
1439 : * information for the tuple. This should solely be used during table rewrites
1440 : * where RelationIsLogicallyLogged(relation) is not yet accurate for the new
1441 : * relation.
1442 : *
1443 : * Note that most of these options will be applied when inserting into the
1444 : * heap's TOAST table, too, if the tuple requires any out-of-line data.
1445 : *
1446 : * The BulkInsertState object (if any; bistate can be NULL for default
1447 : * behavior) is also just passed through to RelationGetBufferForTuple. If
1448 : * `bistate` is provided, table_finish_bulk_insert() needs to be called.
1449 : *
1450 : * On return the slot's tts_tid and tts_tableOid are updated to reflect the
1451 : * insertion. But note that any toasting of fields within the slot is NOT
1452 : * reflected in the slots contents.
1453 : */
1454 : static inline void
1455 10318168 : table_tuple_insert(Relation rel, TupleTableSlot *slot, CommandId cid,
1456 : uint32 options, BulkInsertStateData *bistate)
1457 : {
1458 10318168 : rel->rd_tableam->tuple_insert(rel, slot, cid, options,
1459 : bistate);
1460 10318148 : }
1461 :
1462 : /*
1463 : * Perform a "speculative insertion". These can be backed out afterwards
1464 : * without aborting the whole transaction. Other sessions can wait for the
1465 : * speculative insertion to be confirmed, turning it into a regular tuple, or
1466 : * aborted, as if it never existed. Speculatively inserted tuples behave as
1467 : * "value locks" of short duration, used to implement INSERT .. ON CONFLICT.
1468 : *
1469 : * A transaction having performed a speculative insertion has to either abort,
1470 : * or finish the speculative insertion with
1471 : * table_tuple_complete_speculative(succeeded = ...).
1472 : */
1473 : static inline void
1474 2230 : table_tuple_insert_speculative(Relation rel, TupleTableSlot *slot,
1475 : CommandId cid, uint32 options,
1476 : BulkInsertStateData *bistate,
1477 : uint32 specToken)
1478 : {
1479 2230 : rel->rd_tableam->tuple_insert_speculative(rel, slot, cid, options,
1480 : bistate, specToken);
1481 2230 : }
1482 :
1483 : /*
1484 : * Complete "speculative insertion" started in the same transaction. If
1485 : * succeeded is true, the tuple is fully inserted, if false, it's removed.
1486 : */
1487 : static inline void
1488 2226 : table_tuple_complete_speculative(Relation rel, TupleTableSlot *slot,
1489 : uint32 specToken, bool succeeded)
1490 : {
1491 2226 : rel->rd_tableam->tuple_complete_speculative(rel, slot, specToken,
1492 : succeeded);
1493 2226 : }
1494 :
1495 : /*
1496 : * Insert multiple tuples into a table.
1497 : *
1498 : * This is like table_tuple_insert(), but inserts multiple tuples in one
1499 : * operation. That's often faster than calling table_tuple_insert() in a loop,
1500 : * because e.g. the AM can reduce WAL logging and page locking overhead.
1501 : *
1502 : * Except for taking `nslots` tuples as input, and an array of TupleTableSlots
1503 : * in `slots`, the parameters for table_multi_insert() are the same as for
1504 : * table_tuple_insert().
1505 : *
1506 : * Note: this leaks memory into the current memory context. You can create a
1507 : * temporary context before calling this, if that's a problem.
1508 : */
1509 : static inline void
1510 1467 : table_multi_insert(Relation rel, TupleTableSlot **slots, int nslots,
1511 : CommandId cid, uint32 options, BulkInsertStateData *bistate)
1512 : {
1513 1467 : rel->rd_tableam->multi_insert(rel, slots, nslots,
1514 : cid, options, bistate);
1515 1467 : }
1516 :
1517 : /*
1518 : * Delete a tuple.
1519 : *
1520 : * NB: do not call this directly unless prepared to deal with
1521 : * concurrent-update conditions. Use simple_table_tuple_delete instead.
1522 : *
1523 : * Input parameters:
1524 : * rel - table to be modified (caller must hold suitable lock)
1525 : * tid - TID of tuple to be deleted
1526 : * cid - delete command ID (used for visibility test, and stored into
1527 : * cmax if successful)
1528 : * options - bitmask of options. Supported values:
1529 : * TABLE_DELETE_CHANGING_PARTITION: the tuple is being moved to another
1530 : * partition table due to an update of the partition key.
1531 : * crosscheck - if not InvalidSnapshot, also check tuple against this
1532 : * wait - true if should wait for any conflicting update to commit/abort
1533 : *
1534 : * Output parameters:
1535 : * tmfd - filled in failure cases (see below)
1536 : *
1537 : * Normal, successful return value is TM_Ok, which means we did actually
1538 : * delete it. Failure return codes are TM_SelfModified, TM_Updated, and
1539 : * TM_BeingModified (the last only possible if wait == false).
1540 : *
1541 : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
1542 : * t_xmax, and, if possible, t_cmax. See comments for struct
1543 : * TM_FailureData for additional info.
1544 : */
1545 : static inline TM_Result
1546 1061829 : table_tuple_delete(Relation rel, ItemPointer tid, CommandId cid,
1547 : uint32 options, Snapshot snapshot, Snapshot crosscheck,
1548 : bool wait, TM_FailureData *tmfd)
1549 : {
1550 1061829 : return rel->rd_tableam->tuple_delete(rel, tid, cid, options,
1551 : snapshot, crosscheck,
1552 : wait, tmfd);
1553 : }
1554 :
1555 : /*
1556 : * Update a tuple.
1557 : *
1558 : * NB: do not call this directly unless you are prepared to deal with
1559 : * concurrent-update conditions. Use simple_table_tuple_update instead.
1560 : *
1561 : * Input parameters:
1562 : * rel - table to be modified (caller must hold suitable lock)
1563 : * otid - TID of old tuple to be replaced
1564 : * cid - update command ID (used for visibility test, and stored into
1565 : * cmax/cmin if successful)
1566 : * options - bitmask of options. No values are currently recognized.
1567 : * crosscheck - if not InvalidSnapshot, also check old tuple against this
1568 : * options - These allow the caller to specify options that may change the
1569 : * behavior of the AM. The AM will ignore options that it does not support.
1570 : * TABLE_UPDATE_WAIT -- set if should wait for any conflicting update to
1571 : * commit/abort
1572 : * TABLE_UPDATE_NO_LOGICAL -- force-disables the emitting of logical
1573 : * decoding information for the tuple.
1574 : *
1575 : * Output parameters:
1576 : * slot - newly constructed tuple data to store
1577 : * tmfd - filled in failure cases (see below)
1578 : * lockmode - filled with lock mode acquired on tuple
1579 : * update_indexes - in success cases this is set if new index entries
1580 : * are required for this tuple; see TU_UpdateIndexes
1581 : *
1582 : * Normal, successful return value is TM_Ok, which means we did actually
1583 : * update it. Failure return codes are TM_SelfModified, TM_Updated, and
1584 : * TM_BeingModified (the last only possible if wait == false).
1585 : *
1586 : * On success, the slot's tts_tid and tts_tableOid are updated to match the new
1587 : * stored tuple; in particular, slot->tts_tid is set to the TID where the
1588 : * new tuple was inserted, and its HEAP_ONLY_TUPLE flag is set iff a HOT
1589 : * update was done. However, any TOAST changes in the new tuple's
1590 : * data are not reflected into *newtup.
1591 : *
1592 : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
1593 : * t_xmax, and, if possible, t_cmax. See comments for struct TM_FailureData
1594 : * for additional info.
1595 : */
1596 : static inline TM_Result
1597 2245326 : table_tuple_update(Relation rel, ItemPointer otid, TupleTableSlot *slot,
1598 : CommandId cid, uint32 options,
1599 : Snapshot snapshot, Snapshot crosscheck,
1600 : bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode,
1601 : TU_UpdateIndexes *update_indexes)
1602 : {
1603 2245326 : return rel->rd_tableam->tuple_update(rel, otid, slot,
1604 : cid, options, snapshot, crosscheck,
1605 : wait, tmfd,
1606 : lockmode, update_indexes);
1607 : }
1608 :
1609 : /*
1610 : * Lock a tuple in the specified mode.
1611 : *
1612 : * Input parameters:
1613 : * rel: relation containing tuple (caller must hold suitable lock)
1614 : * tid: TID of tuple to lock (updated if an update chain was followed)
1615 : * snapshot: snapshot to use for visibility determinations
1616 : * cid: current command ID (used for visibility test, and stored into
1617 : * tuple's cmax if lock is successful)
1618 : * mode: lock mode desired
1619 : * wait_policy: what to do if tuple lock is not available
1620 : * flags:
1621 : * If TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS, follow the update chain to
1622 : * also lock descendant tuples if lock modes don't conflict.
1623 : * If TUPLE_LOCK_FLAG_FIND_LAST_VERSION, follow the update chain and lock
1624 : * latest version.
1625 : *
1626 : * Output parameters:
1627 : * *slot: contains the target tuple
1628 : * *tmfd: filled in failure cases (see below)
1629 : *
1630 : * Function result may be:
1631 : * TM_Ok: lock was successfully acquired
1632 : * TM_Invisible: lock failed because tuple was never visible to us
1633 : * TM_SelfModified: lock failed because tuple updated by self
1634 : * TM_Updated: lock failed because tuple updated by other xact
1635 : * TM_Deleted: lock failed because tuple deleted by other xact
1636 : * TM_WouldBlock: lock couldn't be acquired and wait_policy is skip
1637 : *
1638 : * In the failure cases other than TM_Invisible and TM_Deleted, the routine
1639 : * fills *tmfd with the tuple's t_ctid, t_xmax, and, if possible, t_cmax.
1640 : * Additionally, in both success and failure cases, tmfd->traversed is set if
1641 : * an update chain was followed. See comments for struct TM_FailureData for
1642 : * additional info.
1643 : */
1644 : static inline TM_Result
1645 570288 : table_tuple_lock(Relation rel, ItemPointer tid, Snapshot snapshot,
1646 : TupleTableSlot *slot, CommandId cid, LockTupleMode mode,
1647 : LockWaitPolicy wait_policy, uint8 flags,
1648 : TM_FailureData *tmfd)
1649 : {
1650 570288 : return rel->rd_tableam->tuple_lock(rel, tid, snapshot, slot,
1651 : cid, mode, wait_policy,
1652 : flags, tmfd);
1653 : }
1654 :
1655 : /*
1656 : * Perform operations necessary to complete insertions made via
1657 : * tuple_insert and multi_insert with a BulkInsertState specified.
1658 : */
1659 : static inline void
1660 3166 : table_finish_bulk_insert(Relation rel, uint32 options)
1661 : {
1662 : /* optional callback */
1663 3166 : if (rel->rd_tableam && rel->rd_tableam->finish_bulk_insert)
1664 0 : rel->rd_tableam->finish_bulk_insert(rel, options);
1665 3166 : }
1666 :
1667 :
1668 : /* ------------------------------------------------------------------------
1669 : * DDL related functionality.
1670 : * ------------------------------------------------------------------------
1671 : */
1672 :
1673 : /*
1674 : * Create storage for `rel` in `newrlocator`, with persistence set to
1675 : * `persistence`.
1676 : *
1677 : * This is used both during relation creation and various DDL operations to
1678 : * create new rel storage that can be filled from scratch. When creating
1679 : * new storage for an existing relfilelocator, this should be called before the
1680 : * relcache entry has been updated.
1681 : *
1682 : * *freezeXid, *minmulti are set to the xid / multixact horizon for the table
1683 : * that pg_class.{relfrozenxid, relminmxid} have to be set to.
1684 : */
1685 : static inline void
1686 43296 : table_relation_set_new_filelocator(Relation rel,
1687 : const RelFileLocator *newrlocator,
1688 : char persistence,
1689 : TransactionId *freezeXid,
1690 : MultiXactId *minmulti)
1691 : {
1692 43296 : rel->rd_tableam->relation_set_new_filelocator(rel, newrlocator,
1693 : persistence, freezeXid,
1694 : minmulti);
1695 43296 : }
1696 :
1697 : /*
1698 : * Remove all table contents from `rel`, in a non-transactional manner.
1699 : * Non-transactional meaning that there's no need to support rollbacks. This
1700 : * commonly only is used to perform truncations for relation storage created in
1701 : * the current transaction.
1702 : */
1703 : static inline void
1704 398 : table_relation_nontransactional_truncate(Relation rel)
1705 : {
1706 398 : rel->rd_tableam->relation_nontransactional_truncate(rel);
1707 398 : }
1708 :
1709 : /*
1710 : * Copy data from `rel` into the new relfilelocator `newrlocator`. The new
1711 : * relfilelocator may not have storage associated before this function is
1712 : * called. This is only supposed to be used for low level operations like
1713 : * changing a relation's tablespace.
1714 : */
1715 : static inline void
1716 59 : table_relation_copy_data(Relation rel, const RelFileLocator *newrlocator)
1717 : {
1718 59 : rel->rd_tableam->relation_copy_data(rel, newrlocator);
1719 59 : }
1720 :
1721 : /*
1722 : * Copy data from `OldTable` into `NewTable`, as part of a CLUSTER or VACUUM
1723 : * FULL.
1724 : *
1725 : * Additional Input parameters:
1726 : * - use_sort - if true, the table contents are sorted appropriate for
1727 : * `OldIndex`; if false and OldIndex is not InvalidOid, the data is copied
1728 : * in that index's order; if false and OldIndex is InvalidOid, no sorting is
1729 : * performed
1730 : * - OldIndex - see use_sort
1731 : * - OldestXmin - computed by vacuum_get_cutoffs(), even when
1732 : * not needed for the relation's AM
1733 : * - *xid_cutoff - ditto
1734 : * - *multi_cutoff - ditto
1735 : * - snapshot - if != NULL, ignore data changes done by transactions that this
1736 : * (MVCC) snapshot considers still in-progress or in the future.
1737 : *
1738 : * Output parameters:
1739 : * - *xid_cutoff - rel's new relfrozenxid value, may be invalid
1740 : * - *multi_cutoff - rel's new relminmxid value, may be invalid
1741 : * - *tups_vacuumed - stats, for logging, if appropriate for AM
1742 : * - *tups_recently_dead - stats, for logging, if appropriate for AM
1743 : */
1744 : static inline void
1745 391 : table_relation_copy_for_cluster(Relation OldTable, Relation NewTable,
1746 : Relation OldIndex,
1747 : bool use_sort,
1748 : TransactionId OldestXmin,
1749 : Snapshot snapshot,
1750 : TransactionId *xid_cutoff,
1751 : MultiXactId *multi_cutoff,
1752 : double *num_tuples,
1753 : double *tups_vacuumed,
1754 : double *tups_recently_dead)
1755 : {
1756 391 : OldTable->rd_tableam->relation_copy_for_cluster(OldTable, NewTable, OldIndex,
1757 : use_sort, OldestXmin,
1758 : snapshot,
1759 : xid_cutoff, multi_cutoff,
1760 : num_tuples, tups_vacuumed,
1761 : tups_recently_dead);
1762 391 : }
1763 :
1764 : /*
1765 : * Perform VACUUM on the relation. The VACUUM can be triggered by a user or by
1766 : * autovacuum. The specific actions performed by the AM will depend heavily on
1767 : * the individual AM.
1768 : *
1769 : * On entry a transaction needs to already been established, and the
1770 : * table is locked with a ShareUpdateExclusive lock.
1771 : *
1772 : * Note that neither VACUUM FULL (and CLUSTER), nor ANALYZE go through this
1773 : * routine, even if (for ANALYZE) it is part of the same VACUUM command.
1774 : */
1775 : static inline void
1776 116482 : table_relation_vacuum(Relation rel, const VacuumParams *params,
1777 : BufferAccessStrategy bstrategy)
1778 : {
1779 116482 : rel->rd_tableam->relation_vacuum(rel, params, bstrategy);
1780 116482 : }
1781 :
1782 : /*
1783 : * Prepare to analyze the next block in the read stream. The scan needs to
1784 : * have been started with table_beginscan_analyze(). Note that this routine
1785 : * might acquire resources like locks that are held until
1786 : * table_scan_analyze_next_tuple() returns false.
1787 : *
1788 : * Returns false if block is unsuitable for sampling, true otherwise.
1789 : */
1790 : static inline bool
1791 90494 : table_scan_analyze_next_block(TableScanDesc scan, ReadStream *stream)
1792 : {
1793 90494 : return scan->rs_rd->rd_tableam->scan_analyze_next_block(scan, stream);
1794 : }
1795 :
1796 : /*
1797 : * Iterate over tuples in the block selected with
1798 : * table_scan_analyze_next_block() (which needs to have returned true, and
1799 : * this routine may not have returned false for the same block before). If a
1800 : * tuple that's suitable for sampling is found, true is returned and a tuple
1801 : * is stored in `slot`.
1802 : *
1803 : * *liverows and *deadrows are incremented according to the encountered
1804 : * tuples.
1805 : */
1806 : static inline bool
1807 7120880 : table_scan_analyze_next_tuple(TableScanDesc scan,
1808 : double *liverows, double *deadrows,
1809 : TupleTableSlot *slot)
1810 : {
1811 7120880 : return scan->rs_rd->rd_tableam->scan_analyze_next_tuple(scan,
1812 : liverows, deadrows,
1813 : slot);
1814 : }
1815 :
1816 : /*
1817 : * table_index_build_scan - scan the table to find tuples to be indexed
1818 : *
1819 : * This is called back from an access-method-specific index build procedure
1820 : * after the AM has done whatever setup it needs. The parent table relation
1821 : * is scanned to find tuples that should be entered into the index. Each
1822 : * such tuple is passed to the AM's callback routine, which does the right
1823 : * things to add it to the new index. After we return, the AM's index
1824 : * build procedure does whatever cleanup it needs.
1825 : *
1826 : * The total count of live tuples is returned. This is for updating pg_class
1827 : * statistics. (It's annoying not to be able to do that here, but we want to
1828 : * merge that update with others; see index_update_stats.) Note that the
1829 : * index AM itself must keep track of the number of index tuples; we don't do
1830 : * so here because the AM might reject some of the tuples for its own reasons,
1831 : * such as being unable to store NULLs.
1832 : *
1833 : * If 'progress', the PROGRESS_SCAN_BLOCKS_TOTAL counter is updated when
1834 : * starting the scan, and PROGRESS_SCAN_BLOCKS_DONE is updated as we go along.
1835 : *
1836 : * A side effect is to set indexInfo->ii_BrokenHotChain to true if we detect
1837 : * any potentially broken HOT chains. Currently, we set this if there are any
1838 : * RECENTLY_DEAD or DELETE_IN_PROGRESS entries in a HOT chain, without trying
1839 : * very hard to detect whether they're really incompatible with the chain tip.
1840 : * This only really makes sense for heap AM, it might need to be generalized
1841 : * for other AMs later.
1842 : */
1843 : static inline double
1844 34505 : table_index_build_scan(Relation table_rel,
1845 : Relation index_rel,
1846 : IndexInfo *index_info,
1847 : bool allow_sync,
1848 : bool progress,
1849 : IndexBuildCallback callback,
1850 : void *callback_state,
1851 : TableScanDesc scan)
1852 : {
1853 34505 : return table_rel->rd_tableam->index_build_range_scan(table_rel,
1854 : index_rel,
1855 : index_info,
1856 : allow_sync,
1857 : false,
1858 : progress,
1859 : 0,
1860 : InvalidBlockNumber,
1861 : callback,
1862 : callback_state,
1863 : scan);
1864 : }
1865 :
1866 : /*
1867 : * As table_index_build_scan(), except that instead of scanning the complete
1868 : * table, only the given number of blocks are scanned. Scan to end-of-rel can
1869 : * be signaled by passing InvalidBlockNumber as numblocks. Note that
1870 : * restricting the range to scan cannot be done when requesting syncscan.
1871 : *
1872 : * When "anyvisible" mode is requested, all tuples visible to any transaction
1873 : * are indexed and counted as live, including those inserted or deleted by
1874 : * transactions that are still in progress.
1875 : */
1876 : static inline double
1877 1492 : table_index_build_range_scan(Relation table_rel,
1878 : Relation index_rel,
1879 : IndexInfo *index_info,
1880 : bool allow_sync,
1881 : bool anyvisible,
1882 : bool progress,
1883 : BlockNumber start_blockno,
1884 : BlockNumber numblocks,
1885 : IndexBuildCallback callback,
1886 : void *callback_state,
1887 : TableScanDesc scan)
1888 : {
1889 1492 : return table_rel->rd_tableam->index_build_range_scan(table_rel,
1890 : index_rel,
1891 : index_info,
1892 : allow_sync,
1893 : anyvisible,
1894 : progress,
1895 : start_blockno,
1896 : numblocks,
1897 : callback,
1898 : callback_state,
1899 : scan);
1900 : }
1901 :
1902 : /*
1903 : * table_index_validate_scan - second table scan for concurrent index build
1904 : *
1905 : * See validate_index() for an explanation.
1906 : */
1907 : static inline void
1908 408 : table_index_validate_scan(Relation table_rel,
1909 : Relation index_rel,
1910 : IndexInfo *index_info,
1911 : Snapshot snapshot,
1912 : ValidateIndexState *state)
1913 : {
1914 408 : table_rel->rd_tableam->index_validate_scan(table_rel,
1915 : index_rel,
1916 : index_info,
1917 : snapshot,
1918 : state);
1919 408 : }
1920 :
1921 :
1922 : /* ----------------------------------------------------------------------------
1923 : * Miscellaneous functionality
1924 : * ----------------------------------------------------------------------------
1925 : */
1926 :
1927 : /*
1928 : * Return the current size of `rel` in bytes. If `forkNumber` is
1929 : * InvalidForkNumber, return the relation's overall size, otherwise the size
1930 : * for the indicated fork.
1931 : *
1932 : * Note that the overall size might not be the equivalent of the sum of sizes
1933 : * for the individual forks for some AMs, e.g. because the AMs storage does
1934 : * not neatly map onto the builtin types of forks.
1935 : */
1936 : static inline uint64
1937 1928496 : table_relation_size(Relation rel, ForkNumber forkNumber)
1938 : {
1939 1928496 : return rel->rd_tableam->relation_size(rel, forkNumber);
1940 : }
1941 :
1942 : /*
1943 : * table_relation_needs_toast_table - does this relation need a toast table?
1944 : */
1945 : static inline bool
1946 30314 : table_relation_needs_toast_table(Relation rel)
1947 : {
1948 30314 : return rel->rd_tableam->relation_needs_toast_table(rel);
1949 : }
1950 :
1951 : /*
1952 : * Return the OID of the AM that should be used to implement the TOAST table
1953 : * for this relation.
1954 : */
1955 : static inline Oid
1956 11232 : table_relation_toast_am(Relation rel)
1957 : {
1958 11232 : return rel->rd_tableam->relation_toast_am(rel);
1959 : }
1960 :
1961 : /*
1962 : * Fetch all or part of a TOAST value from a TOAST table.
1963 : *
1964 : * If this AM is never used to implement a TOAST table, then this callback
1965 : * is not needed. But, if toasted values are ever stored in a table of this
1966 : * type, then you will need this callback.
1967 : *
1968 : * toastrel is the relation in which the toasted value is stored.
1969 : *
1970 : * valueid identifies which toast value is to be fetched. For the heap,
1971 : * this corresponds to the values stored in the chunk_id column.
1972 : *
1973 : * attrsize is the total size of the toast value to be fetched.
1974 : *
1975 : * sliceoffset is the offset within the toast value of the first byte that
1976 : * should be fetched.
1977 : *
1978 : * slicelength is the number of bytes from the toast value that should be
1979 : * fetched.
1980 : *
1981 : * result is caller-allocated space into which the fetched bytes should be
1982 : * stored.
1983 : */
1984 : static inline void
1985 17744 : table_relation_fetch_toast_slice(Relation toastrel, Oid valueid,
1986 : int32 attrsize, int32 sliceoffset,
1987 : int32 slicelength, varlena *result)
1988 : {
1989 17744 : toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
1990 : attrsize,
1991 : sliceoffset, slicelength,
1992 : result);
1993 17744 : }
1994 :
1995 :
1996 : /* ----------------------------------------------------------------------------
1997 : * Planner related functionality
1998 : * ----------------------------------------------------------------------------
1999 : */
2000 :
2001 : /*
2002 : * Estimate the current size of the relation, as an AM specific workhorse for
2003 : * estimate_rel_size(). Look there for an explanation of the parameters.
2004 : */
2005 : static inline void
2006 353306 : table_relation_estimate_size(Relation rel, int32 *attr_widths,
2007 : BlockNumber *pages, double *tuples,
2008 : double *allvisfrac)
2009 : {
2010 353306 : rel->rd_tableam->relation_estimate_size(rel, attr_widths, pages, tuples,
2011 : allvisfrac);
2012 353306 : }
2013 :
2014 :
2015 : /* ----------------------------------------------------------------------------
2016 : * Executor related functionality
2017 : * ----------------------------------------------------------------------------
2018 : */
2019 :
2020 : /*
2021 : * Fetch / check / return tuples as part of a bitmap table scan. `scan` needs
2022 : * to have been started via table_beginscan_bm(). Fetch the next tuple of a
2023 : * bitmap table scan into `slot` and return true if a visible tuple was found,
2024 : * false otherwise.
2025 : *
2026 : * `recheck` is set by the table AM to indicate whether or not the tuple in
2027 : * `slot` should be rechecked. Tuples from lossy pages will always need to be
2028 : * rechecked, but some non-lossy pages' tuples may also require recheck.
2029 : *
2030 : * `lossy_pages` is incremented if the block's representation in the bitmap is
2031 : * lossy; otherwise, `exact_pages` is incremented.
2032 : */
2033 : static inline bool
2034 4142132 : table_scan_bitmap_next_tuple(TableScanDesc scan,
2035 : TupleTableSlot *slot,
2036 : bool *recheck,
2037 : uint64 *lossy_pages,
2038 : uint64 *exact_pages)
2039 : {
2040 4142132 : return scan->rs_rd->rd_tableam->scan_bitmap_next_tuple(scan,
2041 : slot,
2042 : recheck,
2043 : lossy_pages,
2044 : exact_pages);
2045 : }
2046 :
2047 : /*
2048 : * Prepare to fetch tuples from the next block in a sample scan. Returns false
2049 : * if the sample scan is finished, true otherwise. `scan` needs to have been
2050 : * started via table_beginscan_sampling().
2051 : *
2052 : * This will call the TsmRoutine's NextSampleBlock() callback if necessary
2053 : * (i.e. NextSampleBlock is not NULL), or perform a sequential scan over the
2054 : * underlying relation.
2055 : */
2056 : static inline bool
2057 8587 : table_scan_sample_next_block(TableScanDesc scan,
2058 : SampleScanState *scanstate)
2059 : {
2060 8587 : return scan->rs_rd->rd_tableam->scan_sample_next_block(scan, scanstate);
2061 : }
2062 :
2063 : /*
2064 : * Fetch the next sample tuple into `slot` and return true if a visible tuple
2065 : * was found, false otherwise. table_scan_sample_next_block() needs to
2066 : * previously have selected a block (i.e. returned true), and no previous
2067 : * table_scan_sample_next_tuple() for the same block may have returned false.
2068 : *
2069 : * This will call the TsmRoutine's NextSampleTuple() callback.
2070 : */
2071 : static inline bool
2072 169182 : table_scan_sample_next_tuple(TableScanDesc scan,
2073 : SampleScanState *scanstate,
2074 : TupleTableSlot *slot)
2075 : {
2076 169182 : return scan->rs_rd->rd_tableam->scan_sample_next_tuple(scan, scanstate,
2077 : slot);
2078 : }
2079 :
2080 :
2081 : /* ----------------------------------------------------------------------------
2082 : * Functions to make modifications a bit simpler.
2083 : * ----------------------------------------------------------------------------
2084 : */
2085 :
2086 : extern void simple_table_tuple_insert(Relation rel, TupleTableSlot *slot);
2087 : extern void simple_table_tuple_delete(Relation rel, ItemPointer tid,
2088 : Snapshot snapshot);
2089 : extern void simple_table_tuple_update(Relation rel, ItemPointer otid,
2090 : TupleTableSlot *slot, Snapshot snapshot,
2091 : TU_UpdateIndexes *update_indexes);
2092 :
2093 :
2094 : /* ----------------------------------------------------------------------------
2095 : * Helper functions to implement parallel scans for block oriented AMs.
2096 : * ----------------------------------------------------------------------------
2097 : */
2098 :
2099 : extern Size table_block_parallelscan_estimate(Relation rel);
2100 : extern Size table_block_parallelscan_initialize(Relation rel,
2101 : ParallelTableScanDesc pscan);
2102 : extern void table_block_parallelscan_reinitialize(Relation rel,
2103 : ParallelTableScanDesc pscan);
2104 : extern BlockNumber table_block_parallelscan_nextpage(Relation rel,
2105 : ParallelBlockTableScanWorker pbscanwork,
2106 : ParallelBlockTableScanDesc pbscan);
2107 : extern void table_block_parallelscan_startblock_init(Relation rel,
2108 : ParallelBlockTableScanWorker pbscanwork,
2109 : ParallelBlockTableScanDesc pbscan,
2110 : BlockNumber startblock,
2111 : BlockNumber numblocks);
2112 :
2113 :
2114 : /* ----------------------------------------------------------------------------
2115 : * Helper functions to implement relation sizing for block oriented AMs.
2116 : * ----------------------------------------------------------------------------
2117 : */
2118 :
2119 : extern uint64 table_block_relation_size(Relation rel, ForkNumber forkNumber);
2120 : extern void table_block_relation_estimate_size(Relation rel,
2121 : int32 *attr_widths,
2122 : BlockNumber *pages,
2123 : double *tuples,
2124 : double *allvisfrac,
2125 : Size overhead_bytes_per_tuple,
2126 : Size usable_bytes_per_page);
2127 :
2128 : /* ----------------------------------------------------------------------------
2129 : * Functions in tableamapi.c
2130 : * ----------------------------------------------------------------------------
2131 : */
2132 :
2133 : extern const TableAmRoutine *GetTableAmRoutine(Oid amhandler);
2134 :
2135 : /* ----------------------------------------------------------------------------
2136 : * Functions in heapam_handler.c
2137 : * ----------------------------------------------------------------------------
2138 : */
2139 :
2140 : extern const TableAmRoutine *GetHeapamTableAmRoutine(void);
2141 :
2142 : #endif /* TABLEAM_H */
|