Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * tableam.h
4 : * POSTGRES table access method definitions.
5 : *
6 : *
7 : * Portions Copyright (c) 1996-2025, 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 : struct BulkInsertStateData;
37 : struct IndexInfo;
38 : struct SampleScanState;
39 : struct VacuumParams;
40 : struct ValidateIndexState;
41 :
42 : /*
43 : * Bitmask values for the flags argument to the scan_begin callback.
44 : */
45 : typedef enum ScanOptions
46 : {
47 : /* one of SO_TYPE_* may be specified */
48 : SO_TYPE_SEQSCAN = 1 << 0,
49 : SO_TYPE_BITMAPSCAN = 1 << 1,
50 : SO_TYPE_SAMPLESCAN = 1 << 2,
51 : SO_TYPE_TIDSCAN = 1 << 3,
52 : SO_TYPE_TIDRANGESCAN = 1 << 4,
53 : SO_TYPE_ANALYZE = 1 << 5,
54 :
55 : /* several of SO_ALLOW_* may be specified */
56 : /* allow or disallow use of access strategy */
57 : SO_ALLOW_STRAT = 1 << 6,
58 : /* report location to syncscan logic? */
59 : SO_ALLOW_SYNC = 1 << 7,
60 : /* verify visibility page-at-a-time? */
61 : SO_ALLOW_PAGEMODE = 1 << 8,
62 :
63 : /* unregister snapshot at scan end? */
64 : SO_TEMP_SNAPSHOT = 1 << 9,
65 :
66 : /*
67 : * At the discretion of the table AM, bitmap table scans may be able to
68 : * skip fetching a block from the table if none of the table data is
69 : * needed. If table data may be needed, set SO_NEED_TUPLES.
70 : */
71 : SO_NEED_TUPLES = 1 << 10,
72 : } ScanOptions;
73 :
74 : /*
75 : * Result codes for table_{update,delete,lock_tuple}, and for visibility
76 : * routines inside table AMs.
77 : */
78 : typedef enum TM_Result
79 : {
80 : /*
81 : * Signals that the action succeeded (i.e. update/delete performed, lock
82 : * was acquired)
83 : */
84 : TM_Ok,
85 :
86 : /* The affected tuple wasn't visible to the relevant snapshot */
87 : TM_Invisible,
88 :
89 : /* The affected tuple was already modified by the calling backend */
90 : TM_SelfModified,
91 :
92 : /*
93 : * The affected tuple was updated by another transaction. This includes
94 : * the case where tuple was moved to another partition.
95 : */
96 : TM_Updated,
97 :
98 : /* The affected tuple was deleted by another transaction */
99 : TM_Deleted,
100 :
101 : /*
102 : * The affected tuple is currently being modified by another session. This
103 : * will only be returned if table_(update/delete/lock_tuple) are
104 : * instructed not to wait.
105 : */
106 : TM_BeingModified,
107 :
108 : /* lock couldn't be acquired, action skipped. Only used by lock_tuple */
109 : TM_WouldBlock,
110 : } TM_Result;
111 :
112 : /*
113 : * Result codes for table_update(..., update_indexes*..).
114 : * Used to determine which indexes to update.
115 : */
116 : typedef enum TU_UpdateIndexes
117 : {
118 : /* No indexed columns were updated (incl. TID addressing of tuple) */
119 : TU_None,
120 :
121 : /* A non-summarizing indexed column was updated, or the TID has changed */
122 : TU_All,
123 :
124 : /* Only summarized columns were updated, TID is unchanged */
125 : TU_Summarizing,
126 : } TU_UpdateIndexes;
127 :
128 : /*
129 : * When table_tuple_update, table_tuple_delete, or table_tuple_lock fail
130 : * because the target tuple is already outdated, they fill in this struct to
131 : * provide information to the caller about what happened.
132 : *
133 : * ctid is the target's ctid link: it is the same as the target's TID if the
134 : * target was deleted, or the location of the replacement tuple if the target
135 : * was updated.
136 : *
137 : * xmax is the outdating transaction's XID. If the caller wants to visit the
138 : * replacement tuple, it must check that this matches before believing the
139 : * replacement is really a match.
140 : *
141 : * cmax is the outdating command's CID, but only when the failure code is
142 : * TM_SelfModified (i.e., something in the current transaction outdated the
143 : * tuple); otherwise cmax is zero. (We make this restriction because
144 : * HeapTupleHeaderGetCmax doesn't work for tuples outdated in other
145 : * transactions.)
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, struct 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, struct 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 : struct 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 : struct 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, struct 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 : struct 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 : struct 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 : struct IndexInfo *index_info,
708 : Snapshot snapshot,
709 : struct 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 : * Prepare to fetch / check / return tuples from `blockno` as part of a
783 : * bitmap table scan. `scan` was started via table_beginscan_bm(). Return
784 : * false if the bitmap is exhausted and true otherwise.
785 : *
786 : * This will typically read and pin the target block, and do the necessary
787 : * work to allow scan_bitmap_next_tuple() to return tuples (e.g. it might
788 : * make sense to perform tuple visibility checks at this time).
789 : *
790 : * `lossy_pages` and `exact_pages` are EXPLAIN counters that can be
791 : * incremented by the table AM to indicate whether or not the block's
792 : * representation in the bitmap is lossy.
793 : *
794 : * `recheck` is set by the table AM to indicate whether or not the tuples
795 : * from this block should be rechecked. Tuples from lossy pages will
796 : * always need to be rechecked, but some non-lossy pages' tuples may also
797 : * require recheck.
798 : *
799 : * `blockno` is the current block and is set by the table AM. The table AM
800 : * is responsible for advancing the main iterator, but the bitmap table
801 : * scan code still advances the prefetch iterator. `blockno` is used by
802 : * bitmap table scan code to validate that the prefetch block stays ahead
803 : * of the current block.
804 : *
805 : * XXX: Currently this may only be implemented if the AM uses md.c as its
806 : * storage manager, and uses ItemPointer->ip_blkid in a manner that maps
807 : * blockids directly to the underlying storage. nodeBitmapHeapscan.c
808 : * performs prefetching directly using that interface. This probably
809 : * needs to be rectified at a later point.
810 : *
811 : * XXX: Currently this may only be implemented if the AM uses the
812 : * visibilitymap, as nodeBitmapHeapscan.c unconditionally accesses it to
813 : * perform prefetching. This probably needs to be rectified at a later
814 : * point.
815 : *
816 : * Optional callback, but either both scan_bitmap_next_block and
817 : * scan_bitmap_next_tuple need to exist, or neither.
818 : */
819 : bool (*scan_bitmap_next_block) (TableScanDesc scan,
820 : BlockNumber *blockno,
821 : bool *recheck,
822 : uint64 *lossy_pages,
823 : uint64 *exact_pages);
824 :
825 : /*
826 : * Fetch the next tuple of a bitmap table scan into `slot` and return true
827 : * if a visible tuple was found, false otherwise.
828 : *
829 : * Optional callback, but either both scan_bitmap_next_block and
830 : * scan_bitmap_next_tuple need to exist, or neither.
831 : */
832 : bool (*scan_bitmap_next_tuple) (TableScanDesc scan,
833 : TupleTableSlot *slot);
834 :
835 : /*
836 : * Prepare to fetch tuples from the next block in a sample scan. Return
837 : * false if the sample scan is finished, true otherwise. `scan` was
838 : * started via table_beginscan_sampling().
839 : *
840 : * Typically this will first determine the target block by calling the
841 : * TsmRoutine's NextSampleBlock() callback if not NULL, or alternatively
842 : * perform a sequential scan over all blocks. The determined block is
843 : * then typically read and pinned.
844 : *
845 : * As the TsmRoutine interface is block based, a block needs to be passed
846 : * to NextSampleBlock(). If that's not appropriate for an AM, it
847 : * internally needs to perform mapping between the internal and a block
848 : * based representation.
849 : *
850 : * Note that it's not acceptable to hold deadlock prone resources such as
851 : * lwlocks until scan_sample_next_tuple() has exhausted the tuples on the
852 : * block - the tuple is likely to be returned to an upper query node, and
853 : * the next call could be off a long while. Holding buffer pins and such
854 : * is obviously OK.
855 : *
856 : * Currently it is required to implement this interface, as there's no
857 : * alternative way (contrary e.g. to bitmap scans) to implement sample
858 : * scans. If infeasible to implement, the AM may raise an error.
859 : */
860 : bool (*scan_sample_next_block) (TableScanDesc scan,
861 : struct SampleScanState *scanstate);
862 :
863 : /*
864 : * This callback, only called after scan_sample_next_block has returned
865 : * true, should determine the next tuple to be returned from the selected
866 : * block using the TsmRoutine's NextSampleTuple() callback.
867 : *
868 : * The callback needs to perform visibility checks, and only return
869 : * visible tuples. That obviously can mean calling NextSampleTuple()
870 : * multiple times.
871 : *
872 : * The TsmRoutine interface assumes that there's a maximum offset on a
873 : * given page, so if that doesn't apply to an AM, it needs to emulate that
874 : * assumption somehow.
875 : */
876 : bool (*scan_sample_next_tuple) (TableScanDesc scan,
877 : struct SampleScanState *scanstate,
878 : TupleTableSlot *slot);
879 :
880 : } TableAmRoutine;
881 :
882 :
883 : /* ----------------------------------------------------------------------------
884 : * Slot functions.
885 : * ----------------------------------------------------------------------------
886 : */
887 :
888 : /*
889 : * Returns slot callbacks suitable for holding tuples of the appropriate type
890 : * for the relation. Works for tables, views, foreign tables and partitioned
891 : * tables.
892 : */
893 : extern const TupleTableSlotOps *table_slot_callbacks(Relation relation);
894 :
895 : /*
896 : * Returns slot using the callbacks returned by table_slot_callbacks(), and
897 : * registers it on *reglist.
898 : */
899 : extern TupleTableSlot *table_slot_create(Relation relation, List **reglist);
900 :
901 :
902 : /* ----------------------------------------------------------------------------
903 : * Table scan functions.
904 : * ----------------------------------------------------------------------------
905 : */
906 :
907 : /*
908 : * Start a scan of `rel`. Returned tuples pass a visibility test of
909 : * `snapshot`, and if nkeys != 0, the results are filtered by those scan keys.
910 : */
911 : static inline TableScanDesc
912 183480 : table_beginscan(Relation rel, Snapshot snapshot,
913 : int nkeys, struct ScanKeyData *key)
914 : {
915 183480 : uint32 flags = SO_TYPE_SEQSCAN |
916 : SO_ALLOW_STRAT | SO_ALLOW_SYNC | SO_ALLOW_PAGEMODE;
917 :
918 183480 : return rel->rd_tableam->scan_begin(rel, snapshot, nkeys, key, NULL, flags);
919 : }
920 :
921 : /*
922 : * Like table_beginscan(), but for scanning catalog. It'll automatically use a
923 : * snapshot appropriate for scanning catalog relations.
924 : */
925 : extern TableScanDesc table_beginscan_catalog(Relation relation, int nkeys,
926 : struct ScanKeyData *key);
927 :
928 : /*
929 : * Like table_beginscan(), but table_beginscan_strat() offers an extended API
930 : * that lets the caller control whether a nondefault buffer access strategy
931 : * can be used, and whether syncscan can be chosen (possibly resulting in the
932 : * scan not starting from block zero). Both of these default to true with
933 : * plain table_beginscan.
934 : */
935 : static inline TableScanDesc
936 396582 : table_beginscan_strat(Relation rel, Snapshot snapshot,
937 : int nkeys, struct ScanKeyData *key,
938 : bool allow_strat, bool allow_sync)
939 : {
940 396582 : uint32 flags = SO_TYPE_SEQSCAN | SO_ALLOW_PAGEMODE;
941 :
942 396582 : if (allow_strat)
943 396582 : flags |= SO_ALLOW_STRAT;
944 396582 : if (allow_sync)
945 50612 : flags |= SO_ALLOW_SYNC;
946 :
947 396582 : return rel->rd_tableam->scan_begin(rel, snapshot, nkeys, key, NULL, flags);
948 : }
949 :
950 : /*
951 : * table_beginscan_bm is an alternative entry point for setting up a
952 : * TableScanDesc for a bitmap heap scan. Although that scan technology is
953 : * really quite unlike a standard seqscan, there is just enough commonality to
954 : * make it worth using the same data structure.
955 : */
956 : static inline TableScanDesc
957 15470 : table_beginscan_bm(Relation rel, Snapshot snapshot,
958 : int nkeys, struct ScanKeyData *key, bool need_tuple)
959 : {
960 15470 : uint32 flags = SO_TYPE_BITMAPSCAN | SO_ALLOW_PAGEMODE;
961 :
962 15470 : if (need_tuple)
963 12588 : flags |= SO_NEED_TUPLES;
964 :
965 15470 : return rel->rd_tableam->scan_begin(rel, snapshot, nkeys, key,
966 : NULL, flags);
967 : }
968 :
969 : /*
970 : * table_beginscan_sampling is an alternative entry point for setting up a
971 : * TableScanDesc for a TABLESAMPLE scan. As with bitmap scans, it's worth
972 : * using the same data structure although the behavior is rather different.
973 : * In addition to the options offered by table_beginscan_strat, this call
974 : * also allows control of whether page-mode visibility checking is used.
975 : */
976 : static inline TableScanDesc
977 146 : table_beginscan_sampling(Relation rel, Snapshot snapshot,
978 : int nkeys, struct ScanKeyData *key,
979 : bool allow_strat, bool allow_sync,
980 : bool allow_pagemode)
981 : {
982 146 : uint32 flags = SO_TYPE_SAMPLESCAN;
983 :
984 146 : if (allow_strat)
985 134 : flags |= SO_ALLOW_STRAT;
986 146 : if (allow_sync)
987 66 : flags |= SO_ALLOW_SYNC;
988 146 : if (allow_pagemode)
989 122 : flags |= SO_ALLOW_PAGEMODE;
990 :
991 146 : return rel->rd_tableam->scan_begin(rel, snapshot, nkeys, key, NULL, flags);
992 : }
993 :
994 : /*
995 : * table_beginscan_tid is an alternative entry point for setting up a
996 : * TableScanDesc for a Tid scan. As with bitmap scans, it's worth using
997 : * the same data structure although the behavior is rather different.
998 : */
999 : static inline TableScanDesc
1000 730 : table_beginscan_tid(Relation rel, Snapshot snapshot)
1001 : {
1002 730 : uint32 flags = SO_TYPE_TIDSCAN;
1003 :
1004 730 : return rel->rd_tableam->scan_begin(rel, snapshot, 0, NULL, NULL, flags);
1005 : }
1006 :
1007 : /*
1008 : * table_beginscan_analyze is an alternative entry point for setting up a
1009 : * TableScanDesc for an ANALYZE scan. As with bitmap scans, it's worth using
1010 : * the same data structure although the behavior is rather different.
1011 : */
1012 : static inline TableScanDesc
1013 14858 : table_beginscan_analyze(Relation rel)
1014 : {
1015 14858 : uint32 flags = SO_TYPE_ANALYZE;
1016 :
1017 14858 : return rel->rd_tableam->scan_begin(rel, NULL, 0, NULL, NULL, flags);
1018 : }
1019 :
1020 : /*
1021 : * End relation scan.
1022 : */
1023 : static inline void
1024 676996 : table_endscan(TableScanDesc scan)
1025 : {
1026 676996 : scan->rs_rd->rd_tableam->scan_end(scan);
1027 676996 : }
1028 :
1029 : /*
1030 : * Restart a relation scan.
1031 : */
1032 : static inline void
1033 1007348 : table_rescan(TableScanDesc scan,
1034 : struct ScanKeyData *key)
1035 : {
1036 1007348 : scan->rs_rd->rd_tableam->scan_rescan(scan, key, false, false, false, false);
1037 1007348 : }
1038 :
1039 : /*
1040 : * Restart a relation scan after changing params.
1041 : *
1042 : * This call allows changing the buffer strategy, syncscan, and pagemode
1043 : * options before starting a fresh scan. Note that although the actual use of
1044 : * syncscan might change (effectively, enabling or disabling reporting), the
1045 : * previously selected startblock will be kept.
1046 : */
1047 : static inline void
1048 30 : table_rescan_set_params(TableScanDesc scan, struct ScanKeyData *key,
1049 : bool allow_strat, bool allow_sync, bool allow_pagemode)
1050 : {
1051 30 : scan->rs_rd->rd_tableam->scan_rescan(scan, key, true,
1052 : allow_strat, allow_sync,
1053 : allow_pagemode);
1054 30 : }
1055 :
1056 : /*
1057 : * Return next tuple from `scan`, store in slot.
1058 : */
1059 : static inline bool
1060 84770572 : table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
1061 : {
1062 84770572 : slot->tts_tableOid = RelationGetRelid(sscan->rs_rd);
1063 :
1064 : /* We don't expect actual scans using NoMovementScanDirection */
1065 : Assert(direction == ForwardScanDirection ||
1066 : direction == BackwardScanDirection);
1067 :
1068 : /*
1069 : * We don't expect direct calls to table_scan_getnextslot with valid
1070 : * CheckXidAlive for catalog or regular tables. See detailed comments in
1071 : * xact.c where these variables are declared.
1072 : */
1073 84770572 : if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
1074 0 : elog(ERROR, "unexpected table_scan_getnextslot call during logical decoding");
1075 :
1076 84770572 : return sscan->rs_rd->rd_tableam->scan_getnextslot(sscan, direction, slot);
1077 : }
1078 :
1079 : /* ----------------------------------------------------------------------------
1080 : * TID Range scanning related functions.
1081 : * ----------------------------------------------------------------------------
1082 : */
1083 :
1084 : /*
1085 : * table_beginscan_tidrange is the entry point for setting up a TableScanDesc
1086 : * for a TID range scan.
1087 : */
1088 : static inline TableScanDesc
1089 112 : table_beginscan_tidrange(Relation rel, Snapshot snapshot,
1090 : ItemPointer mintid,
1091 : ItemPointer maxtid)
1092 : {
1093 : TableScanDesc sscan;
1094 112 : uint32 flags = SO_TYPE_TIDRANGESCAN | SO_ALLOW_PAGEMODE;
1095 :
1096 112 : sscan = rel->rd_tableam->scan_begin(rel, snapshot, 0, NULL, NULL, flags);
1097 :
1098 : /* Set the range of TIDs to scan */
1099 112 : sscan->rs_rd->rd_tableam->scan_set_tidrange(sscan, mintid, maxtid);
1100 :
1101 112 : return sscan;
1102 : }
1103 :
1104 : /*
1105 : * table_rescan_tidrange resets the scan position and sets the minimum and
1106 : * maximum TID range to scan for a TableScanDesc created by
1107 : * table_beginscan_tidrange.
1108 : */
1109 : static inline void
1110 66 : table_rescan_tidrange(TableScanDesc sscan, ItemPointer mintid,
1111 : ItemPointer maxtid)
1112 : {
1113 : /* Ensure table_beginscan_tidrange() was used. */
1114 : Assert((sscan->rs_flags & SO_TYPE_TIDRANGESCAN) != 0);
1115 :
1116 66 : sscan->rs_rd->rd_tableam->scan_rescan(sscan, NULL, false, false, false, false);
1117 66 : sscan->rs_rd->rd_tableam->scan_set_tidrange(sscan, mintid, maxtid);
1118 66 : }
1119 :
1120 : /*
1121 : * Fetch the next tuple from `sscan` for a TID range scan created by
1122 : * table_beginscan_tidrange(). Stores the tuple in `slot` and returns true,
1123 : * or returns false if no more tuples exist in the range.
1124 : */
1125 : static inline bool
1126 5940 : table_scan_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction,
1127 : TupleTableSlot *slot)
1128 : {
1129 : /* Ensure table_beginscan_tidrange() was used. */
1130 : Assert((sscan->rs_flags & SO_TYPE_TIDRANGESCAN) != 0);
1131 :
1132 : /* We don't expect actual scans using NoMovementScanDirection */
1133 : Assert(direction == ForwardScanDirection ||
1134 : direction == BackwardScanDirection);
1135 :
1136 5940 : return sscan->rs_rd->rd_tableam->scan_getnextslot_tidrange(sscan,
1137 : direction,
1138 : slot);
1139 : }
1140 :
1141 :
1142 : /* ----------------------------------------------------------------------------
1143 : * Parallel table scan related functions.
1144 : * ----------------------------------------------------------------------------
1145 : */
1146 :
1147 : /*
1148 : * Estimate the size of shared memory needed for a parallel scan of this
1149 : * relation.
1150 : */
1151 : extern Size table_parallelscan_estimate(Relation rel, Snapshot snapshot);
1152 :
1153 : /*
1154 : * Initialize ParallelTableScanDesc for a parallel scan of this
1155 : * relation. `pscan` needs to be sized according to parallelscan_estimate()
1156 : * for the same relation. Call this just once in the leader process; then,
1157 : * individual workers attach via table_beginscan_parallel.
1158 : */
1159 : extern void table_parallelscan_initialize(Relation rel,
1160 : ParallelTableScanDesc pscan,
1161 : Snapshot snapshot);
1162 :
1163 : /*
1164 : * Begin a parallel scan. `pscan` needs to have been initialized with
1165 : * table_parallelscan_initialize(), for the same relation. The initialization
1166 : * does not need to have happened in this backend.
1167 : *
1168 : * Caller must hold a suitable lock on the relation.
1169 : */
1170 : extern TableScanDesc table_beginscan_parallel(Relation relation,
1171 : ParallelTableScanDesc pscan);
1172 :
1173 : /*
1174 : * Restart a parallel scan. Call this in the leader process. Caller is
1175 : * responsible for making sure that all workers have finished the scan
1176 : * beforehand.
1177 : */
1178 : static inline void
1179 228 : table_parallelscan_reinitialize(Relation rel, ParallelTableScanDesc pscan)
1180 : {
1181 228 : rel->rd_tableam->parallelscan_reinitialize(rel, pscan);
1182 228 : }
1183 :
1184 :
1185 : /* ----------------------------------------------------------------------------
1186 : * Index scan related functions.
1187 : * ----------------------------------------------------------------------------
1188 : */
1189 :
1190 : /*
1191 : * Prepare to fetch tuples from the relation, as needed when fetching tuples
1192 : * for an index scan.
1193 : *
1194 : * Tuples for an index scan can then be fetched via table_index_fetch_tuple().
1195 : */
1196 : static inline IndexFetchTableData *
1197 24384018 : table_index_fetch_begin(Relation rel)
1198 : {
1199 24384018 : return rel->rd_tableam->index_fetch_begin(rel);
1200 : }
1201 :
1202 : /*
1203 : * Reset index fetch. Typically this will release cross index fetch resources
1204 : * held in IndexFetchTableData.
1205 : */
1206 : static inline void
1207 19495572 : table_index_fetch_reset(struct IndexFetchTableData *scan)
1208 : {
1209 19495572 : scan->rel->rd_tableam->index_fetch_reset(scan);
1210 19495572 : }
1211 :
1212 : /*
1213 : * Release resources and deallocate index fetch.
1214 : */
1215 : static inline void
1216 24382374 : table_index_fetch_end(struct IndexFetchTableData *scan)
1217 : {
1218 24382374 : scan->rel->rd_tableam->index_fetch_end(scan);
1219 24382374 : }
1220 :
1221 : /*
1222 : * Fetches, as part of an index scan, tuple at `tid` into `slot`, after doing
1223 : * a visibility test according to `snapshot`. If a tuple was found and passed
1224 : * the visibility test, returns true, false otherwise. Note that *tid may be
1225 : * modified when we return true (see later remarks on multiple row versions
1226 : * reachable via a single index entry).
1227 : *
1228 : * *call_again needs to be false on the first call to table_index_fetch_tuple() for
1229 : * a tid. If there potentially is another tuple matching the tid, *call_again
1230 : * will be set to true, signaling that table_index_fetch_tuple() should be called
1231 : * again for the same tid.
1232 : *
1233 : * *all_dead, if all_dead is not NULL, will be set to true by
1234 : * table_index_fetch_tuple() iff it is guaranteed that no backend needs to see
1235 : * that tuple. Index AMs can use that to avoid returning that tid in future
1236 : * searches.
1237 : *
1238 : * The difference between this function and table_tuple_fetch_row_version()
1239 : * is that this function returns the currently visible version of a row if
1240 : * the AM supports storing multiple row versions reachable via a single index
1241 : * entry (like heap's HOT). Whereas table_tuple_fetch_row_version() only
1242 : * evaluates the tuple exactly at `tid`. Outside of index entry ->table tuple
1243 : * lookups, table_tuple_fetch_row_version() is what's usually needed.
1244 : */
1245 : static inline bool
1246 34429720 : table_index_fetch_tuple(struct IndexFetchTableData *scan,
1247 : ItemPointer tid,
1248 : Snapshot snapshot,
1249 : TupleTableSlot *slot,
1250 : bool *call_again, bool *all_dead)
1251 : {
1252 : /*
1253 : * We don't expect direct calls to table_index_fetch_tuple with valid
1254 : * CheckXidAlive for catalog or regular tables. See detailed comments in
1255 : * xact.c where these variables are declared.
1256 : */
1257 34429720 : if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
1258 0 : elog(ERROR, "unexpected table_index_fetch_tuple call during logical decoding");
1259 :
1260 34429720 : return scan->rel->rd_tableam->index_fetch_tuple(scan, tid, snapshot,
1261 : slot, call_again,
1262 : all_dead);
1263 : }
1264 :
1265 : /*
1266 : * This is a convenience wrapper around table_index_fetch_tuple() which
1267 : * returns whether there are table tuple items corresponding to an index
1268 : * entry. This likely is only useful to verify if there's a conflict in a
1269 : * unique index.
1270 : */
1271 : extern bool table_index_fetch_tuple_check(Relation rel,
1272 : ItemPointer tid,
1273 : Snapshot snapshot,
1274 : bool *all_dead);
1275 :
1276 :
1277 : /* ------------------------------------------------------------------------
1278 : * Functions for non-modifying operations on individual tuples
1279 : * ------------------------------------------------------------------------
1280 : */
1281 :
1282 :
1283 : /*
1284 : * Fetch tuple at `tid` into `slot`, after doing a visibility test according to
1285 : * `snapshot`. If a tuple was found and passed the visibility test, returns
1286 : * true, false otherwise.
1287 : *
1288 : * See table_index_fetch_tuple's comment about what the difference between
1289 : * these functions is. It is correct to use this function outside of index
1290 : * entry->table tuple lookups.
1291 : */
1292 : static inline bool
1293 345474 : table_tuple_fetch_row_version(Relation rel,
1294 : ItemPointer tid,
1295 : Snapshot snapshot,
1296 : TupleTableSlot *slot)
1297 : {
1298 : /*
1299 : * We don't expect direct calls to table_tuple_fetch_row_version with
1300 : * valid CheckXidAlive for catalog or regular tables. See detailed
1301 : * comments in xact.c where these variables are declared.
1302 : */
1303 345474 : if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
1304 0 : elog(ERROR, "unexpected table_tuple_fetch_row_version call during logical decoding");
1305 :
1306 345474 : return rel->rd_tableam->tuple_fetch_row_version(rel, tid, snapshot, slot);
1307 : }
1308 :
1309 : /*
1310 : * Verify that `tid` is a potentially valid tuple identifier. That doesn't
1311 : * mean that the pointed to row needs to exist or be visible, but that
1312 : * attempting to fetch the row (e.g. with table_tuple_get_latest_tid() or
1313 : * table_tuple_fetch_row_version()) should not error out if called with that
1314 : * tid.
1315 : *
1316 : * `scan` needs to have been started via table_beginscan().
1317 : */
1318 : static inline bool
1319 394 : table_tuple_tid_valid(TableScanDesc scan, ItemPointer tid)
1320 : {
1321 394 : return scan->rs_rd->rd_tableam->tuple_tid_valid(scan, tid);
1322 : }
1323 :
1324 : /*
1325 : * Return the latest version of the tuple at `tid`, by updating `tid` to
1326 : * point at the newest version.
1327 : */
1328 : extern void table_tuple_get_latest_tid(TableScanDesc scan, ItemPointer tid);
1329 :
1330 : /*
1331 : * Return true iff tuple in slot satisfies the snapshot.
1332 : *
1333 : * This assumes the slot's tuple is valid, and of the appropriate type for the
1334 : * AM.
1335 : *
1336 : * Some AMs might modify the data underlying the tuple as a side-effect. If so
1337 : * they ought to mark the relevant buffer dirty.
1338 : */
1339 : static inline bool
1340 218506 : table_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot,
1341 : Snapshot snapshot)
1342 : {
1343 218506 : return rel->rd_tableam->tuple_satisfies_snapshot(rel, slot, snapshot);
1344 : }
1345 :
1346 : /*
1347 : * Determine which index tuples are safe to delete based on their table TID.
1348 : *
1349 : * Determines which entries from index AM caller's TM_IndexDeleteOp state
1350 : * point to vacuumable table tuples. Entries that are found by tableam to be
1351 : * vacuumable are naturally safe for index AM to delete, and so get directly
1352 : * marked as deletable. See comments above TM_IndexDelete and comments above
1353 : * TM_IndexDeleteOp for full details.
1354 : *
1355 : * Returns a snapshotConflictHorizon transaction ID that caller places in
1356 : * its index deletion WAL record. This might be used during subsequent REDO
1357 : * of the WAL record when in Hot Standby mode -- a recovery conflict for the
1358 : * index deletion operation might be required on the standby.
1359 : */
1360 : static inline TransactionId
1361 10402 : table_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
1362 : {
1363 10402 : return rel->rd_tableam->index_delete_tuples(rel, delstate);
1364 : }
1365 :
1366 :
1367 : /* ----------------------------------------------------------------------------
1368 : * Functions for manipulations of physical tuples.
1369 : * ----------------------------------------------------------------------------
1370 : */
1371 :
1372 : /*
1373 : * Insert a tuple from a slot into table AM routine.
1374 : *
1375 : * The options bitmask allows the caller to specify options that may change the
1376 : * behaviour of the AM. The AM will ignore options that it does not support.
1377 : *
1378 : * If the TABLE_INSERT_SKIP_FSM option is specified, AMs are free to not reuse
1379 : * free space in the relation. This can save some cycles when we know the
1380 : * relation is new and doesn't contain useful amounts of free space.
1381 : * TABLE_INSERT_SKIP_FSM is commonly passed directly to
1382 : * RelationGetBufferForTuple. See that method for more information.
1383 : *
1384 : * TABLE_INSERT_FROZEN should only be specified for inserts into
1385 : * relation storage created during the current subtransaction and when
1386 : * there are no prior snapshots or pre-existing portals open.
1387 : * This causes rows to be frozen, which is an MVCC violation and
1388 : * requires explicit options chosen by user.
1389 : *
1390 : * TABLE_INSERT_NO_LOGICAL force-disables the emitting of logical decoding
1391 : * information for the tuple. This should solely be used during table rewrites
1392 : * where RelationIsLogicallyLogged(relation) is not yet accurate for the new
1393 : * relation.
1394 : *
1395 : * Note that most of these options will be applied when inserting into the
1396 : * heap's TOAST table, too, if the tuple requires any out-of-line data.
1397 : *
1398 : * The BulkInsertState object (if any; bistate can be NULL for default
1399 : * behavior) is also just passed through to RelationGetBufferForTuple. If
1400 : * `bistate` is provided, table_finish_bulk_insert() needs to be called.
1401 : *
1402 : * On return the slot's tts_tid and tts_tableOid are updated to reflect the
1403 : * insertion. But note that any toasting of fields within the slot is NOT
1404 : * reflected in the slots contents.
1405 : */
1406 : static inline void
1407 13863472 : table_tuple_insert(Relation rel, TupleTableSlot *slot, CommandId cid,
1408 : int options, struct BulkInsertStateData *bistate)
1409 : {
1410 13863472 : rel->rd_tableam->tuple_insert(rel, slot, cid, options,
1411 : bistate);
1412 13863434 : }
1413 :
1414 : /*
1415 : * Perform a "speculative insertion". These can be backed out afterwards
1416 : * without aborting the whole transaction. Other sessions can wait for the
1417 : * speculative insertion to be confirmed, turning it into a regular tuple, or
1418 : * aborted, as if it never existed. Speculatively inserted tuples behave as
1419 : * "value locks" of short duration, used to implement INSERT .. ON CONFLICT.
1420 : *
1421 : * A transaction having performed a speculative insertion has to either abort,
1422 : * or finish the speculative insertion with
1423 : * table_tuple_complete_speculative(succeeded = ...).
1424 : */
1425 : static inline void
1426 4128 : table_tuple_insert_speculative(Relation rel, TupleTableSlot *slot,
1427 : CommandId cid, int options,
1428 : struct BulkInsertStateData *bistate,
1429 : uint32 specToken)
1430 : {
1431 4128 : rel->rd_tableam->tuple_insert_speculative(rel, slot, cid, options,
1432 : bistate, specToken);
1433 4128 : }
1434 :
1435 : /*
1436 : * Complete "speculative insertion" started in the same transaction. If
1437 : * succeeded is true, the tuple is fully inserted, if false, it's removed.
1438 : */
1439 : static inline void
1440 4122 : table_tuple_complete_speculative(Relation rel, TupleTableSlot *slot,
1441 : uint32 specToken, bool succeeded)
1442 : {
1443 4122 : rel->rd_tableam->tuple_complete_speculative(rel, slot, specToken,
1444 : succeeded);
1445 4122 : }
1446 :
1447 : /*
1448 : * Insert multiple tuples into a table.
1449 : *
1450 : * This is like table_tuple_insert(), but inserts multiple tuples in one
1451 : * operation. That's often faster than calling table_tuple_insert() in a loop,
1452 : * because e.g. the AM can reduce WAL logging and page locking overhead.
1453 : *
1454 : * Except for taking `nslots` tuples as input, and an array of TupleTableSlots
1455 : * in `slots`, the parameters for table_multi_insert() are the same as for
1456 : * table_tuple_insert().
1457 : *
1458 : * Note: this leaks memory into the current memory context. You can create a
1459 : * temporary context before calling this, if that's a problem.
1460 : */
1461 : static inline void
1462 2390 : table_multi_insert(Relation rel, TupleTableSlot **slots, int nslots,
1463 : CommandId cid, int options, struct BulkInsertStateData *bistate)
1464 : {
1465 2390 : rel->rd_tableam->multi_insert(rel, slots, nslots,
1466 : cid, options, bistate);
1467 2390 : }
1468 :
1469 : /*
1470 : * Delete a tuple.
1471 : *
1472 : * NB: do not call this directly unless prepared to deal with
1473 : * concurrent-update conditions. Use simple_table_tuple_delete instead.
1474 : *
1475 : * Input parameters:
1476 : * relation - table to be modified (caller must hold suitable lock)
1477 : * tid - TID of tuple to be deleted
1478 : * cid - delete command ID (used for visibility test, and stored into
1479 : * cmax if successful)
1480 : * crosscheck - if not InvalidSnapshot, also check tuple against this
1481 : * wait - true if should wait for any conflicting update to commit/abort
1482 : * Output parameters:
1483 : * tmfd - filled in failure cases (see below)
1484 : * changingPart - true iff the tuple is being moved to another partition
1485 : * table due to an update of the partition key. Otherwise, false.
1486 : *
1487 : * Normal, successful return value is TM_Ok, which means we did actually
1488 : * delete it. Failure return codes are TM_SelfModified, TM_Updated, and
1489 : * TM_BeingModified (the last only possible if wait == false).
1490 : *
1491 : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
1492 : * t_xmax, and, if possible, t_cmax. See comments for struct
1493 : * TM_FailureData for additional info.
1494 : */
1495 : static inline TM_Result
1496 1720374 : table_tuple_delete(Relation rel, ItemPointer tid, CommandId cid,
1497 : Snapshot snapshot, Snapshot crosscheck, bool wait,
1498 : TM_FailureData *tmfd, bool changingPart)
1499 : {
1500 1720374 : return rel->rd_tableam->tuple_delete(rel, tid, cid,
1501 : snapshot, crosscheck,
1502 : wait, tmfd, changingPart);
1503 : }
1504 :
1505 : /*
1506 : * Update a tuple.
1507 : *
1508 : * NB: do not call this directly unless you are prepared to deal with
1509 : * concurrent-update conditions. Use simple_table_tuple_update instead.
1510 : *
1511 : * Input parameters:
1512 : * relation - table to be modified (caller must hold suitable lock)
1513 : * otid - TID of old tuple to be replaced
1514 : * slot - newly constructed tuple data to store
1515 : * cid - update command ID (used for visibility test, and stored into
1516 : * cmax/cmin if successful)
1517 : * crosscheck - if not InvalidSnapshot, also check old tuple against this
1518 : * wait - true if should wait for any conflicting update to commit/abort
1519 : * Output parameters:
1520 : * tmfd - filled in failure cases (see below)
1521 : * lockmode - filled with lock mode acquired on tuple
1522 : * update_indexes - in success cases this is set to true if new index entries
1523 : * are required for this tuple
1524 : *
1525 : * Normal, successful return value is TM_Ok, which means we did actually
1526 : * update it. Failure return codes are TM_SelfModified, TM_Updated, and
1527 : * TM_BeingModified (the last only possible if wait == false).
1528 : *
1529 : * On success, the slot's tts_tid and tts_tableOid are updated to match the new
1530 : * stored tuple; in particular, slot->tts_tid is set to the TID where the
1531 : * new tuple was inserted, and its HEAP_ONLY_TUPLE flag is set iff a HOT
1532 : * update was done. However, any TOAST changes in the new tuple's
1533 : * data are not reflected into *newtup.
1534 : *
1535 : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
1536 : * t_xmax, and, if possible, t_cmax. See comments for struct TM_FailureData
1537 : * for additional info.
1538 : */
1539 : static inline TM_Result
1540 378524 : table_tuple_update(Relation rel, ItemPointer otid, TupleTableSlot *slot,
1541 : CommandId cid, Snapshot snapshot, Snapshot crosscheck,
1542 : bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode,
1543 : TU_UpdateIndexes *update_indexes)
1544 : {
1545 378524 : return rel->rd_tableam->tuple_update(rel, otid, slot,
1546 : cid, snapshot, crosscheck,
1547 : wait, tmfd,
1548 : lockmode, update_indexes);
1549 : }
1550 :
1551 : /*
1552 : * Lock a tuple in the specified mode.
1553 : *
1554 : * Input parameters:
1555 : * relation: relation containing tuple (caller must hold suitable lock)
1556 : * tid: TID of tuple to lock
1557 : * snapshot: snapshot to use for visibility determinations
1558 : * cid: current command ID (used for visibility test, and stored into
1559 : * tuple's cmax if lock is successful)
1560 : * mode: lock mode desired
1561 : * wait_policy: what to do if tuple lock is not available
1562 : * flags:
1563 : * If TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS, follow the update chain to
1564 : * also lock descendant tuples if lock modes don't conflict.
1565 : * If TUPLE_LOCK_FLAG_FIND_LAST_VERSION, follow the update chain and lock
1566 : * latest version.
1567 : *
1568 : * Output parameters:
1569 : * *slot: contains the target tuple
1570 : * *tmfd: filled in failure cases (see below)
1571 : *
1572 : * Function result may be:
1573 : * TM_Ok: lock was successfully acquired
1574 : * TM_Invisible: lock failed because tuple was never visible to us
1575 : * TM_SelfModified: lock failed because tuple updated by self
1576 : * TM_Updated: lock failed because tuple updated by other xact
1577 : * TM_Deleted: lock failed because tuple deleted by other xact
1578 : * TM_WouldBlock: lock couldn't be acquired and wait_policy is skip
1579 : *
1580 : * In the failure cases other than TM_Invisible and TM_Deleted, the routine
1581 : * fills *tmfd with the tuple's t_ctid, t_xmax, and, if possible, t_cmax. See
1582 : * comments for struct TM_FailureData for additional info.
1583 : */
1584 : static inline TM_Result
1585 169848 : table_tuple_lock(Relation rel, ItemPointer tid, Snapshot snapshot,
1586 : TupleTableSlot *slot, CommandId cid, LockTupleMode mode,
1587 : LockWaitPolicy wait_policy, uint8 flags,
1588 : TM_FailureData *tmfd)
1589 : {
1590 169848 : return rel->rd_tableam->tuple_lock(rel, tid, snapshot, slot,
1591 : cid, mode, wait_policy,
1592 : flags, tmfd);
1593 : }
1594 :
1595 : /*
1596 : * Perform operations necessary to complete insertions made via
1597 : * tuple_insert and multi_insert with a BulkInsertState specified.
1598 : */
1599 : static inline void
1600 3836 : table_finish_bulk_insert(Relation rel, int options)
1601 : {
1602 : /* optional callback */
1603 3836 : if (rel->rd_tableam && rel->rd_tableam->finish_bulk_insert)
1604 0 : rel->rd_tableam->finish_bulk_insert(rel, options);
1605 3836 : }
1606 :
1607 :
1608 : /* ------------------------------------------------------------------------
1609 : * DDL related functionality.
1610 : * ------------------------------------------------------------------------
1611 : */
1612 :
1613 : /*
1614 : * Create storage for `rel` in `newrlocator`, with persistence set to
1615 : * `persistence`.
1616 : *
1617 : * This is used both during relation creation and various DDL operations to
1618 : * create new rel storage that can be filled from scratch. When creating
1619 : * new storage for an existing relfilelocator, this should be called before the
1620 : * relcache entry has been updated.
1621 : *
1622 : * *freezeXid, *minmulti are set to the xid / multixact horizon for the table
1623 : * that pg_class.{relfrozenxid, relminmxid} have to be set to.
1624 : */
1625 : static inline void
1626 60808 : table_relation_set_new_filelocator(Relation rel,
1627 : const RelFileLocator *newrlocator,
1628 : char persistence,
1629 : TransactionId *freezeXid,
1630 : MultiXactId *minmulti)
1631 : {
1632 60808 : rel->rd_tableam->relation_set_new_filelocator(rel, newrlocator,
1633 : persistence, freezeXid,
1634 : minmulti);
1635 60808 : }
1636 :
1637 : /*
1638 : * Remove all table contents from `rel`, in a non-transactional manner.
1639 : * Non-transactional meaning that there's no need to support rollbacks. This
1640 : * commonly only is used to perform truncations for relation storage created in
1641 : * the current transaction.
1642 : */
1643 : static inline void
1644 576 : table_relation_nontransactional_truncate(Relation rel)
1645 : {
1646 576 : rel->rd_tableam->relation_nontransactional_truncate(rel);
1647 576 : }
1648 :
1649 : /*
1650 : * Copy data from `rel` into the new relfilelocator `newrlocator`. The new
1651 : * relfilelocator may not have storage associated before this function is
1652 : * called. This is only supposed to be used for low level operations like
1653 : * changing a relation's tablespace.
1654 : */
1655 : static inline void
1656 98 : table_relation_copy_data(Relation rel, const RelFileLocator *newrlocator)
1657 : {
1658 98 : rel->rd_tableam->relation_copy_data(rel, newrlocator);
1659 98 : }
1660 :
1661 : /*
1662 : * Copy data from `OldTable` into `NewTable`, as part of a CLUSTER or VACUUM
1663 : * FULL.
1664 : *
1665 : * Additional Input parameters:
1666 : * - use_sort - if true, the table contents are sorted appropriate for
1667 : * `OldIndex`; if false and OldIndex is not InvalidOid, the data is copied
1668 : * in that index's order; if false and OldIndex is InvalidOid, no sorting is
1669 : * performed
1670 : * - OldIndex - see use_sort
1671 : * - OldestXmin - computed by vacuum_get_cutoffs(), even when
1672 : * not needed for the relation's AM
1673 : * - *xid_cutoff - ditto
1674 : * - *multi_cutoff - ditto
1675 : *
1676 : * Output parameters:
1677 : * - *xid_cutoff - rel's new relfrozenxid value, may be invalid
1678 : * - *multi_cutoff - rel's new relminmxid value, may be invalid
1679 : * - *tups_vacuumed - stats, for logging, if appropriate for AM
1680 : * - *tups_recently_dead - stats, for logging, if appropriate for AM
1681 : */
1682 : static inline void
1683 546 : table_relation_copy_for_cluster(Relation OldTable, Relation NewTable,
1684 : Relation OldIndex,
1685 : bool use_sort,
1686 : TransactionId OldestXmin,
1687 : TransactionId *xid_cutoff,
1688 : MultiXactId *multi_cutoff,
1689 : double *num_tuples,
1690 : double *tups_vacuumed,
1691 : double *tups_recently_dead)
1692 : {
1693 546 : OldTable->rd_tableam->relation_copy_for_cluster(OldTable, NewTable, OldIndex,
1694 : use_sort, OldestXmin,
1695 : xid_cutoff, multi_cutoff,
1696 : num_tuples, tups_vacuumed,
1697 : tups_recently_dead);
1698 546 : }
1699 :
1700 : /*
1701 : * Perform VACUUM on the relation. The VACUUM can be triggered by a user or by
1702 : * autovacuum. The specific actions performed by the AM will depend heavily on
1703 : * the individual AM.
1704 : *
1705 : * On entry a transaction needs to already been established, and the
1706 : * table is locked with a ShareUpdateExclusive lock.
1707 : *
1708 : * Note that neither VACUUM FULL (and CLUSTER), nor ANALYZE go through this
1709 : * routine, even if (for ANALYZE) it is part of the same VACUUM command.
1710 : */
1711 : static inline void
1712 113712 : table_relation_vacuum(Relation rel, struct VacuumParams *params,
1713 : BufferAccessStrategy bstrategy)
1714 : {
1715 113712 : rel->rd_tableam->relation_vacuum(rel, params, bstrategy);
1716 113710 : }
1717 :
1718 : /*
1719 : * Prepare to analyze the next block in the read stream. The scan needs to
1720 : * have been started with table_beginscan_analyze(). Note that this routine
1721 : * might acquire resources like locks that are held until
1722 : * table_scan_analyze_next_tuple() returns false.
1723 : *
1724 : * Returns false if block is unsuitable for sampling, true otherwise.
1725 : */
1726 : static inline bool
1727 145796 : table_scan_analyze_next_block(TableScanDesc scan, ReadStream *stream)
1728 : {
1729 145796 : return scan->rs_rd->rd_tableam->scan_analyze_next_block(scan, stream);
1730 : }
1731 :
1732 : /*
1733 : * Iterate over tuples in the block selected with
1734 : * table_scan_analyze_next_block() (which needs to have returned true, and
1735 : * this routine may not have returned false for the same block before). If a
1736 : * tuple that's suitable for sampling is found, true is returned and a tuple
1737 : * is stored in `slot`.
1738 : *
1739 : * *liverows and *deadrows are incremented according to the encountered
1740 : * tuples.
1741 : */
1742 : static inline bool
1743 10290192 : table_scan_analyze_next_tuple(TableScanDesc scan, TransactionId OldestXmin,
1744 : double *liverows, double *deadrows,
1745 : TupleTableSlot *slot)
1746 : {
1747 10290192 : return scan->rs_rd->rd_tableam->scan_analyze_next_tuple(scan, OldestXmin,
1748 : liverows, deadrows,
1749 : slot);
1750 : }
1751 :
1752 : /*
1753 : * table_index_build_scan - scan the table to find tuples to be indexed
1754 : *
1755 : * This is called back from an access-method-specific index build procedure
1756 : * after the AM has done whatever setup it needs. The parent table relation
1757 : * is scanned to find tuples that should be entered into the index. Each
1758 : * such tuple is passed to the AM's callback routine, which does the right
1759 : * things to add it to the new index. After we return, the AM's index
1760 : * build procedure does whatever cleanup it needs.
1761 : *
1762 : * The total count of live tuples is returned. This is for updating pg_class
1763 : * statistics. (It's annoying not to be able to do that here, but we want to
1764 : * merge that update with others; see index_update_stats.) Note that the
1765 : * index AM itself must keep track of the number of index tuples; we don't do
1766 : * so here because the AM might reject some of the tuples for its own reasons,
1767 : * such as being unable to store NULLs.
1768 : *
1769 : * If 'progress', the PROGRESS_SCAN_BLOCKS_TOTAL counter is updated when
1770 : * starting the scan, and PROGRESS_SCAN_BLOCKS_DONE is updated as we go along.
1771 : *
1772 : * A side effect is to set indexInfo->ii_BrokenHotChain to true if we detect
1773 : * any potentially broken HOT chains. Currently, we set this if there are any
1774 : * RECENTLY_DEAD or DELETE_IN_PROGRESS entries in a HOT chain, without trying
1775 : * very hard to detect whether they're really incompatible with the chain tip.
1776 : * This only really makes sense for heap AM, it might need to be generalized
1777 : * for other AMs later.
1778 : */
1779 : static inline double
1780 50842 : table_index_build_scan(Relation table_rel,
1781 : Relation index_rel,
1782 : struct IndexInfo *index_info,
1783 : bool allow_sync,
1784 : bool progress,
1785 : IndexBuildCallback callback,
1786 : void *callback_state,
1787 : TableScanDesc scan)
1788 : {
1789 50842 : return table_rel->rd_tableam->index_build_range_scan(table_rel,
1790 : index_rel,
1791 : index_info,
1792 : allow_sync,
1793 : false,
1794 : progress,
1795 : 0,
1796 : InvalidBlockNumber,
1797 : callback,
1798 : callback_state,
1799 : scan);
1800 : }
1801 :
1802 : /*
1803 : * As table_index_build_scan(), except that instead of scanning the complete
1804 : * table, only the given number of blocks are scanned. Scan to end-of-rel can
1805 : * be signaled by passing InvalidBlockNumber as numblocks. Note that
1806 : * restricting the range to scan cannot be done when requesting syncscan.
1807 : *
1808 : * When "anyvisible" mode is requested, all tuples visible to any transaction
1809 : * are indexed and counted as live, including those inserted or deleted by
1810 : * transactions that are still in progress.
1811 : */
1812 : static inline double
1813 2942 : table_index_build_range_scan(Relation table_rel,
1814 : Relation index_rel,
1815 : struct IndexInfo *index_info,
1816 : bool allow_sync,
1817 : bool anyvisible,
1818 : bool progress,
1819 : BlockNumber start_blockno,
1820 : BlockNumber numblocks,
1821 : IndexBuildCallback callback,
1822 : void *callback_state,
1823 : TableScanDesc scan)
1824 : {
1825 2942 : return table_rel->rd_tableam->index_build_range_scan(table_rel,
1826 : index_rel,
1827 : index_info,
1828 : allow_sync,
1829 : anyvisible,
1830 : progress,
1831 : start_blockno,
1832 : numblocks,
1833 : callback,
1834 : callback_state,
1835 : scan);
1836 : }
1837 :
1838 : /*
1839 : * table_index_validate_scan - second table scan for concurrent index build
1840 : *
1841 : * See validate_index() for an explanation.
1842 : */
1843 : static inline void
1844 620 : table_index_validate_scan(Relation table_rel,
1845 : Relation index_rel,
1846 : struct IndexInfo *index_info,
1847 : Snapshot snapshot,
1848 : struct ValidateIndexState *state)
1849 : {
1850 620 : table_rel->rd_tableam->index_validate_scan(table_rel,
1851 : index_rel,
1852 : index_info,
1853 : snapshot,
1854 : state);
1855 620 : }
1856 :
1857 :
1858 : /* ----------------------------------------------------------------------------
1859 : * Miscellaneous functionality
1860 : * ----------------------------------------------------------------------------
1861 : */
1862 :
1863 : /*
1864 : * Return the current size of `rel` in bytes. If `forkNumber` is
1865 : * InvalidForkNumber, return the relation's overall size, otherwise the size
1866 : * for the indicated fork.
1867 : *
1868 : * Note that the overall size might not be the equivalent of the sum of sizes
1869 : * for the individual forks for some AMs, e.g. because the AMs storage does
1870 : * not neatly map onto the builtin types of forks.
1871 : */
1872 : static inline uint64
1873 2346474 : table_relation_size(Relation rel, ForkNumber forkNumber)
1874 : {
1875 2346474 : return rel->rd_tableam->relation_size(rel, forkNumber);
1876 : }
1877 :
1878 : /*
1879 : * table_relation_needs_toast_table - does this relation need a toast table?
1880 : */
1881 : static inline bool
1882 41270 : table_relation_needs_toast_table(Relation rel)
1883 : {
1884 41270 : return rel->rd_tableam->relation_needs_toast_table(rel);
1885 : }
1886 :
1887 : /*
1888 : * Return the OID of the AM that should be used to implement the TOAST table
1889 : * for this relation.
1890 : */
1891 : static inline Oid
1892 16718 : table_relation_toast_am(Relation rel)
1893 : {
1894 16718 : return rel->rd_tableam->relation_toast_am(rel);
1895 : }
1896 :
1897 : /*
1898 : * Fetch all or part of a TOAST value from a TOAST table.
1899 : *
1900 : * If this AM is never used to implement a TOAST table, then this callback
1901 : * is not needed. But, if toasted values are ever stored in a table of this
1902 : * type, then you will need this callback.
1903 : *
1904 : * toastrel is the relation in which the toasted value is stored.
1905 : *
1906 : * valueid identifies which toast value is to be fetched. For the heap,
1907 : * this corresponds to the values stored in the chunk_id column.
1908 : *
1909 : * attrsize is the total size of the toast value to be fetched.
1910 : *
1911 : * sliceoffset is the offset within the toast value of the first byte that
1912 : * should be fetched.
1913 : *
1914 : * slicelength is the number of bytes from the toast value that should be
1915 : * fetched.
1916 : *
1917 : * result is caller-allocated space into which the fetched bytes should be
1918 : * stored.
1919 : */
1920 : static inline void
1921 20180 : table_relation_fetch_toast_slice(Relation toastrel, Oid valueid,
1922 : int32 attrsize, int32 sliceoffset,
1923 : int32 slicelength, struct varlena *result)
1924 : {
1925 20180 : toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
1926 : attrsize,
1927 : sliceoffset, slicelength,
1928 : result);
1929 20180 : }
1930 :
1931 :
1932 : /* ----------------------------------------------------------------------------
1933 : * Planner related functionality
1934 : * ----------------------------------------------------------------------------
1935 : */
1936 :
1937 : /*
1938 : * Estimate the current size of the relation, as an AM specific workhorse for
1939 : * estimate_rel_size(). Look there for an explanation of the parameters.
1940 : */
1941 : static inline void
1942 404040 : table_relation_estimate_size(Relation rel, int32 *attr_widths,
1943 : BlockNumber *pages, double *tuples,
1944 : double *allvisfrac)
1945 : {
1946 404040 : rel->rd_tableam->relation_estimate_size(rel, attr_widths, pages, tuples,
1947 : allvisfrac);
1948 404040 : }
1949 :
1950 :
1951 : /* ----------------------------------------------------------------------------
1952 : * Executor related functionality
1953 : * ----------------------------------------------------------------------------
1954 : */
1955 :
1956 : /*
1957 : * Prepare to fetch / check / return tuples as part of a bitmap table scan.
1958 : * `scan` needs to have been started via table_beginscan_bm(). Returns false
1959 : * if there are no more blocks in the bitmap, true otherwise.
1960 : *
1961 : * `lossy_pages` and `exact_pages` are EXPLAIN counters that can be
1962 : * incremented by the table AM to indicate whether or not the block's
1963 : * representation in the bitmap is lossy.
1964 : *
1965 : * `recheck` is set by the table AM to indicate whether or not the tuples
1966 : * from this block should be rechecked.
1967 : *
1968 : * `blockno` is the current block and is set by the table AM and is used by
1969 : * bitmap table scan code to validate that the prefetch block stays ahead of
1970 : * the current block.
1971 : *
1972 : * Note, this is an optionally implemented function, therefore should only be
1973 : * used after verifying the presence (at plan time or such).
1974 : */
1975 : static inline bool
1976 410486 : table_scan_bitmap_next_block(TableScanDesc scan,
1977 : BlockNumber *blockno,
1978 : bool *recheck,
1979 : uint64 *lossy_pages,
1980 : uint64 *exact_pages)
1981 : {
1982 : /*
1983 : * We don't expect direct calls to table_scan_bitmap_next_block with valid
1984 : * CheckXidAlive for catalog or regular tables. See detailed comments in
1985 : * xact.c where these variables are declared.
1986 : */
1987 410486 : if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
1988 0 : elog(ERROR, "unexpected table_scan_bitmap_next_block call during logical decoding");
1989 :
1990 410486 : return scan->rs_rd->rd_tableam->scan_bitmap_next_block(scan,
1991 : blockno, recheck,
1992 : lossy_pages,
1993 : exact_pages);
1994 : }
1995 :
1996 : /*
1997 : * Fetch the next tuple of a bitmap table scan into `slot` and return true if
1998 : * a visible tuple was found, false otherwise.
1999 : * table_scan_bitmap_next_block() needs to previously have selected a
2000 : * block (i.e. returned true), and no previous
2001 : * table_scan_bitmap_next_tuple() for the same block may have
2002 : * returned false.
2003 : */
2004 : static inline bool
2005 6797414 : table_scan_bitmap_next_tuple(TableScanDesc scan,
2006 : TupleTableSlot *slot)
2007 : {
2008 : /*
2009 : * We don't expect direct calls to table_scan_bitmap_next_tuple with valid
2010 : * CheckXidAlive for catalog or regular tables. See detailed comments in
2011 : * xact.c where these variables are declared.
2012 : */
2013 6797414 : if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
2014 0 : elog(ERROR, "unexpected table_scan_bitmap_next_tuple call during logical decoding");
2015 :
2016 6797414 : return scan->rs_rd->rd_tableam->scan_bitmap_next_tuple(scan,
2017 : slot);
2018 : }
2019 :
2020 : /*
2021 : * Prepare to fetch tuples from the next block in a sample scan. Returns false
2022 : * if the sample scan is finished, true otherwise. `scan` needs to have been
2023 : * started via table_beginscan_sampling().
2024 : *
2025 : * This will call the TsmRoutine's NextSampleBlock() callback if necessary
2026 : * (i.e. NextSampleBlock is not NULL), or perform a sequential scan over the
2027 : * underlying relation.
2028 : */
2029 : static inline bool
2030 12912 : table_scan_sample_next_block(TableScanDesc scan,
2031 : struct SampleScanState *scanstate)
2032 : {
2033 : /*
2034 : * We don't expect direct calls to table_scan_sample_next_block with valid
2035 : * CheckXidAlive for catalog or regular tables. See detailed comments in
2036 : * xact.c where these variables are declared.
2037 : */
2038 12912 : if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
2039 0 : elog(ERROR, "unexpected table_scan_sample_next_block call during logical decoding");
2040 12912 : return scan->rs_rd->rd_tableam->scan_sample_next_block(scan, scanstate);
2041 : }
2042 :
2043 : /*
2044 : * Fetch the next sample tuple into `slot` and return true if a visible tuple
2045 : * was found, false otherwise. table_scan_sample_next_block() needs to
2046 : * previously have selected a block (i.e. returned true), and no previous
2047 : * table_scan_sample_next_tuple() for the same block may have returned false.
2048 : *
2049 : * This will call the TsmRoutine's NextSampleTuple() callback.
2050 : */
2051 : static inline bool
2052 253896 : table_scan_sample_next_tuple(TableScanDesc scan,
2053 : struct SampleScanState *scanstate,
2054 : TupleTableSlot *slot)
2055 : {
2056 : /*
2057 : * We don't expect direct calls to table_scan_sample_next_tuple with valid
2058 : * CheckXidAlive for catalog or regular tables. See detailed comments in
2059 : * xact.c where these variables are declared.
2060 : */
2061 253896 : if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
2062 0 : elog(ERROR, "unexpected table_scan_sample_next_tuple call during logical decoding");
2063 253896 : return scan->rs_rd->rd_tableam->scan_sample_next_tuple(scan, scanstate,
2064 : slot);
2065 : }
2066 :
2067 :
2068 : /* ----------------------------------------------------------------------------
2069 : * Functions to make modifications a bit simpler.
2070 : * ----------------------------------------------------------------------------
2071 : */
2072 :
2073 : extern void simple_table_tuple_insert(Relation rel, TupleTableSlot *slot);
2074 : extern void simple_table_tuple_delete(Relation rel, ItemPointer tid,
2075 : Snapshot snapshot);
2076 : extern void simple_table_tuple_update(Relation rel, ItemPointer otid,
2077 : TupleTableSlot *slot, Snapshot snapshot,
2078 : TU_UpdateIndexes *update_indexes);
2079 :
2080 :
2081 : /* ----------------------------------------------------------------------------
2082 : * Helper functions to implement parallel scans for block oriented AMs.
2083 : * ----------------------------------------------------------------------------
2084 : */
2085 :
2086 : extern Size table_block_parallelscan_estimate(Relation rel);
2087 : extern Size table_block_parallelscan_initialize(Relation rel,
2088 : ParallelTableScanDesc pscan);
2089 : extern void table_block_parallelscan_reinitialize(Relation rel,
2090 : ParallelTableScanDesc pscan);
2091 : extern BlockNumber table_block_parallelscan_nextpage(Relation rel,
2092 : ParallelBlockTableScanWorker pbscanwork,
2093 : ParallelBlockTableScanDesc pbscan);
2094 : extern void table_block_parallelscan_startblock_init(Relation rel,
2095 : ParallelBlockTableScanWorker pbscanwork,
2096 : ParallelBlockTableScanDesc pbscan);
2097 :
2098 :
2099 : /* ----------------------------------------------------------------------------
2100 : * Helper functions to implement relation sizing for block oriented AMs.
2101 : * ----------------------------------------------------------------------------
2102 : */
2103 :
2104 : extern uint64 table_block_relation_size(Relation rel, ForkNumber forkNumber);
2105 : extern void table_block_relation_estimate_size(Relation rel,
2106 : int32 *attr_widths,
2107 : BlockNumber *pages,
2108 : double *tuples,
2109 : double *allvisfrac,
2110 : Size overhead_bytes_per_tuple,
2111 : Size usable_bytes_per_page);
2112 :
2113 : /* ----------------------------------------------------------------------------
2114 : * Functions in tableamapi.c
2115 : * ----------------------------------------------------------------------------
2116 : */
2117 :
2118 : extern const TableAmRoutine *GetTableAmRoutine(Oid amhandler);
2119 :
2120 : /* ----------------------------------------------------------------------------
2121 : * Functions in heapam_handler.c
2122 : * ----------------------------------------------------------------------------
2123 : */
2124 :
2125 : extern const TableAmRoutine *GetHeapamTableAmRoutine(void);
2126 :
2127 : #endif /* TABLEAM_H */
|