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