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