LCOV - code coverage report
Current view: top level - src/include/access - tableam.h (source / functions) Hit Total Coverage
Test: PostgreSQL 14devel Lines: 135 143 94.4 %
Date: 2021-01-26 21:06:51 Functions: 46 46 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13