PostgreSQL Source Code  git master
heapam_handler.c File Reference
#include "postgres.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heaptoast.h"
#include "access/multixact.h"
#include "access/rewriteheap.h"
#include "access/syncscan.h"
#include "access/tableam.h"
#include "access/tsmapi.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/index.h"
#include "catalog/storage.h"
#include "catalog/storage_xlog.h"
#include "commands/progress.h"
#include "executor/executor.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "storage/bufmgr.h"
#include "storage/bufpage.h"
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/procarray.h"
#include "storage/smgr.h"
#include "utils/builtins.h"
#include "utils/rel.h"
Include dependency graph for heapam_handler.c:

Go to the source code of this file.

Macros

#define HEAP_OVERHEAD_BYTES_PER_TUPLE   (MAXALIGN(SizeofHeapTupleHeader) + sizeof(ItemIdData))
 
#define HEAP_USABLE_BYTES_PER_PAGE   (BLCKSZ - SizeOfPageHeaderData)
 

Functions

static void reform_and_rewrite_tuple (HeapTuple tuple, Relation OldHeap, Relation NewHeap, Datum *values, bool *isnull, RewriteState rwstate)
 
static bool SampleHeapTupleVisible (TableScanDesc scan, Buffer buffer, HeapTuple tuple, OffsetNumber tupoffset)
 
static BlockNumber heapam_scan_get_blocks_done (HeapScanDesc hscan)
 
static const TupleTableSlotOpsheapam_slot_callbacks (Relation relation)
 
static IndexFetchTableDataheapam_index_fetch_begin (Relation rel)
 
static void heapam_index_fetch_reset (IndexFetchTableData *scan)
 
static void heapam_index_fetch_end (IndexFetchTableData *scan)
 
static bool heapam_index_fetch_tuple (struct IndexFetchTableData *scan, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot, bool *call_again, bool *all_dead)
 
static bool heapam_fetch_row_version (Relation relation, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot)
 
static bool heapam_tuple_tid_valid (TableScanDesc scan, ItemPointer tid)
 
static bool heapam_tuple_satisfies_snapshot (Relation rel, TupleTableSlot *slot, Snapshot snapshot)
 
static void heapam_tuple_insert (Relation relation, TupleTableSlot *slot, CommandId cid, int options, BulkInsertState bistate)
 
static void heapam_tuple_insert_speculative (Relation relation, TupleTableSlot *slot, CommandId cid, int options, BulkInsertState bistate, uint32 specToken)
 
static void heapam_tuple_complete_speculative (Relation relation, TupleTableSlot *slot, uint32 specToken, bool succeeded)
 
static TM_Result heapam_tuple_delete (Relation relation, ItemPointer tid, CommandId cid, Snapshot snapshot, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
 
static TM_Result heapam_tuple_update (Relation relation, ItemPointer otid, TupleTableSlot *slot, CommandId cid, Snapshot snapshot, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, bool *update_indexes)
 
static TM_Result heapam_tuple_lock (Relation relation, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, uint8 flags, TM_FailureData *tmfd)
 
static void heapam_relation_set_new_filenode (Relation rel, const RelFileNode *newrnode, char persistence, TransactionId *freezeXid, MultiXactId *minmulti)
 
static void heapam_relation_nontransactional_truncate (Relation rel)
 
static void heapam_relation_copy_data (Relation rel, const RelFileNode *newrnode)
 
static void heapam_relation_copy_for_cluster (Relation OldHeap, Relation NewHeap, Relation OldIndex, bool use_sort, TransactionId OldestXmin, TransactionId *xid_cutoff, MultiXactId *multi_cutoff, double *num_tuples, double *tups_vacuumed, double *tups_recently_dead)
 
static bool heapam_scan_analyze_next_block (TableScanDesc scan, BlockNumber blockno, BufferAccessStrategy bstrategy)
 
static bool heapam_scan_analyze_next_tuple (TableScanDesc scan, TransactionId OldestXmin, double *liverows, double *deadrows, TupleTableSlot *slot)
 
static double heapam_index_build_range_scan (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool allow_sync, bool anyvisible, bool progress, BlockNumber start_blockno, BlockNumber numblocks, IndexBuildCallback callback, void *callback_state, TableScanDesc scan)
 
static void heapam_index_validate_scan (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, Snapshot snapshot, ValidateIndexState *state)
 
static bool heapam_relation_needs_toast_table (Relation rel)
 
static Oid heapam_relation_toast_am (Relation rel)
 
static void heapam_estimate_rel_size (Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
 
static bool heapam_scan_bitmap_next_block (TableScanDesc scan, TBMIterateResult *tbmres)
 
static bool heapam_scan_bitmap_next_tuple (TableScanDesc scan, TBMIterateResult *tbmres, TupleTableSlot *slot)
 
static bool heapam_scan_sample_next_block (TableScanDesc scan, SampleScanState *scanstate)
 
static bool heapam_scan_sample_next_tuple (TableScanDesc scan, SampleScanState *scanstate, TupleTableSlot *slot)
 
const TableAmRoutineGetHeapamTableAmRoutine (void)
 
Datum heap_tableam_handler (PG_FUNCTION_ARGS)
 

Variables

static const TableAmRoutine heapam_methods
 

Macro Definition Documentation

◆ HEAP_OVERHEAD_BYTES_PER_TUPLE

#define HEAP_OVERHEAD_BYTES_PER_TUPLE   (MAXALIGN(SizeofHeapTupleHeader) + sizeof(ItemIdData))

Definition at line 2087 of file heapam_handler.c.

Referenced by heapam_estimate_rel_size().

◆ HEAP_USABLE_BYTES_PER_PAGE

#define HEAP_USABLE_BYTES_PER_PAGE   (BLCKSZ - SizeOfPageHeaderData)

Definition at line 2089 of file heapam_handler.c.

Referenced by heapam_estimate_rel_size().

Function Documentation

◆ GetHeapamTableAmRoutine()

const TableAmRoutine* GetHeapamTableAmRoutine ( void  )

Definition at line 2595 of file heapam_handler.c.

References heapam_methods.

Referenced by formrdesc(), heap_getnext(), and table_scan_sample_next_tuple().

2596 {
2597  return &heapam_methods;
2598 }
static const TableAmRoutine heapam_methods

◆ heap_tableam_handler()

Datum heap_tableam_handler ( PG_FUNCTION_ARGS  )

Definition at line 2601 of file heapam_handler.c.

References PG_RETURN_POINTER.

2602 {
2604 }
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
static const TableAmRoutine heapam_methods

◆ heapam_estimate_rel_size()

static void heapam_estimate_rel_size ( Relation  rel,
int32 attr_widths,
BlockNumber pages,
double *  tuples,
double *  allvisfrac 
)
static

Definition at line 2093 of file heapam_handler.c.

References HEAP_OVERHEAD_BYTES_PER_TUPLE, HEAP_USABLE_BYTES_PER_PAGE, and table_block_relation_estimate_size().

Referenced by SampleHeapTupleVisible().

2096 {
2097  table_block_relation_estimate_size(rel, attr_widths, pages,
2098  tuples, allvisfrac,
2101 }
#define HEAP_OVERHEAD_BYTES_PER_TUPLE
#define HEAP_USABLE_BYTES_PER_PAGE
void table_block_relation_estimate_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac, Size overhead_bytes_per_tuple, Size usable_bytes_per_page)
Definition: tableam.c:665

◆ heapam_fetch_row_version()

static bool heapam_fetch_row_version ( Relation  relation,
ItemPointer  tid,
Snapshot  snapshot,
TupleTableSlot slot 
)
static

Definition at line 180 of file heapam_handler.c.

References Assert, BufferHeapTupleTableSlot::base, ExecStorePinnedBufferHeapTuple(), heap_fetch(), RelationGetRelid, HeapTupleData::t_self, TTS_IS_BUFFERTUPLE, TupleTableSlot::tts_tableOid, and HeapTupleTableSlot::tupdata.

Referenced by SampleHeapTupleVisible().

184 {
186  Buffer buffer;
187 
188  Assert(TTS_IS_BUFFERTUPLE(slot));
189 
190  bslot->base.tupdata.t_self = *tid;
191  if (heap_fetch(relation, snapshot, &bslot->base.tupdata, &buffer))
192  {
193  /* store in slot, transferring existing pin */
194  ExecStorePinnedBufferHeapTuple(&bslot->base.tupdata, slot, buffer);
195  slot->tts_tableOid = RelationGetRelid(relation);
196 
197  return true;
198  }
199 
200  return false;
201 }
Oid tts_tableOid
Definition: tuptable.h:131
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf)
Definition: heapam.c:1595
ItemPointerData t_self
Definition: htup.h:65
#define TTS_IS_BUFFERTUPLE(slot)
Definition: tuptable.h:231
#define Assert(condition)
Definition: c.h:804
TupleTableSlot * ExecStorePinnedBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1418
HeapTupleTableSlot base
Definition: tuptable.h:259
HeapTupleData tupdata
Definition: tuptable.h:253
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:477

◆ heapam_index_build_range_scan()

static double heapam_index_build_range_scan ( Relation  heapRelation,
Relation  indexRelation,
IndexInfo indexInfo,
bool  allow_sync,
bool  anyvisible,
bool  progress,
BlockNumber  start_blockno,
BlockNumber  numblocks,
IndexBuildCallback  callback,
void *  callback_state,
TableScanDesc  scan 
)
static

Definition at line 1157 of file heapam_handler.c.

References Assert, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage, callback(), CHECK_FOR_INTERRUPTS, CreateExecutorState(), ExprContext::ecxt_per_tuple_memory, ExprContext::ecxt_scantuple, elog, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg_internal(), ERROR, ExecDropSingleTupleTableSlot(), ExecPrepareQual(), ExecQual(), ExecStoreBufferHeapTuple(), FormIndexDatum(), ForwardScanDirection, FreeExecutorState(), GetOldestNonRemovableTransactionId(), GetPerTupleExprContext, GetTransactionSnapshot(), heap_get_root_tuples(), heap_getnext(), heap_setscanlimits(), heapam_scan_get_blocks_done(), HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleIsHeapOnly, HeapTupleIsHotUpdated, HeapTupleSatisfiesVacuum(), IndexInfo::ii_BrokenHotChain, IndexInfo::ii_Concurrent, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExpressionsState, IndexInfo::ii_Predicate, IndexInfo::ii_PredicateState, IndexInfo::ii_Unique, INDEX_MAX_KEYS, InvalidBlockNumber, InvalidOffsetNumber, InvalidTransactionId, IsBootstrapProcessingMode, IsMVCCSnapshot, IsSystemRelation(), ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, ItemPointerSet, LockBuffer(), MaxHeapTuplesPerPage, MemoryContextReset(), NIL, OffsetNumberIsValid, OidIsValid, pgstat_progress_update_param(), ParallelBlockTableScanDescData::phs_nblocks, PROGRESS_SCAN_BLOCKS_DONE, PROGRESS_SCAN_BLOCKS_TOTAL, RelationData::rd_rel, RegisterSnapshot(), RelationGetRelationName, HeapScanDescData::rs_base, HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_nblocks, TableScanDescData::rs_parallel, TableScanDescData::rs_snapshot, SnapshotAny, HeapTupleData::t_data, HeapTupleData::t_self, table_beginscan_strat(), table_endscan(), table_slot_create(), TransactionIdIsCurrentTransactionId(), TransactionIdIsValid, UnregisterSnapshot(), values, WARNING, XactLockTableWait(), and XLTW_InsertIndexUnique.

Referenced by SampleHeapTupleVisible().

1168 {
1169  HeapScanDesc hscan;
1170  bool is_system_catalog;
1171  bool checking_uniqueness;
1172  HeapTuple heapTuple;
1174  bool isnull[INDEX_MAX_KEYS];
1175  double reltuples;
1176  ExprState *predicate;
1177  TupleTableSlot *slot;
1178  EState *estate;
1179  ExprContext *econtext;
1180  Snapshot snapshot;
1181  bool need_unregister_snapshot = false;
1182  TransactionId OldestXmin;
1183  BlockNumber previous_blkno = InvalidBlockNumber;
1184  BlockNumber root_blkno = InvalidBlockNumber;
1185  OffsetNumber root_offsets[MaxHeapTuplesPerPage];
1186 
1187  /*
1188  * sanity checks
1189  */
1190  Assert(OidIsValid(indexRelation->rd_rel->relam));
1191 
1192  /* Remember if it's a system catalog */
1193  is_system_catalog = IsSystemRelation(heapRelation);
1194 
1195  /* See whether we're verifying uniqueness/exclusion properties */
1196  checking_uniqueness = (indexInfo->ii_Unique ||
1197  indexInfo->ii_ExclusionOps != NULL);
1198 
1199  /*
1200  * "Any visible" mode is not compatible with uniqueness checks; make sure
1201  * only one of those is requested.
1202  */
1203  Assert(!(anyvisible && checking_uniqueness));
1204 
1205  /*
1206  * Need an EState for evaluation of index expressions and partial-index
1207  * predicates. Also a slot to hold the current tuple.
1208  */
1209  estate = CreateExecutorState();
1210  econtext = GetPerTupleExprContext(estate);
1211  slot = table_slot_create(heapRelation, NULL);
1212 
1213  /* Arrange for econtext's scan tuple to be the tuple under test */
1214  econtext->ecxt_scantuple = slot;
1215 
1216  /* Set up execution state for predicate, if any. */
1217  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
1218 
1219  /*
1220  * Prepare for scan of the base relation. In a normal index build, we use
1221  * SnapshotAny because we must retrieve all tuples and do our own time
1222  * qual checks (because we have to index RECENTLY_DEAD tuples). In a
1223  * concurrent build, or during bootstrap, we take a regular MVCC snapshot
1224  * and index whatever's live according to that.
1225  */
1226  OldestXmin = InvalidTransactionId;
1227 
1228  /* okay to ignore lazy VACUUMs here */
1229  if (!IsBootstrapProcessingMode() && !indexInfo->ii_Concurrent)
1230  OldestXmin = GetOldestNonRemovableTransactionId(heapRelation);
1231 
1232  if (!scan)
1233  {
1234  /*
1235  * Serial index build.
1236  *
1237  * Must begin our own heap scan in this case. We may also need to
1238  * register a snapshot whose lifetime is under our direct control.
1239  */
1240  if (!TransactionIdIsValid(OldestXmin))
1241  {
1243  need_unregister_snapshot = true;
1244  }
1245  else
1246  snapshot = SnapshotAny;
1247 
1248  scan = table_beginscan_strat(heapRelation, /* relation */
1249  snapshot, /* snapshot */
1250  0, /* number of keys */
1251  NULL, /* scan key */
1252  true, /* buffer access strategy OK */
1253  allow_sync); /* syncscan OK? */
1254  }
1255  else
1256  {
1257  /*
1258  * Parallel index build.
1259  *
1260  * Parallel case never registers/unregisters own snapshot. Snapshot
1261  * is taken from parallel heap scan, and is SnapshotAny or an MVCC
1262  * snapshot, based on same criteria as serial case.
1263  */
1265  Assert(allow_sync);
1266  snapshot = scan->rs_snapshot;
1267  }
1268 
1269  hscan = (HeapScanDesc) scan;
1270 
1271  /*
1272  * Must have called GetOldestNonRemovableTransactionId() if using
1273  * SnapshotAny. Shouldn't have for an MVCC snapshot. (It's especially
1274  * worth checking this for parallel builds, since ambuild routines that
1275  * support parallel builds must work these details out for themselves.)
1276  */
1277  Assert(snapshot == SnapshotAny || IsMVCCSnapshot(snapshot));
1278  Assert(snapshot == SnapshotAny ? TransactionIdIsValid(OldestXmin) :
1279  !TransactionIdIsValid(OldestXmin));
1280  Assert(snapshot == SnapshotAny || !anyvisible);
1281 
1282  /* Publish number of blocks to scan */
1283  if (progress)
1284  {
1285  BlockNumber nblocks;
1286 
1287  if (hscan->rs_base.rs_parallel != NULL)
1288  {
1290 
1292  nblocks = pbscan->phs_nblocks;
1293  }
1294  else
1295  nblocks = hscan->rs_nblocks;
1296 
1298  nblocks);
1299  }
1300 
1301  /* set our scan endpoints */
1302  if (!allow_sync)
1303  heap_setscanlimits(scan, start_blockno, numblocks);
1304  else
1305  {
1306  /* syncscan can only be requested on whole relation */
1307  Assert(start_blockno == 0);
1308  Assert(numblocks == InvalidBlockNumber);
1309  }
1310 
1311  reltuples = 0;
1312 
1313  /*
1314  * Scan all tuples in the base relation.
1315  */
1316  while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1317  {
1318  bool tupleIsAlive;
1319 
1321 
1322  /* Report scan progress, if asked to. */
1323  if (progress)
1324  {
1325  BlockNumber blocks_done = heapam_scan_get_blocks_done(hscan);
1326 
1327  if (blocks_done != previous_blkno)
1328  {
1330  blocks_done);
1331  previous_blkno = blocks_done;
1332  }
1333  }
1334 
1335  /*
1336  * When dealing with a HOT-chain of updated tuples, we want to index
1337  * the values of the live tuple (if any), but index it under the TID
1338  * of the chain's root tuple. This approach is necessary to preserve
1339  * the HOT-chain structure in the heap. So we need to be able to find
1340  * the root item offset for every tuple that's in a HOT-chain. When
1341  * first reaching a new page of the relation, call
1342  * heap_get_root_tuples() to build a map of root item offsets on the
1343  * page.
1344  *
1345  * It might look unsafe to use this information across buffer
1346  * lock/unlock. However, we hold ShareLock on the table so no
1347  * ordinary insert/update/delete should occur; and we hold pin on the
1348  * buffer continuously while visiting the page, so no pruning
1349  * operation can occur either.
1350  *
1351  * In cases with only ShareUpdateExclusiveLock on the table, it's
1352  * possible for some HOT tuples to appear that we didn't know about
1353  * when we first read the page. To handle that case, we re-obtain the
1354  * list of root offsets when a HOT tuple points to a root item that we
1355  * don't know about.
1356  *
1357  * Also, although our opinions about tuple liveness could change while
1358  * we scan the page (due to concurrent transaction commits/aborts),
1359  * the chain root locations won't, so this info doesn't need to be
1360  * rebuilt after waiting for another transaction.
1361  *
1362  * Note the implied assumption that there is no more than one live
1363  * tuple per HOT-chain --- else we could create more than one index
1364  * entry pointing to the same root tuple.
1365  */
1366  if (hscan->rs_cblock != root_blkno)
1367  {
1368  Page page = BufferGetPage(hscan->rs_cbuf);
1369 
1371  heap_get_root_tuples(page, root_offsets);
1373 
1374  root_blkno = hscan->rs_cblock;
1375  }
1376 
1377  if (snapshot == SnapshotAny)
1378  {
1379  /* do our own time qual check */
1380  bool indexIt;
1381  TransactionId xwait;
1382 
1383  recheck:
1384 
1385  /*
1386  * We could possibly get away with not locking the buffer here,
1387  * since caller should hold ShareLock on the relation, but let's
1388  * be conservative about it. (This remark is still correct even
1389  * with HOT-pruning: our pin on the buffer prevents pruning.)
1390  */
1392 
1393  /*
1394  * The criteria for counting a tuple as live in this block need to
1395  * match what analyze.c's heapam_scan_analyze_next_tuple() does,
1396  * otherwise CREATE INDEX and ANALYZE may produce wildly different
1397  * reltuples values, e.g. when there are many recently-dead
1398  * tuples.
1399  */
1400  switch (HeapTupleSatisfiesVacuum(heapTuple, OldestXmin,
1401  hscan->rs_cbuf))
1402  {
1403  case HEAPTUPLE_DEAD:
1404  /* Definitely dead, we can ignore it */
1405  indexIt = false;
1406  tupleIsAlive = false;
1407  break;
1408  case HEAPTUPLE_LIVE:
1409  /* Normal case, index and unique-check it */
1410  indexIt = true;
1411  tupleIsAlive = true;
1412  /* Count it as live, too */
1413  reltuples += 1;
1414  break;
1416 
1417  /*
1418  * If tuple is recently deleted then we must index it
1419  * anyway to preserve MVCC semantics. (Pre-existing
1420  * transactions could try to use the index after we finish
1421  * building it, and may need to see such tuples.)
1422  *
1423  * However, if it was HOT-updated then we must only index
1424  * the live tuple at the end of the HOT-chain. Since this
1425  * breaks semantics for pre-existing snapshots, mark the
1426  * index as unusable for them.
1427  *
1428  * We don't count recently-dead tuples in reltuples, even
1429  * if we index them; see heapam_scan_analyze_next_tuple().
1430  */
1431  if (HeapTupleIsHotUpdated(heapTuple))
1432  {
1433  indexIt = false;
1434  /* mark the index as unsafe for old snapshots */
1435  indexInfo->ii_BrokenHotChain = true;
1436  }
1437  else
1438  indexIt = true;
1439  /* In any case, exclude the tuple from unique-checking */
1440  tupleIsAlive = false;
1441  break;
1443 
1444  /*
1445  * In "anyvisible" mode, this tuple is visible and we
1446  * don't need any further checks.
1447  */
1448  if (anyvisible)
1449  {
1450  indexIt = true;
1451  tupleIsAlive = true;
1452  reltuples += 1;
1453  break;
1454  }
1455 
1456  /*
1457  * Since caller should hold ShareLock or better, normally
1458  * the only way to see this is if it was inserted earlier
1459  * in our own transaction. However, it can happen in
1460  * system catalogs, since we tend to release write lock
1461  * before commit there. Give a warning if neither case
1462  * applies.
1463  */
1464  xwait = HeapTupleHeaderGetXmin(heapTuple->t_data);
1466  {
1467  if (!is_system_catalog)
1468  elog(WARNING, "concurrent insert in progress within table \"%s\"",
1469  RelationGetRelationName(heapRelation));
1470 
1471  /*
1472  * If we are performing uniqueness checks, indexing
1473  * such a tuple could lead to a bogus uniqueness
1474  * failure. In that case we wait for the inserting
1475  * transaction to finish and check again.
1476  */
1477  if (checking_uniqueness)
1478  {
1479  /*
1480  * Must drop the lock on the buffer before we wait
1481  */
1483  XactLockTableWait(xwait, heapRelation,
1484  &heapTuple->t_self,
1487  goto recheck;
1488  }
1489  }
1490  else
1491  {
1492  /*
1493  * For consistency with
1494  * heapam_scan_analyze_next_tuple(), count
1495  * HEAPTUPLE_INSERT_IN_PROGRESS tuples as live only
1496  * when inserted by our own transaction.
1497  */
1498  reltuples += 1;
1499  }
1500 
1501  /*
1502  * We must index such tuples, since if the index build
1503  * commits then they're good.
1504  */
1505  indexIt = true;
1506  tupleIsAlive = true;
1507  break;
1509 
1510  /*
1511  * As with INSERT_IN_PROGRESS case, this is unexpected
1512  * unless it's our own deletion or a system catalog; but
1513  * in anyvisible mode, this tuple is visible.
1514  */
1515  if (anyvisible)
1516  {
1517  indexIt = true;
1518  tupleIsAlive = false;
1519  reltuples += 1;
1520  break;
1521  }
1522 
1523  xwait = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
1525  {
1526  if (!is_system_catalog)
1527  elog(WARNING, "concurrent delete in progress within table \"%s\"",
1528  RelationGetRelationName(heapRelation));
1529 
1530  /*
1531  * If we are performing uniqueness checks, assuming
1532  * the tuple is dead could lead to missing a
1533  * uniqueness violation. In that case we wait for the
1534  * deleting transaction to finish and check again.
1535  *
1536  * Also, if it's a HOT-updated tuple, we should not
1537  * index it but rather the live tuple at the end of
1538  * the HOT-chain. However, the deleting transaction
1539  * could abort, possibly leaving this tuple as live
1540  * after all, in which case it has to be indexed. The
1541  * only way to know what to do is to wait for the
1542  * deleting transaction to finish and check again.
1543  */
1544  if (checking_uniqueness ||
1545  HeapTupleIsHotUpdated(heapTuple))
1546  {
1547  /*
1548  * Must drop the lock on the buffer before we wait
1549  */
1551  XactLockTableWait(xwait, heapRelation,
1552  &heapTuple->t_self,
1555  goto recheck;
1556  }
1557 
1558  /*
1559  * Otherwise index it but don't check for uniqueness,
1560  * the same as a RECENTLY_DEAD tuple.
1561  */
1562  indexIt = true;
1563 
1564  /*
1565  * Count HEAPTUPLE_DELETE_IN_PROGRESS tuples as live,
1566  * if they were not deleted by the current
1567  * transaction. That's what
1568  * heapam_scan_analyze_next_tuple() does, and we want
1569  * the behavior to be consistent.
1570  */
1571  reltuples += 1;
1572  }
1573  else if (HeapTupleIsHotUpdated(heapTuple))
1574  {
1575  /*
1576  * It's a HOT-updated tuple deleted by our own xact.
1577  * We can assume the deletion will commit (else the
1578  * index contents don't matter), so treat the same as
1579  * RECENTLY_DEAD HOT-updated tuples.
1580  */
1581  indexIt = false;
1582  /* mark the index as unsafe for old snapshots */
1583  indexInfo->ii_BrokenHotChain = true;
1584  }
1585  else
1586  {
1587  /*
1588  * It's a regular tuple deleted by our own xact. Index
1589  * it, but don't check for uniqueness nor count in
1590  * reltuples, the same as a RECENTLY_DEAD tuple.
1591  */
1592  indexIt = true;
1593  }
1594  /* In any case, exclude the tuple from unique-checking */
1595  tupleIsAlive = false;
1596  break;
1597  default:
1598  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1599  indexIt = tupleIsAlive = false; /* keep compiler quiet */
1600  break;
1601  }
1602 
1604 
1605  if (!indexIt)
1606  continue;
1607  }
1608  else
1609  {
1610  /* heap_getnext did the time qual check */
1611  tupleIsAlive = true;
1612  reltuples += 1;
1613  }
1614 
1616 
1617  /* Set up for predicate or expression evaluation */
1618  ExecStoreBufferHeapTuple(heapTuple, slot, hscan->rs_cbuf);
1619 
1620  /*
1621  * In a partial index, discard tuples that don't satisfy the
1622  * predicate.
1623  */
1624  if (predicate != NULL)
1625  {
1626  if (!ExecQual(predicate, econtext))
1627  continue;
1628  }
1629 
1630  /*
1631  * For the current heap tuple, extract all the attributes we use in
1632  * this index, and note which are null. This also performs evaluation
1633  * of any expressions needed.
1634  */
1635  FormIndexDatum(indexInfo,
1636  slot,
1637  estate,
1638  values,
1639  isnull);
1640 
1641  /*
1642  * You'd think we should go ahead and build the index tuple here, but
1643  * some index AMs want to do further processing on the data first. So
1644  * pass the values[] and isnull[] arrays, instead.
1645  */
1646 
1647  if (HeapTupleIsHeapOnly(heapTuple))
1648  {
1649  /*
1650  * For a heap-only tuple, pretend its TID is that of the root. See
1651  * src/backend/access/heap/README.HOT for discussion.
1652  */
1653  ItemPointerData tid;
1654  OffsetNumber offnum;
1655 
1656  offnum = ItemPointerGetOffsetNumber(&heapTuple->t_self);
1657 
1658  /*
1659  * If a HOT tuple points to a root that we don't know about,
1660  * obtain root items afresh. If that still fails, report it as
1661  * corruption.
1662  */
1663  if (root_offsets[offnum - 1] == InvalidOffsetNumber)
1664  {
1665  Page page = BufferGetPage(hscan->rs_cbuf);
1666 
1668  heap_get_root_tuples(page, root_offsets);
1670  }
1671 
1672  if (!OffsetNumberIsValid(root_offsets[offnum - 1]))
1673  ereport(ERROR,
1675  errmsg_internal("failed to find parent tuple for heap-only tuple at (%u,%u) in table \"%s\"",
1676  ItemPointerGetBlockNumber(&heapTuple->t_self),
1677  offnum,
1678  RelationGetRelationName(heapRelation))));
1679 
1680  ItemPointerSet(&tid, ItemPointerGetBlockNumber(&heapTuple->t_self),
1681  root_offsets[offnum - 1]);
1682 
1683  /* Call the AM's callback routine to process the tuple */
1684  callback(indexRelation, &tid, values, isnull, tupleIsAlive,
1685  callback_state);
1686  }
1687  else
1688  {
1689  /* Call the AM's callback routine to process the tuple */
1690  callback(indexRelation, &heapTuple->t_self, values, isnull,
1691  tupleIsAlive, callback_state);
1692  }
1693  }
1694 
1695  /* Report scan progress one last time. */
1696  if (progress)
1697  {
1698  BlockNumber blks_done;
1699 
1700  if (hscan->rs_base.rs_parallel != NULL)
1701  {
1703 
1705  blks_done = pbscan->phs_nblocks;
1706  }
1707  else
1708  blks_done = hscan->rs_nblocks;
1709 
1711  blks_done);
1712  }
1713 
1714  table_endscan(scan);
1715 
1716  /* we can now forget our snapshot, if set and registered by us */
1717  if (need_unregister_snapshot)
1718  UnregisterSnapshot(snapshot);
1719 
1721 
1722  FreeExecutorState(estate);
1723 
1724  /* These may have been pointing to the now-gone estate */
1725  indexInfo->ii_ExpressionsState = NIL;
1726  indexInfo->ii_PredicateState = NULL;
1727 
1728  return reltuples;
1729 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:365
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2662
#define NIL
Definition: pg_list.h:65
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
BlockNumber rs_cblock
Definition: heapam.h:59
List * ii_Predicate
Definition: execnodes.h:163
bool IsSystemRelation(Relation relation)
Definition: catalog.c:74
uint32 TransactionId
Definition: c.h:587
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:869
struct ParallelBlockTableScanDescData * ParallelBlockTableScanDesc
Definition: relscan.h:85
TableScanDescData rs_base
Definition: heapam.h:49
ExprState * ii_PredicateState
Definition: execnodes.h:164
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:234
#define MaxHeapTuplesPerPage
Definition: htup_details.h:573
int errcode(int sqlerrcode)
Definition: elog.c:698
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:109
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:396
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define OidIsValid(objectId)
Definition: c.h:710
static TableScanDesc table_beginscan_strat(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key, bool allow_strat, bool allow_sync)
Definition: tableam.h:907
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:68
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define HeapTupleIsHotUpdated(tuple)
Definition: htup_details.h:675
#define GetPerTupleExprContext(estate)
Definition: executor.h:533
List * ii_ExpressionsState
Definition: execnodes.h:162
TransactionId GetOldestNonRemovableTransactionId(Relation rel)
Definition: procarray.c:2005
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:48
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
void heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
Definition: heapam.c:348
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:511
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:774
bool ii_BrokenHotChain
Definition: execnodes.h:175
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
void heap_get_root_tuples(Page page, OffsetNumber *root_offsets)
Definition: pruneheap.c:900
EState * CreateExecutorState(void)
Definition: execUtils.c:90
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:47
#define WARNING
Definition: elog.h:40
int progress
Definition: pgbench.c:272
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
uintptr_t Datum
Definition: postgres.h:411
BlockNumber rs_nblocks
Definition: heapam.h:52
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4011
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1392
#define IsMVCCSnapshot(snapshot)
Definition: snapmgr.h:96
#define InvalidOffsetNumber
Definition: off.h:26
#define ereport(elevel,...)
Definition: elog.h:157
Buffer rs_cbuf
Definition: heapam.h:60
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
bool ii_Unique
Definition: execnodes.h:172
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:640
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:684
#define Assert(condition)
Definition: c.h:804
void pgstat_progress_update_param(int index, int64 val)
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:313
#define INDEX_MAX_KEYS
#define InvalidBlockNumber
Definition: block.h:33
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:226
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:119
bool ii_Concurrent
Definition: execnodes.h:174
#define SnapshotAny
Definition: snapmgr.h:67
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
static Datum values[MAXATTR]
Definition: bootstrap.c:166
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:406
Oid * ii_ExclusionOps
Definition: execnodes.h:165
struct SnapshotData * rs_snapshot
Definition: relscan.h:35
#define elog(elevel,...)
Definition: elog.h:232
#define OffsetNumberIsValid(offsetNumber)
Definition: off.h:39
struct ParallelTableScanDescData * rs_parallel
Definition: relscan.h:49
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static BlockNumber heapam_scan_get_blocks_done(HeapScanDesc hscan)
Pointer Page
Definition: bufpage.h:78
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127

◆ heapam_index_fetch_begin()

static IndexFetchTableData* heapam_index_fetch_begin ( Relation  rel)
static

Definition at line 79 of file heapam_handler.c.

References InvalidBuffer, palloc0(), IndexFetchTableData::rel, IndexFetchHeapData::xs_base, and IndexFetchHeapData::xs_cbuf.

Referenced by SampleHeapTupleVisible().

80 {
82 
83  hscan->xs_base.rel = rel;
84  hscan->xs_cbuf = InvalidBuffer;
85 
86  return &hscan->xs_base;
87 }
#define InvalidBuffer
Definition: buf.h:25
Buffer xs_cbuf
Definition: heapam.h:88
void * palloc0(Size size)
Definition: mcxt.c:1093
IndexFetchTableData xs_base
Definition: heapam.h:86

◆ heapam_index_fetch_end()

static void heapam_index_fetch_end ( IndexFetchTableData scan)
static

Definition at line 102 of file heapam_handler.c.

References heapam_index_fetch_reset(), and pfree().

Referenced by SampleHeapTupleVisible().

103 {
104  IndexFetchHeapData *hscan = (IndexFetchHeapData *) scan;
105 
107 
108  pfree(hscan);
109 }
static void heapam_index_fetch_reset(IndexFetchTableData *scan)
void pfree(void *pointer)
Definition: mcxt.c:1169

◆ heapam_index_fetch_reset()

static void heapam_index_fetch_reset ( IndexFetchTableData scan)
static

Definition at line 90 of file heapam_handler.c.

References BufferIsValid, InvalidBuffer, ReleaseBuffer(), and IndexFetchHeapData::xs_cbuf.

Referenced by heapam_index_fetch_end(), and SampleHeapTupleVisible().

91 {
92  IndexFetchHeapData *hscan = (IndexFetchHeapData *) scan;
93 
94  if (BufferIsValid(hscan->xs_cbuf))
95  {
96  ReleaseBuffer(hscan->xs_cbuf);
97  hscan->xs_cbuf = InvalidBuffer;
98  }
99 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3772
Buffer xs_cbuf
Definition: heapam.h:88
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123

◆ heapam_index_fetch_tuple()

static bool heapam_index_fetch_tuple ( struct IndexFetchTableData scan,
ItemPointer  tid,
Snapshot  snapshot,
TupleTableSlot slot,
bool call_again,
bool all_dead 
)
static

Definition at line 112 of file heapam_handler.c.

References Assert, BufferHeapTupleTableSlot::base, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, ExecStoreBufferHeapTuple(), heap_hot_search_buffer(), heap_page_prune_opt(), IsMVCCSnapshot, ItemPointerGetBlockNumber, LockBuffer(), IndexFetchTableData::rel, RelationGetRelid, ReleaseAndReadBuffer(), HeapTupleData::t_self, TTS_IS_BUFFERTUPLE, TupleTableSlot::tts_tableOid, HeapTupleTableSlot::tupdata, IndexFetchHeapData::xs_base, and IndexFetchHeapData::xs_cbuf.

Referenced by SampleHeapTupleVisible().

117 {
118  IndexFetchHeapData *hscan = (IndexFetchHeapData *) scan;
120  bool got_heap_tuple;
121 
122  Assert(TTS_IS_BUFFERTUPLE(slot));
123 
124  /* We can skip the buffer-switching logic if we're in mid-HOT chain. */
125  if (!*call_again)
126  {
127  /* Switch to correct buffer if we don't have it already */
128  Buffer prev_buf = hscan->xs_cbuf;
129 
130  hscan->xs_cbuf = ReleaseAndReadBuffer(hscan->xs_cbuf,
131  hscan->xs_base.rel,
133 
134  /*
135  * Prune page, but only if we weren't already on this page
136  */
137  if (prev_buf != hscan->xs_cbuf)
138  heap_page_prune_opt(hscan->xs_base.rel, hscan->xs_cbuf);
139  }
140 
141  /* Obtain share-lock on the buffer so we can examine visibility */
143  got_heap_tuple = heap_hot_search_buffer(tid,
144  hscan->xs_base.rel,
145  hscan->xs_cbuf,
146  snapshot,
147  &bslot->base.tupdata,
148  all_dead,
149  !*call_again);
150  bslot->base.tupdata.t_self = *tid;
152 
153  if (got_heap_tuple)
154  {
155  /*
156  * Only in a non-MVCC snapshot can more than one member of the HOT
157  * chain be visible.
158  */
159  *call_again = !IsMVCCSnapshot(snapshot);
160 
161  slot->tts_tableOid = RelationGetRelid(scan->rel);
162  ExecStoreBufferHeapTuple(&bslot->base.tupdata, slot, hscan->xs_cbuf);
163  }
164  else
165  {
166  /* We've reached the end of the HOT chain. */
167  *call_again = false;
168  }
169 
170  return got_heap_tuple;
171 }
Oid tts_tableOid
Definition: tuptable.h:131
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
bool heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
Definition: heapam.c:1710
ItemPointerData t_self
Definition: htup.h:65
Buffer xs_cbuf
Definition: heapam.h:88
#define TTS_IS_BUFFERTUPLE(slot)
Definition: tuptable.h:231
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4011
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1392
#define IsMVCCSnapshot(snapshot)
Definition: snapmgr.h:96
#define Assert(condition)
Definition: c.h:804
Buffer ReleaseAndReadBuffer(Buffer buffer, Relation relation, BlockNumber blockNum)
Definition: bufmgr.c:1619
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
HeapTupleTableSlot base
Definition: tuptable.h:259
void heap_page_prune_opt(Relation relation, Buffer buffer)
Definition: pruneheap.c:87
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
HeapTupleData tupdata
Definition: tuptable.h:253
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:477
IndexFetchTableData xs_base
Definition: heapam.h:86

◆ heapam_index_validate_scan()

static void heapam_index_validate_scan ( Relation  heapRelation,
Relation  indexRelation,
IndexInfo indexInfo,
Snapshot  snapshot,
ValidateIndexState state 
)
static

Definition at line 1732 of file heapam_handler.c.

References Assert, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage, CHECK_FOR_INTERRUPTS, CreateExecutorState(), DatumGetInt64, DatumGetPointer, ExprContext::ecxt_per_tuple_memory, ExprContext::ecxt_scantuple, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg_internal(), ERROR, ExecDropSingleTupleTableSlot(), ExecPrepareQual(), ExecQual(), ExecStoreHeapTuple(), FormIndexDatum(), ForwardScanDirection, FreeExecutorState(), GetPerTupleExprContext, heap_get_root_tuples(), heap_getnext(), HeapTupleIsHeapOnly, ValidateIndexState::htups, IndexInfo::ii_ExpressionsState, IndexInfo::ii_Predicate, IndexInfo::ii_PredicateState, IndexInfo::ii_Unique, index_insert(), INDEX_MAX_KEYS, InvalidBlockNumber, ItemPointerCompare(), ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, ItemPointerSetOffsetNumber, itemptr_decode(), LockBuffer(), MakeSingleTupleTableSlot(), MaxHeapTuplesPerPage, MemoryContextReset(), NIL, OffsetNumberIsValid, OidIsValid, pfree(), pgstat_progress_update_param(), PROGRESS_SCAN_BLOCKS_DONE, PROGRESS_SCAN_BLOCKS_TOTAL, RelationData::rd_rel, RelationGetDescr, RelationGetRelationName, HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_nblocks, HeapTupleData::t_self, table_beginscan_strat(), table_endscan(), TTSOpsHeapTuple, ValidateIndexState::tuplesort, tuplesort_getdatum(), ValidateIndexState::tups_inserted, UNIQUE_CHECK_NO, UNIQUE_CHECK_YES, and values.

Referenced by SampleHeapTupleVisible().

1737 {
1738  TableScanDesc scan;
1739  HeapScanDesc hscan;
1740  HeapTuple heapTuple;
1742  bool isnull[INDEX_MAX_KEYS];
1743  ExprState *predicate;
1744  TupleTableSlot *slot;
1745  EState *estate;
1746  ExprContext *econtext;
1747  BlockNumber root_blkno = InvalidBlockNumber;
1748  OffsetNumber root_offsets[MaxHeapTuplesPerPage];
1749  bool in_index[MaxHeapTuplesPerPage];
1750  BlockNumber previous_blkno = InvalidBlockNumber;
1751 
1752  /* state variables for the merge */
1753  ItemPointer indexcursor = NULL;
1754  ItemPointerData decoded;
1755  bool tuplesort_empty = false;
1756 
1757  /*
1758  * sanity checks
1759  */
1760  Assert(OidIsValid(indexRelation->rd_rel->relam));
1761 
1762  /*
1763  * Need an EState for evaluation of index expressions and partial-index
1764  * predicates. Also a slot to hold the current tuple.
1765  */
1766  estate = CreateExecutorState();
1767  econtext = GetPerTupleExprContext(estate);
1768  slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRelation),
1769  &TTSOpsHeapTuple);
1770 
1771  /* Arrange for econtext's scan tuple to be the tuple under test */
1772  econtext->ecxt_scantuple = slot;
1773 
1774  /* Set up execution state for predicate, if any. */
1775  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
1776 
1777  /*
1778  * Prepare for scan of the base relation. We need just those tuples
1779  * satisfying the passed-in reference snapshot. We must disable syncscan
1780  * here, because it's critical that we read from block zero forward to
1781  * match the sorted TIDs.
1782  */
1783  scan = table_beginscan_strat(heapRelation, /* relation */
1784  snapshot, /* snapshot */
1785  0, /* number of keys */
1786  NULL, /* scan key */
1787  true, /* buffer access strategy OK */
1788  false); /* syncscan not OK */
1789  hscan = (HeapScanDesc) scan;
1790 
1792  hscan->rs_nblocks);
1793 
1794  /*
1795  * Scan all tuples matching the snapshot.
1796  */
1797  while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1798  {
1799  ItemPointer heapcursor = &heapTuple->t_self;
1800  ItemPointerData rootTuple;
1801  OffsetNumber root_offnum;
1802 
1804 
1805  state->htups += 1;
1806 
1807  if ((previous_blkno == InvalidBlockNumber) ||
1808  (hscan->rs_cblock != previous_blkno))
1809  {
1811  hscan->rs_cblock);
1812  previous_blkno = hscan->rs_cblock;
1813  }
1814 
1815  /*
1816  * As commented in table_index_build_scan, we should index heap-only
1817  * tuples under the TIDs of their root tuples; so when we advance onto
1818  * a new heap page, build a map of root item offsets on the page.
1819  *
1820  * This complicates merging against the tuplesort output: we will
1821  * visit the live tuples in order by their offsets, but the root
1822  * offsets that we need to compare against the index contents might be
1823  * ordered differently. So we might have to "look back" within the
1824  * tuplesort output, but only within the current page. We handle that
1825  * by keeping a bool array in_index[] showing all the
1826  * already-passed-over tuplesort output TIDs of the current page. We
1827  * clear that array here, when advancing onto a new heap page.
1828  */
1829  if (hscan->rs_cblock != root_blkno)
1830  {
1831  Page page = BufferGetPage(hscan->rs_cbuf);
1832 
1834  heap_get_root_tuples(page, root_offsets);
1836 
1837  memset(in_index, 0, sizeof(in_index));
1838 
1839  root_blkno = hscan->rs_cblock;
1840  }
1841 
1842  /* Convert actual tuple TID to root TID */
1843  rootTuple = *heapcursor;
1844  root_offnum = ItemPointerGetOffsetNumber(heapcursor);
1845 
1846  if (HeapTupleIsHeapOnly(heapTuple))
1847  {
1848  root_offnum = root_offsets[root_offnum - 1];
1849  if (!OffsetNumberIsValid(root_offnum))
1850  ereport(ERROR,
1852  errmsg_internal("failed to find parent tuple for heap-only tuple at (%u,%u) in table \"%s\"",
1853  ItemPointerGetBlockNumber(heapcursor),
1854  ItemPointerGetOffsetNumber(heapcursor),
1855  RelationGetRelationName(heapRelation))));
1856  ItemPointerSetOffsetNumber(&rootTuple, root_offnum);
1857  }
1858 
1859  /*
1860  * "merge" by skipping through the index tuples until we find or pass
1861  * the current root tuple.
1862  */
1863  while (!tuplesort_empty &&
1864  (!indexcursor ||
1865  ItemPointerCompare(indexcursor, &rootTuple) < 0))
1866  {
1867  Datum ts_val;
1868  bool ts_isnull;
1869 
1870  if (indexcursor)
1871  {
1872  /*
1873  * Remember index items seen earlier on the current heap page
1874  */
1875  if (ItemPointerGetBlockNumber(indexcursor) == root_blkno)
1876  in_index[ItemPointerGetOffsetNumber(indexcursor) - 1] = true;
1877  }
1878 
1879  tuplesort_empty = !tuplesort_getdatum(state->tuplesort, true,
1880  &ts_val, &ts_isnull, NULL);
1881  Assert(tuplesort_empty || !ts_isnull);
1882  if (!tuplesort_empty)
1883  {
1884  itemptr_decode(&decoded, DatumGetInt64(ts_val));
1885  indexcursor = &decoded;
1886 
1887  /* If int8 is pass-by-ref, free (encoded) TID Datum memory */
1888 #ifndef USE_FLOAT8_BYVAL
1889  pfree(DatumGetPointer(ts_val));
1890 #endif
1891  }
1892  else
1893  {
1894  /* Be tidy */
1895  indexcursor = NULL;
1896  }
1897  }
1898 
1899  /*
1900  * If the tuplesort has overshot *and* we didn't see a match earlier,
1901  * then this tuple is missing from the index, so insert it.
1902  */
1903  if ((tuplesort_empty ||
1904  ItemPointerCompare(indexcursor, &rootTuple) > 0) &&
1905  !in_index[root_offnum - 1])
1906  {
1908 
1909  /* Set up for predicate or expression evaluation */
1910  ExecStoreHeapTuple(heapTuple, slot, false);
1911 
1912  /*
1913  * In a partial index, discard tuples that don't satisfy the
1914  * predicate.
1915  */
1916  if (predicate != NULL)
1917  {
1918  if (!ExecQual(predicate, econtext))
1919  continue;
1920  }
1921 
1922  /*
1923  * For the current heap tuple, extract all the attributes we use
1924  * in this index, and note which are null. This also performs
1925  * evaluation of any expressions needed.
1926  */
1927  FormIndexDatum(indexInfo,
1928  slot,
1929  estate,
1930  values,
1931  isnull);
1932 
1933  /*
1934  * You'd think we should go ahead and build the index tuple here,
1935  * but some index AMs want to do further processing on the data
1936  * first. So pass the values[] and isnull[] arrays, instead.
1937  */
1938 
1939  /*
1940  * If the tuple is already committed dead, you might think we
1941  * could suppress uniqueness checking, but this is no longer true
1942  * in the presence of HOT, because the insert is actually a proxy
1943  * for a uniqueness check on the whole HOT-chain. That is, the
1944  * tuple we have here could be dead because it was already
1945  * HOT-updated, and if so the updating transaction will not have
1946  * thought it should insert index entries. The index AM will
1947  * check the whole HOT-chain and correctly detect a conflict if
1948  * there is one.
1949  */
1950 
1951  index_insert(indexRelation,
1952  values,
1953  isnull,
1954  &rootTuple,
1955  heapRelation,
1956  indexInfo->ii_Unique ?
1958  false,
1959  indexInfo);
1960 
1961  state->tups_inserted += 1;
1962  }
1963  }
1964 
1965  table_endscan(scan);
1966 
1968 
1969  FreeExecutorState(estate);
1970 
1971  /* These may have been pointing to the now-gone estate */
1972  indexInfo->ii_ExpressionsState = NIL;
1973  indexInfo->ii_PredicateState = NULL;
1974 }
int32 ItemPointerCompare(ItemPointer arg1, ItemPointer arg2)
Definition: itemptr.c:52
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2662
#define NIL
Definition: pg_list.h:65
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
bool tuplesort_getdatum(Tuplesortstate *state, bool forward, Datum *val, bool *isNull, Datum *abbrev)
Definition: tuplesort.c:2494
BlockNumber rs_cblock
Definition: heapam.h:59
List * ii_Predicate
Definition: execnodes.h:163
#define RelationGetDescr(relation)
Definition: rel.h:503
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
ExprState * ii_PredicateState
Definition: execnodes.h:164
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:234
#define MaxHeapTuplesPerPage
Definition: htup_details.h:573
int errcode(int sqlerrcode)
Definition: elog.c:698
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:109
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:396
#define OidIsValid(objectId)
Definition: c.h:710
static TableScanDesc table_beginscan_strat(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key, bool allow_strat, bool allow_sync)
Definition: tableam.h:907
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
uint16 OffsetNumber
Definition: off.h:24
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define GetPerTupleExprContext(estate)
Definition: executor.h:533
List * ii_ExpressionsState
Definition: execnodes.h:162
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define DatumGetInt64(X)
Definition: postgres.h:651
Tuplesortstate * tuplesort
Definition: index.h:49
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
#define RelationGetRelationName(relation)
Definition: rel.h:511
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:774
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
void heap_get_root_tuples(Page page, OffsetNumber *root_offsets)
Definition: pruneheap.c:900
EState * CreateExecutorState(void)
Definition: execUtils.c:90
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:47
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
uintptr_t Datum
Definition: postgres.h:411
BlockNumber rs_nblocks
Definition: heapam.h:52
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4011
static void itemptr_decode(ItemPointer itemptr, int64 encoded)
Definition: index.h:206
#define ereport(elevel,...)
Definition: elog.h:157
Buffer rs_cbuf
Definition: heapam.h:60
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
bool ii_Unique
Definition: execnodes.h:172
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:684
#define Assert(condition)
Definition: c.h:804
void pgstat_progress_update_param(int index, int64 val)
double tups_inserted
Definition: index.h:51
#define INDEX_MAX_KEYS
#define InvalidBlockNumber
Definition: block.h:33
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:226
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:119
#define DatumGetPointer(X)
Definition: postgres.h:593
double htups
Definition: index.h:51
#define ItemPointerSetOffsetNumber(pointer, offsetNumber)
Definition: itemptr.h:148
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
static Datum values[MAXATTR]
Definition: bootstrap.c:166
#define OffsetNumberIsValid(offsetNumber)
Definition: off.h:39
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:84
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
bool index_insert(Relation indexRelation, Datum *values, bool *isnull, ItemPointer heap_t_ctid, Relation heapRelation, IndexUniqueCheck checkUnique, bool indexUnchanged, IndexInfo *indexInfo)
Definition: indexam.c:176
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1352
Pointer Page
Definition: bufpage.h:78

◆ heapam_relation_copy_data()

static void heapam_relation_copy_data ( Relation  rel,
const RelFileNode newrnode 
)
static

Definition at line 623 of file heapam_handler.c.

References FlushRelationBuffers(), INIT_FORKNUM, log_smgrcreate(), MAIN_FORKNUM, MAX_FORKNUM, RelationData::rd_backend, RelationData::rd_rel, RelationCopyStorage(), RelationCreateStorage(), RelationDropStorage(), RelationGetSmgr(), RelationIsPermanent, smgrclose(), smgrcreate(), smgrexists(), and smgropen().

Referenced by SampleHeapTupleVisible().

624 {
625  SMgrRelation dstrel;
626 
627  dstrel = smgropen(*newrnode, rel->rd_backend);
628 
629  /*
630  * Since we copy the file directly without looking at the shared buffers,
631  * we'd better first flush out any pages of the source relation that are
632  * in shared buffers. We assume no new changes will be made while we are
633  * holding exclusive lock on the rel.
634  */
636 
637  /*
638  * Create and copy all forks of the relation, and schedule unlinking of
639  * old physical files.
640  *
641  * NOTE: any conflict in relfilenode value will be caught in
642  * RelationCreateStorage().
643  */
644  RelationCreateStorage(*newrnode, rel->rd_rel->relpersistence);
645 
646  /* copy main fork */
648  rel->rd_rel->relpersistence);
649 
650  /* copy those extra forks that exist */
651  for (ForkNumber forkNum = MAIN_FORKNUM + 1;
652  forkNum <= MAX_FORKNUM; forkNum++)
653  {
654  if (smgrexists(RelationGetSmgr(rel), forkNum))
655  {
656  smgrcreate(dstrel, forkNum, false);
657 
658  /*
659  * WAL log creation if the relation is persistent, or this is the
660  * init fork of an unlogged relation.
661  */
662  if (RelationIsPermanent(rel) ||
663  (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
664  forkNum == INIT_FORKNUM))
665  log_smgrcreate(newrnode, forkNum);
666  RelationCopyStorage(RelationGetSmgr(rel), dstrel, forkNum,
667  rel->rd_rel->relpersistence);
668  }
669  }
670 
671 
672  /* drop old relation, and close new one */
673  RelationDropStorage(rel);
674  smgrclose(dstrel);
675 }
#define RelationIsPermanent(relation)
Definition: rel.h:590
void smgrclose(SMgrRelation reln)
Definition: smgr.c:256
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition: smgr.c:333
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:247
Form_pg_class rd_rel
Definition: rel.h:109
SMgrRelation RelationCreateStorage(RelFileNode rnode, char relpersistence)
Definition: storage.c:118
SMgrRelation smgropen(RelFileNode rnode, BackendId backend)
Definition: smgr.c:146
ForkNumber
Definition: relpath.h:40
void RelationDropStorage(Relation rel)
Definition: storage.c:195
void RelationCopyStorage(SMgrRelation src, SMgrRelation dst, ForkNumber forkNum, char relpersistence)
Definition: storage.c:414
BackendId rd_backend
Definition: rel.h:59
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:544
void FlushRelationBuffers(Relation rel)
Definition: bufmgr.c:3516
#define MAX_FORKNUM
Definition: relpath.h:55
void log_smgrcreate(const RelFileNode *rnode, ForkNumber forkNum)
Definition: storage.c:175

◆ heapam_relation_copy_for_cluster()

static void heapam_relation_copy_for_cluster ( Relation  OldHeap,
Relation  NewHeap,
Relation  OldIndex,
bool  use_sort,
TransactionId  OldestXmin,
TransactionId xid_cutoff,
MultiXactId multi_cutoff,
double *  num_tuples,
double *  tups_vacuumed,
double *  tups_recently_dead 
)
static

Definition at line 678 of file heapam_handler.c.

References Assert, begin_heap_rewrite(), buf, BufferHeapTupleTableSlot::buffer, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, CHECK_FOR_INTERRUPTS, elog, end_heap_rewrite(), ERROR, ExecDropSingleTupleTableSlot(), ExecFetchSlotHeapTuple(), ForwardScanDirection, HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleSatisfiesVacuum(), index_beginscan(), index_endscan(), index_getnext_slot(), index_rescan(), InvalidBlockNumber, IsSystemRelation(), LockBuffer(), maintenance_work_mem, TupleDescData::natts, palloc(), pfree(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PROGRESS_CLUSTER_HEAP_BLKS_SCANNED, PROGRESS_CLUSTER_HEAP_TUPLES_SCANNED, PROGRESS_CLUSTER_HEAP_TUPLES_WRITTEN, PROGRESS_CLUSTER_INDEX_RELID, PROGRESS_CLUSTER_PHASE, PROGRESS_CLUSTER_PHASE_INDEX_SCAN_HEAP, PROGRESS_CLUSTER_PHASE_SEQ_SCAN_HEAP, PROGRESS_CLUSTER_PHASE_SORT_TUPLES, PROGRESS_CLUSTER_PHASE_WRITE_NEW_HEAP, PROGRESS_CLUSTER_TOTAL_HEAP_BLKS, reform_and_rewrite_tuple(), RelationGetDescr, RelationGetRelationName, RelationGetRelid, RelationGetTargetBlock, rewrite_heap_dead_tuple(), HeapScanDescData::rs_cblock, HeapScanDescData::rs_nblocks, HeapScanDescData::rs_startblock, SnapshotAny, HeapTupleData::t_data, table_beginscan(), table_endscan(), table_scan_getnextslot(), table_slot_create(), TransactionIdIsCurrentTransactionId(), tuplesort_begin_cluster(), tuplesort_end(), tuplesort_getheaptuple(), tuplesort_performsort(), tuplesort_putheaptuple(), values, WARNING, and IndexScanDescData::xs_recheck.

Referenced by SampleHeapTupleVisible().

686 {
687  RewriteState rwstate;
688  IndexScanDesc indexScan;
689  TableScanDesc tableScan;
690  HeapScanDesc heapScan;
691  bool is_system_catalog;
692  Tuplesortstate *tuplesort;
693  TupleDesc oldTupDesc = RelationGetDescr(OldHeap);
694  TupleDesc newTupDesc = RelationGetDescr(NewHeap);
695  TupleTableSlot *slot;
696  int natts;
697  Datum *values;
698  bool *isnull;
700  BlockNumber prev_cblock = InvalidBlockNumber;
701 
702  /* Remember if it's a system catalog */
703  is_system_catalog = IsSystemRelation(OldHeap);
704 
705  /*
706  * Valid smgr_targblock implies something already wrote to the relation.
707  * This may be harmless, but this function hasn't planned for it.
708  */
710 
711  /* Preallocate values/isnull arrays */
712  natts = newTupDesc->natts;
713  values = (Datum *) palloc(natts * sizeof(Datum));
714  isnull = (bool *) palloc(natts * sizeof(bool));
715 
716  /* Initialize the rewrite operation */
717  rwstate = begin_heap_rewrite(OldHeap, NewHeap, OldestXmin, *xid_cutoff,
718  *multi_cutoff);
719 
720 
721  /* Set up sorting if wanted */
722  if (use_sort)
723  tuplesort = tuplesort_begin_cluster(oldTupDesc, OldIndex,
725  NULL, false);
726  else
727  tuplesort = NULL;
728 
729  /*
730  * Prepare to scan the OldHeap. To ensure we see recently-dead tuples
731  * that still need to be copied, we scan with SnapshotAny and use
732  * HeapTupleSatisfiesVacuum for the visibility test.
733  */
734  if (OldIndex != NULL && !use_sort)
735  {
736  const int ci_index[] = {
739  };
740  int64 ci_val[2];
741 
742  /* Set phase and OIDOldIndex to columns */
744  ci_val[1] = RelationGetRelid(OldIndex);
745  pgstat_progress_update_multi_param(2, ci_index, ci_val);
746 
747  tableScan = NULL;
748  heapScan = NULL;
749  indexScan = index_beginscan(OldHeap, OldIndex, SnapshotAny, 0, 0);
750  index_rescan(indexScan, NULL, 0, NULL, 0);
751  }
752  else
753  {
754  /* In scan-and-sort mode and also VACUUM FULL, set phase */
757 
758  tableScan = table_beginscan(OldHeap, SnapshotAny, 0, (ScanKey) NULL);
759  heapScan = (HeapScanDesc) tableScan;
760  indexScan = NULL;
761 
762  /* Set total heap blocks */
764  heapScan->rs_nblocks);
765  }
766 
767  slot = table_slot_create(OldHeap, NULL);
768  hslot = (BufferHeapTupleTableSlot *) slot;
769 
770  /*
771  * Scan through the OldHeap, either in OldIndex order or sequentially;
772  * copy each tuple into the NewHeap, or transiently to the tuplesort
773  * module. Note that we don't bother sorting dead tuples (they won't get
774  * to the new table anyway).
775  */
776  for (;;)
777  {
778  HeapTuple tuple;
779  Buffer buf;
780  bool isdead;
781 
783 
784  if (indexScan != NULL)
785  {
786  if (!index_getnext_slot(indexScan, ForwardScanDirection, slot))
787  break;
788 
789  /* Since we used no scan keys, should never need to recheck */
790  if (indexScan->xs_recheck)
791  elog(ERROR, "CLUSTER does not support lossy index conditions");
792  }
793  else
794  {
795  if (!table_scan_getnextslot(tableScan, ForwardScanDirection, slot))
796  {
797  /*
798  * If the last pages of the scan were empty, we would go to
799  * the next phase while heap_blks_scanned != heap_blks_total.
800  * Instead, to ensure that heap_blks_scanned is equivalent to
801  * total_heap_blks after the table scan phase, this parameter
802  * is manually updated to the correct value when the table
803  * scan finishes.
804  */
806  heapScan->rs_nblocks);
807  break;
808  }
809 
810  /*
811  * In scan-and-sort mode and also VACUUM FULL, set heap blocks
812  * scanned
813  *
814  * Note that heapScan may start at an offset and wrap around, i.e.
815  * rs_startblock may be >0, and rs_cblock may end with a number
816  * below rs_startblock. To prevent showing this wraparound to the
817  * user, we offset rs_cblock by rs_startblock (modulo rs_nblocks).
818  */
819  if (prev_cblock != heapScan->rs_cblock)
820  {
822  (heapScan->rs_cblock +
823  heapScan->rs_nblocks -
824  heapScan->rs_startblock
825  ) % heapScan->rs_nblocks + 1);
826  prev_cblock = heapScan->rs_cblock;
827  }
828  }
829 
830  tuple = ExecFetchSlotHeapTuple(slot, false, NULL);
831  buf = hslot->buffer;
832 
834 
835  switch (HeapTupleSatisfiesVacuum(tuple, OldestXmin, buf))
836  {
837  case HEAPTUPLE_DEAD:
838  /* Definitely dead */
839  isdead = true;
840  break;
842  *tups_recently_dead += 1;
843  /* fall through */
844  case HEAPTUPLE_LIVE:
845  /* Live or recently dead, must copy it */
846  isdead = false;
847  break;
849 
850  /*
851  * Since we hold exclusive lock on the relation, normally the
852  * only way to see this is if it was inserted earlier in our
853  * own transaction. However, it can happen in system
854  * catalogs, since we tend to release write lock before commit
855  * there. Give a warning if neither case applies; but in any
856  * case we had better copy it.
857  */
858  if (!is_system_catalog &&
860  elog(WARNING, "concurrent insert in progress within table \"%s\"",
861  RelationGetRelationName(OldHeap));
862  /* treat as live */
863  isdead = false;
864  break;
866 
867  /*
868  * Similar situation to INSERT_IN_PROGRESS case.
869  */
870  if (!is_system_catalog &&
872  elog(WARNING, "concurrent delete in progress within table \"%s\"",
873  RelationGetRelationName(OldHeap));
874  /* treat as recently dead */
875  *tups_recently_dead += 1;
876  isdead = false;
877  break;
878  default:
879  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
880  isdead = false; /* keep compiler quiet */
881  break;
882  }
883 
885 
886  if (isdead)
887  {
888  *tups_vacuumed += 1;
889  /* heap rewrite module still needs to see it... */
890  if (rewrite_heap_dead_tuple(rwstate, tuple))
891  {
892  /* A previous recently-dead tuple is now known dead */
893  *tups_vacuumed += 1;
894  *tups_recently_dead -= 1;
895  }
896  continue;
897  }
898 
899  *num_tuples += 1;
900  if (tuplesort != NULL)
901  {
902  tuplesort_putheaptuple(tuplesort, tuple);
903 
904  /*
905  * In scan-and-sort mode, report increase in number of tuples
906  * scanned
907  */
909  *num_tuples);
910  }
911  else
912  {
913  const int ct_index[] = {
916  };
917  int64 ct_val[2];
918 
919  reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
920  values, isnull, rwstate);
921 
922  /*
923  * In indexscan mode and also VACUUM FULL, report increase in
924  * number of tuples scanned and written
925  */
926  ct_val[0] = *num_tuples;
927  ct_val[1] = *num_tuples;
928  pgstat_progress_update_multi_param(2, ct_index, ct_val);
929  }
930  }
931 
932  if (indexScan != NULL)
933  index_endscan(indexScan);
934  if (tableScan != NULL)
935  table_endscan(tableScan);
936  if (slot)
938 
939  /*
940  * In scan-and-sort mode, complete the sort, then read out all live tuples
941  * from the tuplestore and write them to the new relation.
942  */
943  if (tuplesort != NULL)
944  {
945  double n_tuples = 0;
946 
947  /* Report that we are now sorting tuples */
950 
951  tuplesort_performsort(tuplesort);
952 
953  /* Report that we are now writing new heap */
956 
957  for (;;)
958  {
959  HeapTuple tuple;
960 
962 
963  tuple = tuplesort_getheaptuple(tuplesort, true);
964  if (tuple == NULL)
965  break;
966 
967  n_tuples += 1;
969  OldHeap, NewHeap,
970  values, isnull,
971  rwstate);
972  /* Report n_tuples */
974  n_tuples);
975  }
976 
977  tuplesort_end(tuplesort);
978  }
979 
980  /* Write out any remaining tuples, and fsync if needed */
981  end_heap_rewrite(rwstate);
982 
983  /* Clean up */
984  pfree(values);
985  pfree(isnull);
986 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:365
#define PROGRESS_CLUSTER_PHASE_SEQ_SCAN_HEAP
Definition: progress.h:65
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
BlockNumber rs_cblock
Definition: heapam.h:59
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:2040
void end_heap_rewrite(RewriteState state)
Definition: rewriteheap.c:300
HeapTuple tuplesort_getheaptuple(Tuplesortstate *state, bool forward)
Definition: tuplesort.c:2445
bool IsSystemRelation(Relation relation)
Definition: catalog.c:74
#define PROGRESS_CLUSTER_HEAP_TUPLES_WRITTEN
Definition: progress.h:59
#define RelationGetDescr(relation)
Definition: rel.h:503
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:869
static void reform_and_rewrite_tuple(HeapTuple tuple, Relation OldHeap, Relation NewHeap, Datum *values, bool *isnull, RewriteState rwstate)
Tuplesortstate * tuplesort_begin_cluster(TupleDesc tupDesc, Relation indexRel, int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:971
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:297
#define PROGRESS_CLUSTER_INDEX_RELID
Definition: progress.h:57
#define PROGRESS_CLUSTER_PHASE_WRITE_NEW_HEAP
Definition: progress.h:68
uint32 BlockNumber
Definition: block.h:31
static bool table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:1032
#define RelationGetTargetBlock(relation)
Definition: rel.h:574
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
HeapTupleHeader t_data
Definition: htup.h:68
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
static TableScanDesc table_beginscan(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key)
Definition: tableam.h:883
#define PROGRESS_CLUSTER_PHASE_SORT_TUPLES
Definition: progress.h:67
static char * buf
Definition: pg_test_fsync.c:68
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
#define PROGRESS_CLUSTER_HEAP_TUPLES_SCANNED
Definition: progress.h:58
#define RelationGetRelationName(relation)
Definition: rel.h:511
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:323
BlockNumber rs_startblock
Definition: heapam.h:53
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
#define WARNING
Definition: elog.h:40
uintptr_t Datum
Definition: postgres.h:411
BlockNumber rs_nblocks
Definition: heapam.h:52
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4011
int maintenance_work_mem
Definition: globals.c:126
#define Assert(condition)
Definition: c.h:804
#define PROGRESS_CLUSTER_PHASE_INDEX_SCAN_HEAP
Definition: progress.h:66
void pgstat_progress_update_param(int index, int64 val)
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:313
#define InvalidBlockNumber
Definition: block.h:33
bool index_getnext_slot(IndexScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition: indexam.c:616
#define SnapshotAny
Definition: snapmgr.h:67
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
static Datum values[MAXATTR]
Definition: bootstrap.c:166
bool rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
Definition: rewriteheap.c:563
void * palloc(Size size)
Definition: mcxt.c:1062
#define elog(elevel,...)
Definition: elog.h:232
void tuplesort_putheaptuple(Tuplesortstate *state, HeapTuple tup)
Definition: tuplesort.c:1706
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
#define PROGRESS_CLUSTER_HEAP_BLKS_SCANNED
Definition: progress.h:61
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
#define PROGRESS_CLUSTER_TOTAL_HEAP_BLKS
Definition: progress.h:60
RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap, TransactionId oldest_xmin, TransactionId freeze_xid, MultiXactId cutoff_multi)
Definition: rewriteheap.c:237
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1464
#define PROGRESS_CLUSTER_PHASE
Definition: progress.h:56
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:477
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:205

◆ heapam_relation_needs_toast_table()

static bool heapam_relation_needs_toast_table ( Relation  rel)
static

Definition at line 2028 of file heapam_handler.c.

References att_align_nominal, BITMAPLEN, i, MAXALIGN, TupleDescData::natts, RelationData::rd_att, SizeofHeapTupleHeader, TOAST_TUPLE_THRESHOLD, TupleDescAttr, and type_maximum_size().

Referenced by SampleHeapTupleVisible().

2029 {
2030  int32 data_length = 0;
2031  bool maxlength_unknown = false;
2032  bool has_toastable_attrs = false;
2033  TupleDesc tupdesc = rel->rd_att;
2034  int32 tuple_length;
2035  int i;
2036 
2037  for (i = 0; i < tupdesc->natts; i++)
2038  {
2039  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2040 
2041  if (att->attisdropped)
2042  continue;
2043  data_length = att_align_nominal(data_length, att->attalign);
2044  if (att->attlen > 0)
2045  {
2046  /* Fixed-length types are never toastable */
2047  data_length += att->attlen;
2048  }
2049  else
2050  {
2051  int32 maxlen = type_maximum_size(att->atttypid,
2052  att->atttypmod);
2053 
2054  if (maxlen < 0)
2055  maxlength_unknown = true;
2056  else
2057  data_length += maxlen;
2058  if (att->attstorage != TYPSTORAGE_PLAIN)
2059  has_toastable_attrs = true;
2060  }
2061  }
2062  if (!has_toastable_attrs)
2063  return false; /* nothing to toast? */
2064  if (maxlength_unknown)
2065  return true; /* any unlimited-length attrs? */
2066  tuple_length = MAXALIGN(SizeofHeapTupleHeader +
2067  BITMAPLEN(tupdesc->natts)) +
2068  MAXALIGN(data_length);
2069  return (tuple_length > TOAST_TUPLE_THRESHOLD);
2070 }
#define SizeofHeapTupleHeader
Definition: htup_details.h:184
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:148
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define BITMAPLEN(NATTS)
Definition: htup_details.h:546
signed int int32
Definition: c.h:429
int32 type_maximum_size(Oid type_oid, int32 typemod)
Definition: format_type.c:408
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define TOAST_TUPLE_THRESHOLD
Definition: heaptoast.h:48
TupleDesc rd_att
Definition: rel.h:110
#define MAXALIGN(LEN)
Definition: c.h:757
int i

◆ heapam_relation_nontransactional_truncate()

static void heapam_relation_nontransactional_truncate ( Relation  rel)
static

Definition at line 617 of file heapam_handler.c.

References RelationTruncate().

Referenced by SampleHeapTupleVisible().

618 {
619  RelationTruncate(rel, 0);
620 }
void RelationTruncate(Relation rel, BlockNumber nblocks)
Definition: storage.c:277

◆ heapam_relation_set_new_filenode()

static void heapam_relation_set_new_filenode ( Relation  rel,
const RelFileNode newrnode,
char  persistence,
TransactionId freezeXid,
MultiXactId minmulti 
)
static

Definition at line 567 of file heapam_handler.c.

References Assert, GetOldestMultiXactId(), INIT_FORKNUM, log_smgrcreate(), RelationData::rd_rel, RecentXmin, RelationCreateStorage(), smgrclose(), smgrcreate(), and smgrimmedsync().

Referenced by SampleHeapTupleVisible().

572 {
573  SMgrRelation srel;
574 
575  /*
576  * Initialize to the minimum XID that could put tuples in the table. We
577  * know that no xacts older than RecentXmin are still running, so that
578  * will do.
579  */
580  *freezeXid = RecentXmin;
581 
582  /*
583  * Similarly, initialize the minimum Multixact to the first value that
584  * could possibly be stored in tuples in the table. Running transactions
585  * could reuse values from their local cache, so we are careful to
586  * consider all currently running multis.
587  *
588  * XXX this could be refined further, but is it worth the hassle?
589  */
590  *minmulti = GetOldestMultiXactId();
591 
592  srel = RelationCreateStorage(*newrnode, persistence);
593 
594  /*
595  * If required, set up an init fork for an unlogged table so that it can
596  * be correctly reinitialized on restart. An immediate sync is required
597  * even if the page has been logged, because the write did not go through
598  * shared_buffers and therefore a concurrent checkpoint may have moved the
599  * redo pointer past our xlog record. Recovery may as well remove it
600  * while replaying, for example, XLOG_DBASE_CREATE or XLOG_TBLSPC_CREATE
601  * record. Therefore, logging is necessary even if wal_level=minimal.
602  */
603  if (persistence == RELPERSISTENCE_UNLOGGED)
604  {
605  Assert(rel->rd_rel->relkind == RELKIND_RELATION ||
606  rel->rd_rel->relkind == RELKIND_MATVIEW ||
607  rel->rd_rel->relkind == RELKIND_TOASTVALUE);
608  smgrcreate(srel, INIT_FORKNUM, false);
609  log_smgrcreate(newrnode, INIT_FORKNUM);
611  }
612 
613  smgrclose(srel);
614 }
void smgrclose(SMgrRelation reln)
Definition: smgr.c:256
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition: smgr.c:333
TransactionId RecentXmin
Definition: snapmgr.c:113
Form_pg_class rd_rel
Definition: rel.h:109
SMgrRelation RelationCreateStorage(RelFileNode rnode, char relpersistence)
Definition: storage.c:118
MultiXactId GetOldestMultiXactId(void)
Definition: multixact.c:2506
#define Assert(condition)
Definition: c.h:804
void smgrimmedsync(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:660
void log_smgrcreate(const RelFileNode *rnode, ForkNumber forkNum)
Definition: storage.c:175

◆ heapam_relation_toast_am()

static Oid heapam_relation_toast_am ( Relation  rel)
static

Definition at line 2076 of file heapam_handler.c.

References RelationData::rd_rel.

Referenced by SampleHeapTupleVisible().

2077 {
2078  return rel->rd_rel->relam;
2079 }
Form_pg_class rd_rel
Definition: rel.h:109

◆ heapam_scan_analyze_next_block()

static bool heapam_scan_analyze_next_block ( TableScanDesc  scan,
BlockNumber  blockno,
BufferAccessStrategy  bstrategy 
)
static

Definition at line 989 of file heapam_handler.c.

References BUFFER_LOCK_SHARE, FirstOffsetNumber, LockBuffer(), MAIN_FORKNUM, RBM_NORMAL, ReadBufferExtended(), HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_cindex, and TableScanDescData::rs_rd.

Referenced by SampleHeapTupleVisible().

991 {
992  HeapScanDesc hscan = (HeapScanDesc) scan;
993 
994  /*
995  * We must maintain a pin on the target page's buffer to ensure that
996  * concurrent activity - e.g. HOT pruning - doesn't delete tuples out from
997  * under us. Hence, pin the page until we are done looking at it. We
998  * also choose to hold sharelock on the buffer throughout --- we could
999  * release and re-acquire sharelock for each tuple, but since we aren't
1000  * doing much work per tuple, the extra lock traffic is probably better
1001  * avoided.
1002  */
1003  hscan->rs_cblock = blockno;
1004  hscan->rs_cindex = FirstOffsetNumber;
1005  hscan->rs_cbuf = ReadBufferExtended(scan->rs_rd, MAIN_FORKNUM,
1006  blockno, RBM_NORMAL, bstrategy);
1008 
1009  /* in heap all blocks can contain tuples, so always return true */
1010  return true;
1011 }
BlockNumber rs_cblock
Definition: heapam.h:59
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:741
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
#define FirstOffsetNumber
Definition: off.h:27
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4011
Buffer rs_cbuf
Definition: heapam.h:60
Relation rs_rd
Definition: relscan.h:34
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97

◆ heapam_scan_analyze_next_tuple()

static bool heapam_scan_analyze_next_tuple ( TableScanDesc  scan,
TransactionId  OldestXmin,
double *  liverows,
double *  deadrows,
TupleTableSlot slot 
)
static

Definition at line 1014 of file heapam_handler.c.

References Assert, BufferHeapTupleTableSlot::base, BufferGetPage, elog, ERROR, ExecClearTuple(), ExecStoreBufferHeapTuple(), HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleSatisfiesVacuum(), InvalidBuffer, ItemIdGetLength, ItemIdIsDead, ItemIdIsNormal, ItemPointerSet, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, RelationGetRelid, HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_cindex, TableScanDescData::rs_rd, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransactionIdIsCurrentTransactionId(), TTS_IS_BUFFERTUPLE, HeapTupleTableSlot::tupdata, and UnlockReleaseBuffer().

Referenced by SampleHeapTupleVisible().

1017 {
1018  HeapScanDesc hscan = (HeapScanDesc) scan;
1019  Page targpage;
1020  OffsetNumber maxoffset;
1021  BufferHeapTupleTableSlot *hslot;
1022 
1023  Assert(TTS_IS_BUFFERTUPLE(slot));
1024 
1025  hslot = (BufferHeapTupleTableSlot *) slot;
1026  targpage = BufferGetPage(hscan->rs_cbuf);
1027  maxoffset = PageGetMaxOffsetNumber(targpage);
1028 
1029  /* Inner loop over all tuples on the selected page */
1030  for (; hscan->rs_cindex <= maxoffset; hscan->rs_cindex++)
1031  {
1032  ItemId itemid;
1033  HeapTuple targtuple = &hslot->base.tupdata;
1034  bool sample_it = false;
1035 
1036  itemid = PageGetItemId(targpage, hscan->rs_cindex);
1037 
1038  /*
1039  * We ignore unused and redirect line pointers. DEAD line pointers
1040  * should be counted as dead, because we need vacuum to run to get rid
1041  * of them. Note that this rule agrees with the way that
1042  * heap_page_prune() counts things.
1043  */
1044  if (!ItemIdIsNormal(itemid))
1045  {
1046  if (ItemIdIsDead(itemid))
1047  *deadrows += 1;
1048  continue;
1049  }
1050 
1051  ItemPointerSet(&targtuple->t_self, hscan->rs_cblock, hscan->rs_cindex);
1052 
1053  targtuple->t_tableOid = RelationGetRelid(scan->rs_rd);
1054  targtuple->t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
1055  targtuple->t_len = ItemIdGetLength(itemid);
1056 
1057  switch (HeapTupleSatisfiesVacuum(targtuple, OldestXmin,
1058  hscan->rs_cbuf))
1059  {
1060  case HEAPTUPLE_LIVE:
1061  sample_it = true;
1062  *liverows += 1;
1063  break;
1064 
1065  case HEAPTUPLE_DEAD:
1067  /* Count dead and recently-dead rows */
1068  *deadrows += 1;
1069  break;
1070 
1072 
1073  /*
1074  * Insert-in-progress rows are not counted. We assume that
1075  * when the inserting transaction commits or aborts, it will
1076  * send a stats message to increment the proper count. This
1077  * works right only if that transaction ends after we finish
1078  * analyzing the table; if things happen in the other order,
1079  * its stats update will be overwritten by ours. However, the
1080  * error will be large only if the other transaction runs long
1081  * enough to insert many tuples, so assuming it will finish
1082  * after us is the safer option.
1083  *
1084  * A special case is that the inserting transaction might be
1085  * our own. In this case we should count and sample the row,
1086  * to accommodate users who load a table and analyze it in one
1087  * transaction. (pgstat_report_analyze has to adjust the
1088  * numbers we send to the stats collector to make this come
1089  * out right.)
1090  */
1092  {
1093  sample_it = true;
1094  *liverows += 1;
1095  }
1096  break;
1097 
1099 
1100  /*
1101  * We count and sample delete-in-progress rows the same as
1102  * live ones, so that the stats counters come out right if the
1103  * deleting transaction commits after us, per the same
1104  * reasoning given above.
1105  *
1106  * If the delete was done by our own transaction, however, we
1107  * must count the row as dead to make pgstat_report_analyze's
1108  * stats adjustments come out right. (Note: this works out
1109  * properly when the row was both inserted and deleted in our
1110  * xact.)
1111  *
1112  * The net effect of these choices is that we act as though an
1113  * IN_PROGRESS transaction hasn't happened yet, except if it
1114  * is our own transaction, which we assume has happened.
1115  *
1116  * This approach ensures that we behave sanely if we see both
1117  * the pre-image and post-image rows for a row being updated
1118  * by a concurrent transaction: we will sample the pre-image
1119  * but not the post-image. We also get sane results if the
1120  * concurrent transaction never commits.
1121  */
1123  *deadrows += 1;
1124  else
1125  {
1126  sample_it = true;
1127  *liverows += 1;
1128  }
1129  break;
1130 
1131  default:
1132  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1133  break;
1134  }
1135 
1136  if (sample_it)
1137  {
1138  ExecStoreBufferHeapTuple(targtuple, slot, hscan->rs_cbuf);
1139  hscan->rs_cindex++;
1140 
1141  /* note that we leave the buffer locked here! */
1142  return true;
1143  }
1144  }
1145 
1146  /* Now release the lock and pin on the page */
1147  UnlockReleaseBuffer(hscan->rs_cbuf);
1148  hscan->rs_cbuf = InvalidBuffer;
1149 
1150  /* also prevent old slot contents from having pin on page */
1151  ExecClearTuple(slot);
1152 
1153  return false;
1154 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:365
BlockNumber rs_cblock
Definition: heapam.h:59
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:869
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define InvalidBuffer
Definition: buf.h:25
#define ItemIdIsDead(itemId)
Definition: itemid.h:113
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:68
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3795
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
#define TTS_IS_BUFFERTUPLE(slot)
Definition: tuptable.h:231
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1392
Buffer rs_cbuf
Definition: heapam.h:60
#define Assert(condition)
Definition: c.h:804
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:313
Relation rs_rd
Definition: relscan.h:34
#define elog(elevel,...)
Definition: elog.h:232
HeapTupleTableSlot base
Definition: tuptable.h:259
HeapTupleData tupdata
Definition: tuptable.h:253
#define RelationGetRelid(relation)
Definition: rel.h:477
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127

◆ heapam_scan_bitmap_next_block()

static bool heapam_scan_bitmap_next_block ( TableScanDesc  scan,
TBMIterateResult tbmres 
)
static

Definition at line 2110 of file heapam_handler.c.

References Assert, TBMIterateResult::blockno, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage, FirstOffsetNumber, heap_hot_search_buffer(), heap_page_prune_opt(), HeapCheckForSerializableConflictOut(), HeapTupleHeaderGetXmin, HeapTupleSatisfiesVisibility(), ItemIdGetLength, ItemIdIsNormal, ItemPointerGetOffsetNumber, ItemPointerSet, LockBuffer(), MaxHeapTuplesPerPage, TBMIterateResult::ntuples, OffsetNumberNext, TBMIterateResult::offsets, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PredicateLockTID(), RelationData::rd_id, ReleaseAndReadBuffer(), HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_cindex, HeapScanDescData::rs_nblocks, HeapScanDescData::rs_ntuples, TableScanDescData::rs_rd, TableScanDescData::rs_snapshot, HeapScanDescData::rs_vistuples, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, and HeapTupleData::t_tableOid.

Referenced by SampleHeapTupleVisible().

2112 {
2113  HeapScanDesc hscan = (HeapScanDesc) scan;
2114  BlockNumber page = tbmres->blockno;
2115  Buffer buffer;
2116  Snapshot snapshot;
2117  int ntup;
2118 
2119  hscan->rs_cindex = 0;
2120  hscan->rs_ntuples = 0;
2121 
2122  /*
2123  * Ignore any claimed entries past what we think is the end of the
2124  * relation. It may have been extended after the start of our scan (we
2125  * only hold an AccessShareLock, and it could be inserts from this
2126  * backend).
2127  */
2128  if (page >= hscan->rs_nblocks)
2129  return false;
2130 
2131  /*
2132  * Acquire pin on the target heap page, trading in any pin we held before.
2133  */
2134  hscan->rs_cbuf = ReleaseAndReadBuffer(hscan->rs_cbuf,
2135  scan->rs_rd,
2136  page);
2137  hscan->rs_cblock = page;
2138  buffer = hscan->rs_cbuf;
2139  snapshot = scan->rs_snapshot;
2140 
2141  ntup = 0;
2142 
2143  /*
2144  * Prune and repair fragmentation for the whole page, if possible.
2145  */
2146  heap_page_prune_opt(scan->rs_rd, buffer);
2147 
2148  /*
2149  * We must hold share lock on the buffer content while examining tuple
2150  * visibility. Afterwards, however, the tuples we have found to be
2151  * visible are guaranteed good as long as we hold the buffer pin.
2152  */
2153  LockBuffer(buffer, BUFFER_LOCK_SHARE);
2154 
2155  /*
2156  * We need two separate strategies for lossy and non-lossy cases.
2157  */
2158  if (tbmres->ntuples >= 0)
2159  {
2160  /*
2161  * Bitmap is non-lossy, so we just look through the offsets listed in
2162  * tbmres; but we have to follow any HOT chain starting at each such
2163  * offset.
2164  */
2165  int curslot;
2166 
2167  for (curslot = 0; curslot < tbmres->ntuples; curslot++)
2168  {
2169  OffsetNumber offnum = tbmres->offsets[curslot];
2170  ItemPointerData tid;
2171  HeapTupleData heapTuple;
2172 
2173  ItemPointerSet(&tid, page, offnum);
2174  if (heap_hot_search_buffer(&tid, scan->rs_rd, buffer, snapshot,
2175  &heapTuple, NULL, true))
2176  hscan->rs_vistuples[ntup++] = ItemPointerGetOffsetNumber(&tid);
2177  }
2178  }
2179  else
2180  {
2181  /*
2182  * Bitmap is lossy, so we must examine each line pointer on the page.
2183  * But we can ignore HOT chains, since we'll check each tuple anyway.
2184  */
2185  Page dp = (Page) BufferGetPage(buffer);
2186  OffsetNumber maxoff = PageGetMaxOffsetNumber(dp);
2187  OffsetNumber offnum;
2188 
2189  for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum))
2190  {
2191  ItemId lp;
2192  HeapTupleData loctup;
2193  bool valid;
2194 
2195  lp = PageGetItemId(dp, offnum);
2196  if (!ItemIdIsNormal(lp))
2197  continue;
2198  loctup.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
2199  loctup.t_len = ItemIdGetLength(lp);
2200  loctup.t_tableOid = scan->rs_rd->rd_id;
2201  ItemPointerSet(&loctup.t_self, page, offnum);
2202  valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
2203  if (valid)
2204  {
2205  hscan->rs_vistuples[ntup++] = offnum;
2206  PredicateLockTID(scan->rs_rd, &loctup.t_self, snapshot,
2207  HeapTupleHeaderGetXmin(loctup.t_data));
2208  }
2209  HeapCheckForSerializableConflictOut(valid, scan->rs_rd, &loctup,
2210  buffer, snapshot);
2211  }
2212  }
2213 
2214  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2215 
2216  Assert(ntup <= MaxHeapTuplesPerPage);
2217  hscan->rs_ntuples = ntup;
2218 
2219  return ntup > 0;
2220 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
BlockNumber rs_cblock
Definition: heapam.h:59
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define MaxHeapTuplesPerPage
Definition: htup_details.h:573
uint32 BlockNumber
Definition: block.h:31
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:68
BlockNumber blockno
Definition: tidbitmap.h:42
bool heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
Definition: heapam.c:1710
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
OffsetNumber offsets[FLEXIBLE_ARRAY_MEMBER]
Definition: tidbitmap.h:46
#define FirstOffsetNumber
Definition: off.h:27
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
Oid rd_id
Definition: rel.h:111
int rs_ntuples
Definition: heapam.h:76
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
BlockNumber rs_nblocks
Definition: heapam.h:52
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4011
void PredicateLockTID(Relation relation, ItemPointer tid, Snapshot snapshot, TransactionId tuple_xid)
Definition: predicate.c:2614
void HeapCheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: heapam.c:9789
Buffer rs_cbuf
Definition: heapam.h:60
#define Assert(condition)
Definition: c.h:804
OffsetNumber rs_vistuples[MaxHeapTuplesPerPage]
Definition: heapam.h:77
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:313
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
Buffer ReleaseAndReadBuffer(Buffer buffer, Relation relation, BlockNumber blockNum)
Definition: bufmgr.c:1619
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
Relation rs_rd
Definition: relscan.h:34
struct SnapshotData * rs_snapshot
Definition: relscan.h:35
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
void heap_page_prune_opt(Relation relation, Buffer buffer)
Definition: pruneheap.c:87
int Buffer
Definition: buf.h:23
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127
bool HeapTupleSatisfiesVisibility(HeapTuple tup, Snapshot snapshot, Buffer buffer)

◆ heapam_scan_bitmap_next_tuple()

static bool heapam_scan_bitmap_next_tuple ( TableScanDesc  scan,
TBMIterateResult tbmres,
TupleTableSlot slot 
)
static

Definition at line 2223 of file heapam_handler.c.

References Assert, BufferGetPage, ExecStoreBufferHeapTuple(), ItemIdGetLength, ItemIdIsNormal, ItemPointerSet, PageGetItem, PageGetItemId, pgstat_count_heap_fetch, RelationData::rd_id, HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_cindex, HeapScanDescData::rs_ctup, HeapScanDescData::rs_ntuples, TableScanDescData::rs_rd, HeapScanDescData::rs_vistuples, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, and HeapTupleData::t_tableOid.

Referenced by SampleHeapTupleVisible().

2226 {
2227  HeapScanDesc hscan = (HeapScanDesc) scan;
2228  OffsetNumber targoffset;
2229  Page dp;
2230  ItemId lp;
2231 
2232  /*
2233  * Out of range? If so, nothing more to look at on this page
2234  */
2235  if (hscan->rs_cindex < 0 || hscan->rs_cindex >= hscan->rs_ntuples)
2236  return false;
2237 
2238  targoffset = hscan->rs_vistuples[hscan->rs_cindex];
2239  dp = (Page) BufferGetPage(hscan->rs_cbuf);
2240  lp = PageGetItemId(dp, targoffset);
2241  Assert(ItemIdIsNormal(lp));
2242 
2243  hscan->rs_ctup.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
2244  hscan->rs_ctup.t_len = ItemIdGetLength(lp);
2245  hscan->rs_ctup.t_tableOid = scan->rs_rd->rd_id;
2246  ItemPointerSet(&hscan->rs_ctup.t_self, hscan->rs_cblock, targoffset);
2247 
2249 
2250  /*
2251  * Set up the result slot to point to this tuple. Note that the slot
2252  * acquires a pin on the buffer.
2253  */
2255  slot,
2256  hscan->rs_cbuf);
2257 
2258  hscan->rs_cindex++;
2259 
2260  return true;
2261 }
BlockNumber rs_cblock
Definition: heapam.h:59
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
HeapTupleData rs_ctup
Definition: heapam.h:66
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:68
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
ItemPointerData t_self
Definition: htup.h:65
#define pgstat_count_heap_fetch(rel)
Definition: pgstat.h:1035
uint32 t_len
Definition: htup.h:64
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
Oid rd_id
Definition: rel.h:111
int rs_ntuples
Definition: heapam.h:76
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1392
Buffer rs_cbuf
Definition: heapam.h:60
#define Assert(condition)
Definition: c.h:804
OffsetNumber rs_vistuples[MaxHeapTuplesPerPage]
Definition: heapam.h:77
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
Relation rs_rd
Definition: relscan.h:34
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127

◆ heapam_scan_get_blocks_done()

static BlockNumber heapam_scan_get_blocks_done ( HeapScanDesc  hscan)
static

Definition at line 1983 of file heapam_handler.c.

References ParallelBlockTableScanDescData::phs_nblocks, ParallelBlockTableScanDescData::phs_startblock, HeapScanDescData::rs_base, HeapScanDescData::rs_cblock, HeapScanDescData::rs_nblocks, TableScanDescData::rs_parallel, and HeapScanDescData::rs_startblock.

Referenced by heapam_index_build_range_scan().

1984 {
1985  ParallelBlockTableScanDesc bpscan = NULL;
1986  BlockNumber startblock;
1987  BlockNumber blocks_done;
1988 
1989  if (hscan->rs_base.rs_parallel != NULL)
1990  {
1992  startblock = bpscan->phs_startblock;
1993  }
1994  else
1995  startblock = hscan->rs_startblock;
1996 
1997  /*
1998  * Might have wrapped around the end of the relation, if startblock was
1999  * not zero.
2000  */
2001  if (hscan->rs_cblock > startblock)
2002  blocks_done = hscan->rs_cblock - startblock;
2003  else
2004  {
2005  BlockNumber nblocks;
2006 
2007  nblocks = bpscan != NULL ? bpscan->phs_nblocks : hscan->rs_nblocks;
2008  blocks_done = nblocks - startblock +
2009  hscan->rs_cblock;
2010  }
2011 
2012  return blocks_done;
2013 }
BlockNumber rs_cblock
Definition: heapam.h:59
struct ParallelBlockTableScanDescData * ParallelBlockTableScanDesc
Definition: relscan.h:85
TableScanDescData rs_base
Definition: heapam.h:49
uint32 BlockNumber
Definition: block.h:31
BlockNumber rs_startblock
Definition: heapam.h:53
BlockNumber rs_nblocks
Definition: heapam.h:52
struct ParallelTableScanDescData * rs_parallel
Definition: relscan.h:49

◆ heapam_scan_sample_next_block()

static bool heapam_scan_sample_next_block ( TableScanDesc  scan,
SampleScanState scanstate 
)
static

Definition at line 2264 of file heapam_handler.c.

References Assert, BlockNumberIsValid, BufferIsValid, heapgetpage(), InvalidBlockNumber, InvalidBuffer, TsmRoutine::NextSampleBlock, ReleaseBuffer(), HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, TableScanDescData::rs_flags, HeapScanDescData::rs_inited, HeapScanDescData::rs_nblocks, TableScanDescData::rs_rd, HeapScanDescData::rs_startblock, SO_ALLOW_SYNC, ss_report_location(), and SampleScanState::tsmroutine.

Referenced by SampleHeapTupleVisible().

2265 {
2266  HeapScanDesc hscan = (HeapScanDesc) scan;
2267  TsmRoutine *tsm = scanstate->tsmroutine;
2268  BlockNumber blockno;
2269 
2270  /* return false immediately if relation is empty */
2271  if (hscan->rs_nblocks == 0)
2272  return false;
2273 
2274  if (tsm->NextSampleBlock)
2275  {
2276  blockno = tsm->NextSampleBlock(scanstate, hscan->rs_nblocks);
2277  hscan->rs_cblock = blockno;
2278  }
2279  else
2280  {
2281  /* scanning table sequentially */
2282 
2283  if (hscan->rs_cblock == InvalidBlockNumber)
2284  {
2285  Assert(!hscan->rs_inited);
2286  blockno = hscan->rs_startblock;
2287  }
2288  else
2289  {
2290  Assert(hscan->rs_inited);
2291 
2292  blockno = hscan->rs_cblock + 1;
2293 
2294  if (blockno >= hscan->rs_nblocks)
2295  {
2296  /* wrap to beginning of rel, might not have started at 0 */
2297  blockno = 0;
2298  }
2299 
2300  /*
2301  * Report our new scan position for synchronization purposes.
2302  *
2303  * Note: we do this before checking for end of scan so that the
2304  * final state of the position hint is back at the start of the
2305  * rel. That's not strictly necessary, but otherwise when you run
2306  * the same query multiple times the starting position would shift
2307  * a little bit backwards on every invocation, which is confusing.
2308  * We don't guarantee any specific ordering in general, though.
2309  */
2310  if (scan->rs_flags & SO_ALLOW_SYNC)
2311  ss_report_location(scan->rs_rd, blockno);
2312 
2313  if (blockno == hscan->rs_startblock)
2314  {
2315  blockno = InvalidBlockNumber;
2316  }
2317  }
2318  }
2319 
2320  if (!BlockNumberIsValid(blockno))
2321  {
2322  if (BufferIsValid(hscan->rs_cbuf))
2323  ReleaseBuffer(hscan->rs_cbuf);
2324  hscan->rs_cbuf = InvalidBuffer;
2325  hscan->rs_cblock = InvalidBlockNumber;
2326  hscan->rs_inited = false;
2327 
2328  return false;
2329  }
2330 
2331  heapgetpage(scan, blockno);
2332  hscan->rs_inited = true;
2333 
2334  return true;
2335 }
BlockNumber rs_cblock
Definition: heapam.h:59
#define InvalidBuffer
Definition: buf.h:25
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3772
uint32 rs_flags
Definition: relscan.h:47
void heapgetpage(TableScanDesc sscan, BlockNumber page)
Definition: heapam.c:371
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
bool rs_inited
Definition: heapam.h:58
NextSampleBlock_function NextSampleBlock
Definition: tsmapi.h:73
BlockNumber rs_startblock
Definition: heapam.h:53
BlockNumber rs_nblocks
Definition: heapam.h:52
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
Buffer rs_cbuf
Definition: heapam.h:60
#define Assert(condition)
Definition: c.h:804
#define InvalidBlockNumber
Definition: block.h:33
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
struct TsmRoutine * tsmroutine
Definition: execnodes.h:1403
void ss_report_location(Relation rel, BlockNumber location)
Definition: syncscan.c:288
Relation rs_rd
Definition: relscan.h:34

◆ heapam_scan_sample_next_tuple()

static bool heapam_scan_sample_next_tuple ( TableScanDesc  scan,
SampleScanState scanstate,
TupleTableSlot slot 
)
static

Definition at line 2338 of file heapam_handler.c.

References Assert, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage, CHECK_FOR_INTERRUPTS, ExecClearTuple(), ExecStoreBufferHeapTuple(), HeapCheckForSerializableConflictOut(), ItemIdGetLength, ItemIdIsNormal, ItemPointerSet, LockBuffer(), TsmRoutine::NextSampleTuple, OffsetNumberIsValid, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PageIsAllVisible, pgstat_count_heap_getnext, HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_ctup, TableScanDescData::rs_flags, TableScanDescData::rs_rd, TableScanDescData::rs_snapshot, SampleHeapTupleVisible(), SO_ALLOW_PAGEMODE, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, SnapshotData::takenDuringRecovery, and SampleScanState::tsmroutine.

Referenced by SampleHeapTupleVisible().

2340 {
2341  HeapScanDesc hscan = (HeapScanDesc) scan;
2342  TsmRoutine *tsm = scanstate->tsmroutine;
2343  BlockNumber blockno = hscan->rs_cblock;
2344  bool pagemode = (scan->rs_flags & SO_ALLOW_PAGEMODE) != 0;
2345 
2346  Page page;
2347  bool all_visible;
2348  OffsetNumber maxoffset;
2349 
2350  /*
2351  * When not using pagemode, we must lock the buffer during tuple
2352  * visibility checks.
2353  */
2354  if (!pagemode)
2356 
2357  page = (Page) BufferGetPage(hscan->rs_cbuf);
2358  all_visible = PageIsAllVisible(page) &&
2360  maxoffset = PageGetMaxOffsetNumber(page);
2361 
2362  for (;;)
2363  {
2364  OffsetNumber tupoffset;
2365 
2367 
2368  /* Ask the tablesample method which tuples to check on this page. */
2369  tupoffset = tsm->NextSampleTuple(scanstate,
2370  blockno,
2371  maxoffset);
2372 
2373  if (OffsetNumberIsValid(tupoffset))
2374  {
2375  ItemId itemid;
2376  bool visible;
2377  HeapTuple tuple = &(hscan->rs_ctup);
2378 
2379  /* Skip invalid tuple pointers. */
2380  itemid = PageGetItemId(page, tupoffset);
2381  if (!ItemIdIsNormal(itemid))
2382  continue;
2383 
2384  tuple->t_data = (HeapTupleHeader) PageGetItem(page, itemid);
2385  tuple->t_len = ItemIdGetLength(itemid);
2386  ItemPointerSet(&(tuple->t_self), blockno, tupoffset);
2387 
2388 
2389  if (all_visible)
2390  visible = true;
2391  else
2392  visible = SampleHeapTupleVisible(scan, hscan->rs_cbuf,
2393  tuple, tupoffset);
2394 
2395  /* in pagemode, heapgetpage did this for us */
2396  if (!pagemode)
2397  HeapCheckForSerializableConflictOut(visible, scan->rs_rd, tuple,
2398  hscan->rs_cbuf, scan->rs_snapshot);
2399 
2400  /* Try next tuple from same page. */
2401  if (!visible)
2402  continue;
2403 
2404  /* Found visible tuple, return it. */
2405  if (!pagemode)
2407 
2408  ExecStoreBufferHeapTuple(tuple, slot, hscan->rs_cbuf);
2409 
2410  /* Count successfully-fetched tuples as heap fetches */
2412 
2413  return true;
2414  }
2415  else
2416  {
2417  /*
2418  * If we get here, it means we've exhausted the items on this page
2419  * and it's time to move to the next.
2420  */
2421  if (!pagemode)
2423 
2424  ExecClearTuple(slot);
2425  return false;
2426  }
2427  }
2428 
2429  Assert(0);
2430 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
BlockNumber rs_cblock
Definition: heapam.h:59
#define PageIsAllVisible(page)
Definition: bufpage.h:385
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
uint32 BlockNumber
Definition: block.h:31
uint32 rs_flags
Definition: relscan.h:47
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
HeapTupleData rs_ctup
Definition: heapam.h:66
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:68
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
NextSampleTuple_function NextSampleTuple
Definition: tsmapi.h:74
ItemPointerData t_self
Definition: htup.h:65
static bool SampleHeapTupleVisible(TableScanDesc scan, Buffer buffer, HeapTuple tuple, OffsetNumber tupoffset)
uint32 t_len
Definition: htup.h:64
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4011
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1392
void HeapCheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: heapam.c:9789
Buffer rs_cbuf
Definition: heapam.h:60
#define Assert(condition)
Definition: c.h:804
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
bool takenDuringRecovery
Definition: snapshot.h:184
struct TsmRoutine * tsmroutine
Definition: execnodes.h:1403
Relation rs_rd
Definition: relscan.h:34
struct SnapshotData * rs_snapshot
Definition: relscan.h:35
#define OffsetNumberIsValid(offsetNumber)
Definition: off.h:39
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
#define pgstat_count_heap_getnext(rel)
Definition: pgstat.h:1030
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127

◆ heapam_slot_callbacks()

static const TupleTableSlotOps* heapam_slot_callbacks ( Relation  relation)
static

Definition at line 67 of file heapam_handler.c.

References TTSOpsBufferHeapTuple.

Referenced by SampleHeapTupleVisible().

68 {
69  return &TTSOpsBufferHeapTuple;
70 }
const TupleTableSlotOps TTSOpsBufferHeapTuple
Definition: execTuples.c:86

◆ heapam_tuple_complete_speculative()

static void heapam_tuple_complete_speculative ( Relation  relation,
TupleTableSlot slot,
uint32  specToken,
bool  succeeded 
)
static

Definition at line 283 of file heapam_handler.c.

References ExecFetchSlotHeapTuple(), heap_abort_speculative(), heap_finish_speculative(), pfree(), and TupleTableSlot::tts_tid.

Referenced by SampleHeapTupleVisible().

285 {
286  bool shouldFree = true;
287  HeapTuple tuple = ExecFetchSlotHeapTuple(slot, true, &shouldFree);
288 
289  /* adjust the tuple's state accordingly */
290  if (succeeded)
291  heap_finish_speculative(relation, &slot->tts_tid);
292  else
293  heap_abort_speculative(relation, &slot->tts_tid);
294 
295  if (shouldFree)
296  pfree(tuple);
297 }
void heap_abort_speculative(Relation relation, ItemPointer tid)
Definition: heapam.c:5838
void pfree(void *pointer)
Definition: mcxt.c:1169
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
void heap_finish_speculative(Relation relation, ItemPointer tid)
Definition: heapam.c:5747
ItemPointerData tts_tid
Definition: tuptable.h:130

◆ heapam_tuple_delete()

static TM_Result heapam_tuple_delete ( Relation  relation,
ItemPointer  tid,
CommandId  cid,
Snapshot  snapshot,
Snapshot  crosscheck,
bool  wait,
TM_FailureData tmfd,
bool  changingPart 
)
static

Definition at line 300 of file heapam_handler.c.

References heap_delete().

Referenced by SampleHeapTupleVisible().

303 {
304  /*
305  * Currently Deleting of index tuples are handled at vacuum, in case if
306  * the storage itself is cleaning the dead tuples by itself, it is the
307  * time to call the index tuple deletion also.
308  */
309  return heap_delete(relation, tid, cid, crosscheck, wait, tmfd, changingPart);
310 }
TM_Result heap_delete(Relation relation, ItemPointer tid, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
Definition: heapam.c:2700

◆ heapam_tuple_insert()

static void heapam_tuple_insert ( Relation  relation,
TupleTableSlot slot,
CommandId  cid,
int  options,
BulkInsertState  bistate 
)
static

Definition at line 241 of file heapam_handler.c.

References ExecFetchSlotHeapTuple(), heap_insert(), ItemPointerCopy, pfree(), RelationGetRelid, HeapTupleData::t_self, HeapTupleData::t_tableOid, TupleTableSlot::tts_tableOid, and TupleTableSlot::tts_tid.

Referenced by SampleHeapTupleVisible().

243 {
244  bool shouldFree = true;
245  HeapTuple tuple = ExecFetchSlotHeapTuple(slot, true, &shouldFree);
246 
247  /* Update the tuple with table oid */
248  slot->tts_tableOid = RelationGetRelid(relation);
249  tuple->t_tableOid = slot->tts_tableOid;
250 
251  /* Perform the insertion, and copy the resulting ItemPointer */
252  heap_insert(relation, tuple, cid, options, bistate);
253  ItemPointerCopy(&tuple->t_self, &slot->tts_tid);
254 
255  if (shouldFree)
256  pfree(tuple);
257 }
void heap_insert(Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
Definition: heapam.c:2060
Oid tts_tableOid
Definition: tuptable.h:131
void pfree(void *pointer)
Definition: mcxt.c:1169
ItemPointerData t_self
Definition: htup.h:65
Oid t_tableOid
Definition: htup.h:66
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
ItemPointerData tts_tid
Definition: tuptable.h:130
#define RelationGetRelid(relation)
Definition: rel.h:477
#define ItemPointerCopy(fromPointer, toPointer)
Definition: itemptr.h:161

◆ heapam_tuple_insert_speculative()

static void heapam_tuple_insert_speculative ( Relation  relation,
TupleTableSlot slot,
CommandId  cid,
int  options,
BulkInsertState  bistate,
uint32  specToken 
)
static

Definition at line 260 of file heapam_handler.c.

References ExecFetchSlotHeapTuple(), heap_insert(), HEAP_INSERT_SPECULATIVE, HeapTupleHeaderSetSpeculativeToken, ItemPointerCopy, pfree(), RelationGetRelid, HeapTupleData::t_data, HeapTupleData::t_self, HeapTupleData::t_tableOid, TupleTableSlot::tts_tableOid, and TupleTableSlot::tts_tid.

Referenced by SampleHeapTupleVisible().

263 {
264  bool shouldFree = true;
265  HeapTuple tuple = ExecFetchSlotHeapTuple(slot, true, &shouldFree);
266 
267  /* Update the tuple with table oid */
268  slot->tts_tableOid = RelationGetRelid(relation);
269  tuple->t_tableOid = slot->tts_tableOid;
270 
271  HeapTupleHeaderSetSpeculativeToken(tuple->t_data, specToken);
273 
274  /* Perform the insertion, and copy the resulting ItemPointer */
275  heap_insert(relation, tuple, cid, options, bistate);
276  ItemPointerCopy(&tuple->t_self, &slot->tts_tid);
277 
278  if (shouldFree)
279  pfree(tuple);
280 }
void heap_insert(Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
Definition: heapam.c:2060
Oid tts_tableOid
Definition: tuptable.h:131
#define HeapTupleHeaderSetSpeculativeToken(tup, token)
Definition: htup_details.h:440
#define HEAP_INSERT_SPECULATIVE
Definition: heapam.h:37
HeapTupleHeader t_data
Definition: htup.h:68
void pfree(void *pointer)
Definition: mcxt.c:1169
ItemPointerData t_self
Definition: htup.h:65
Oid t_tableOid
Definition: htup.h:66
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
ItemPointerData tts_tid
Definition: tuptable.h:130
#define RelationGetRelid(relation)
Definition: rel.h:477
#define ItemPointerCopy(fromPointer, toPointer)
Definition: itemptr.h:161

◆ heapam_tuple_lock()

static TM_Result heapam_tuple_lock ( Relation  relation,
ItemPointer  tid,
Snapshot  snapshot,
TupleTableSlot slot,
CommandId  cid,
LockTupleMode  mode,
LockWaitPolicy  wait_policy,
uint8  flags,
TM_FailureData tmfd 
)
static

Definition at line 348 of file heapam_handler.c.

References Assert, BufferHeapTupleTableSlot::base, BufferIsValid, TM_FailureData::cmax, ConditionalXactLockTableWait(), TM_FailureData::ctid, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg(), errmsg_internal(), ERROR, ExecStorePinnedBufferHeapTuple(), heap_fetch(), heap_lock_tuple(), HeapTupleHeaderGetCmin(), HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleHeaderIsSpeculative, InitDirtySnapshot, ItemPointerEquals(), ItemPointerIndicatesMovedPartitions, LockWaitBlock, LockWaitError, LockWaitSkip, RelationGetRelationName, RelationGetRelid, ReleaseBuffer(), HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleData::t_self, HeapTupleData::t_tableOid, TM_Deleted, TM_SelfModified, TM_Updated, TM_WouldBlock, TransactionIdEquals, TransactionIdIsCurrentTransactionId(), TransactionIdIsValid, TM_FailureData::traversed, TTS_IS_BUFFERTUPLE, TupleTableSlot::tts_tableOid, HeapTupleTableSlot::tupdata, TUPLE_LOCK_FLAG_FIND_LAST_VERSION, TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS, XactLockTableWait(), XLTW_FetchUpdated, TM_FailureData::xmax, SnapshotData::xmax, and SnapshotData::xmin.

Referenced by SampleHeapTupleVisible().

352 {
354  TM_Result result;
355  Buffer buffer;
356  HeapTuple tuple = &bslot->base.tupdata;
357  bool follow_updates;
358 
359  follow_updates = (flags & TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS) != 0;
360  tmfd->traversed = false;
361 
362  Assert(TTS_IS_BUFFERTUPLE(slot));
363 
364 tuple_lock_retry:
365  tuple->t_self = *tid;
366  result = heap_lock_tuple(relation, tuple, cid, mode, wait_policy,
367  follow_updates, &buffer, tmfd);
368 
369  if (result == TM_Updated &&
371  {
372  /* Should not encounter speculative tuple on recheck */
374 
375  ReleaseBuffer(buffer);
376 
377  if (!ItemPointerEquals(&tmfd->ctid, &tuple->t_self))
378  {
379  SnapshotData SnapshotDirty;
380  TransactionId priorXmax;
381 
382  /* it was updated, so look at the updated version */
383  *tid = tmfd->ctid;
384  /* updated row should have xmin matching this xmax */
385  priorXmax = tmfd->xmax;
386 
387  /* signal that a tuple later in the chain is getting locked */
388  tmfd->traversed = true;
389 
390  /*
391  * fetch target tuple
392  *
393  * Loop here to deal with updated or busy tuples
394  */
395  InitDirtySnapshot(SnapshotDirty);
396  for (;;)
397  {
399  ereport(ERROR,
400  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
401  errmsg("tuple to be locked was already moved to another partition due to concurrent update")));
402 
403  tuple->t_self = *tid;
404  if (heap_fetch(relation, &SnapshotDirty, tuple, &buffer))
405  {
406  /*
407  * If xmin isn't what we're expecting, the slot must have
408  * been recycled and reused for an unrelated tuple. This
409  * implies that the latest version of the row was deleted,
410  * so we need do nothing. (Should be safe to examine xmin
411  * without getting buffer's content lock. We assume
412  * reading a TransactionId to be atomic, and Xmin never
413  * changes in an existing tuple, except to invalid or
414  * frozen, and neither of those can match priorXmax.)
415  */
417  priorXmax))
418  {
419  ReleaseBuffer(buffer);
420  return TM_Deleted;
421  }
422 
423  /* otherwise xmin should not be dirty... */
424  if (TransactionIdIsValid(SnapshotDirty.xmin))
425  ereport(ERROR,
427  errmsg_internal("t_xmin is uncommitted in tuple to be updated")));
428 
429  /*
430  * If tuple is being updated by other transaction then we
431  * have to wait for its commit/abort, or die trying.
432  */
433  if (TransactionIdIsValid(SnapshotDirty.xmax))
434  {
435  ReleaseBuffer(buffer);
436  switch (wait_policy)
437  {
438  case LockWaitBlock:
439  XactLockTableWait(SnapshotDirty.xmax,
440  relation, &tuple->t_self,
442  break;
443  case LockWaitSkip:
444  if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
445  /* skip instead of waiting */
446  return TM_WouldBlock;
447  break;
448  case LockWaitError:
449  if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
450  ereport(ERROR,
451  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
452  errmsg("could not obtain lock on row in relation \"%s\"",
453  RelationGetRelationName(relation))));
454  break;
455  }
456  continue; /* loop back to repeat heap_fetch */
457  }
458 
459  /*
460  * If tuple was inserted by our own transaction, we have
461  * to check cmin against cid: cmin >= current CID means
462  * our command cannot see the tuple, so we should ignore
463  * it. Otherwise heap_lock_tuple() will throw an error,
464  * and so would any later attempt to update or delete the
465  * tuple. (We need not check cmax because
466  * HeapTupleSatisfiesDirty will consider a tuple deleted
467  * by our transaction dead, regardless of cmax.) We just
468  * checked that priorXmax == xmin, so we can test that
469  * variable instead of doing HeapTupleHeaderGetXmin again.
470  */
471  if (TransactionIdIsCurrentTransactionId(priorXmax) &&
472  HeapTupleHeaderGetCmin(tuple->t_data) >= cid)
473  {
474  tmfd->xmax = priorXmax;
475 
476  /*
477  * Cmin is the problematic value, so store that. See
478  * above.
479  */
480  tmfd->cmax = HeapTupleHeaderGetCmin(tuple->t_data);
481  ReleaseBuffer(buffer);
482  return TM_SelfModified;
483  }
484 
485  /*
486  * This is a live tuple, so try to lock it again.
487  */
488  ReleaseBuffer(buffer);
489  goto tuple_lock_retry;
490  }
491 
492  /*
493  * If the referenced slot was actually empty, the latest
494  * version of the row must have been deleted, so we need do
495  * nothing.
496  */
497  if (tuple->t_data == NULL)
498  {
499  return TM_Deleted;
500  }
501 
502  /*
503  * As above, if xmin isn't what we're expecting, do nothing.
504  */
506  priorXmax))
507  {
508  if (BufferIsValid(buffer))
509  ReleaseBuffer(buffer);
510  return TM_Deleted;
511  }
512 
513  /*
514  * If we get here, the tuple was found but failed
515  * SnapshotDirty. Assuming the xmin is either a committed xact
516  * or our own xact (as it certainly should be if we're trying
517  * to modify the tuple), this must mean that the row was
518  * updated or deleted by either a committed xact or our own
519  * xact. If it was deleted, we can ignore it; if it was
520  * updated then chain up to the next version and repeat the
521  * whole process.
522  *
523  * As above, it should be safe to examine xmax and t_ctid
524  * without the buffer content lock, because they can't be
525  * changing.
526  */
527  if (ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
528  {
529  /* deleted, so forget about it */
530  if (BufferIsValid(buffer))
531  ReleaseBuffer(buffer);
532  return TM_Deleted;
533  }
534 
535  /* updated, so look at the updated row */
536  *tid = tuple->t_data->t_ctid;
537  /* updated row should have xmin matching this xmax */
538  priorXmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
539  if (BufferIsValid(buffer))
540  ReleaseBuffer(buffer);
541  /* loop back to fetch next in chain */
542  }
543  }
544  else
545  {
546  /* tuple was deleted, so give up */
547  return TM_Deleted;
548  }
549  }
550 
551  slot->tts_tableOid = RelationGetRelid(relation);
552  tuple->t_tableOid = slot->tts_tableOid;
553 
554  /* store in slot, transferring existing pin */
555  ExecStorePinnedBufferHeapTuple(tuple, slot, buffer);
556 
557  return result;
558 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:365
Oid tts_tableOid
Definition: tuptable.h:131
ItemPointerData ctid
Definition: tableam.h:126
static PgChecksumMode mode
Definition: pg_checksums.c:65
#define InitDirtySnapshot(snapshotdata)
Definition: snapmgr.h:74
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:587
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:869
CommandId HeapTupleHeaderGetCmin(HeapTupleHeader tup)
Definition: combocid.c:104
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf)
Definition: heapam.c:1595
CommandId cmax
Definition: tableam.h:128
#define HeapTupleHeaderIsSpeculative(tup)
Definition: htup_details.h:429
int errcode(int sqlerrcode)
Definition: elog.c:698
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3772
#define TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS
Definition: tableam.h:240
bool ConditionalXactLockTableWait(TransactionId xid)
Definition: lmgr.c:713
HeapTupleHeader t_data
Definition: htup.h:68
TransactionId xmax
Definition: tableam.h:127
#define ERROR
Definition: elog.h:46
ItemPointerData t_ctid
Definition: htup_details.h:160
ItemPointerData t_self
Definition: htup.h:65
#define RelationGetRelationName(relation)
Definition: rel.h:511
Oid t_tableOid
Definition: htup.h:66
TransactionId xmax
Definition: snapshot.h:158
TransactionId xmin
Definition: snapshot.h:157
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:47
TM_Result
Definition: tableam.h:71
#define TTS_IS_BUFFERTUPLE(slot)
Definition: tuptable.h:231
#define ItemPointerIndicatesMovedPartitions(pointer)
Definition: itemptr.h:184
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:640
#define Assert(condition)
Definition: c.h:804
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:313
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
#define TUPLE_LOCK_FLAG_FIND_LAST_VERSION
Definition: tableam.h:242
TupleTableSlot * ExecStorePinnedBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1418
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
TM_Result heap_lock_tuple(Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, bool follow_updates, Buffer *buffer, TM_FailureData *tmfd)
Definition: heapam.c:4247
int errmsg(const char *fmt,...)
Definition: elog.c:909
HeapTupleTableSlot base
Definition: tuptable.h:259
#define TransactionIdIsValid(xid)
Definition: transam.h:41
bool traversed
Definition: tableam.h:129
HeapTupleData tupdata
Definition: tuptable.h:253
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:477

◆ heapam_tuple_satisfies_snapshot()

static bool heapam_tuple_satisfies_snapshot ( Relation  rel,
TupleTableSlot slot,
Snapshot  snapshot 
)
static

Definition at line 213 of file heapam_handler.c.

References Assert, BufferHeapTupleTableSlot::base, BufferHeapTupleTableSlot::buffer, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferIsValid, HeapTupleSatisfiesVisibility(), LockBuffer(), TTS_IS_BUFFERTUPLE, and HeapTupleTableSlot::tuple.

Referenced by SampleHeapTupleVisible().

215 {
217  bool res;
218 
219  Assert(TTS_IS_BUFFERTUPLE(slot));
220  Assert(BufferIsValid(bslot->buffer));
221 
222  /*
223  * We need buffer pin and lock to call HeapTupleSatisfiesVisibility.
224  * Caller should be holding pin, but not lock.
225  */
227  res = HeapTupleSatisfiesVisibility(bslot->base.tuple, snapshot,
228  bslot->buffer);
230 
231  return res;
232 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
HeapTuple tuple
Definition: tuptable.h:250
#define TTS_IS_BUFFERTUPLE(slot)
Definition: tuptable.h:231
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4011
#define Assert(condition)
Definition: c.h:804
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
HeapTupleTableSlot base
Definition: tuptable.h:259
bool HeapTupleSatisfiesVisibility(HeapTuple tup, Snapshot snapshot, Buffer buffer)

◆ heapam_tuple_tid_valid()

static bool heapam_tuple_tid_valid ( TableScanDesc  scan,
ItemPointer  tid 
)
static

Definition at line 204 of file heapam_handler.c.

References ItemPointerGetBlockNumber, ItemPointerIsValid, and HeapScanDescData::rs_nblocks.

Referenced by SampleHeapTupleVisible().

205 {
206  HeapScanDesc hscan = (HeapScanDesc) scan;
207 
208  return ItemPointerIsValid(tid) &&
210 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
BlockNumber rs_nblocks
Definition: heapam.h:52
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98

◆ heapam_tuple_update()

static TM_Result heapam_tuple_update ( Relation  relation,
ItemPointer  otid,
TupleTableSlot slot,
CommandId  cid,
Snapshot  snapshot,
Snapshot  crosscheck,
bool  wait,
TM_FailureData tmfd,
LockTupleMode lockmode,
bool update_indexes 
)
static

Definition at line 314 of file heapam_handler.c.

References ExecFetchSlotHeapTuple(), heap_update(), HeapTupleIsHeapOnly, ItemPointerCopy, pfree(), RelationGetRelid, HeapTupleData::t_self, HeapTupleData::t_tableOid, TM_Ok, TupleTableSlot::tts_tableOid, and TupleTableSlot::tts_tid.

Referenced by SampleHeapTupleVisible().

318 {
319  bool shouldFree = true;
320  HeapTuple tuple = ExecFetchSlotHeapTuple(slot, true, &shouldFree);
321  TM_Result result;
322 
323  /* Update the tuple with table oid */
324  slot->tts_tableOid = RelationGetRelid(relation);
325  tuple->t_tableOid = slot->tts_tableOid;
326 
327  result = heap_update(relation, otid, tuple, cid, crosscheck, wait,
328  tmfd, lockmode);
329  ItemPointerCopy(&tuple->t_self, &slot->tts_tid);
330 
331  /*
332  * Decide whether new index entries are needed for the tuple
333  *
334  * Note: heap_update returns the tid (location) of the new tuple in the
335  * t_self field.
336  *
337  * If it's a HOT update, we mustn't insert new index entries.
338  */
339  *update_indexes = result == TM_Ok && !HeapTupleIsHeapOnly(tuple);
340 
341  if (shouldFree)
342  pfree(tuple);
343 
344  return result;
345 }
Oid tts_tableOid
Definition: tuptable.h:131
void pfree(void *pointer)
Definition: mcxt.c:1169
ItemPointerData t_self
Definition: htup.h:65
Oid t_tableOid
Definition: htup.h:66
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
TM_Result
Definition: tableam.h:71
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:684
Definition: tableam.h:77
TM_Result heap_update(Relation relation, ItemPointer otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode)
Definition: heapam.c:3153
ItemPointerData tts_tid
Definition: tuptable.h:130
#define RelationGetRelid(relation)
Definition: rel.h:477
#define ItemPointerCopy(fromPointer, toPointer)
Definition: itemptr.h:161

◆ reform_and_rewrite_tuple()

static void reform_and_rewrite_tuple ( HeapTuple  tuple,
Relation  OldHeap,
Relation  NewHeap,
Datum values,
bool isnull,
RewriteState  rwstate 
)
static

Definition at line 2455 of file heapam_handler.c.

References heap_deform_tuple(), heap_form_tuple(), heap_freetuple(), i, TupleDescData::natts, RelationGetDescr, rewrite_heap_tuple(), and TupleDescAttr.

Referenced by heapam_relation_copy_for_cluster().

2458 {
2459  TupleDesc oldTupDesc = RelationGetDescr(OldHeap);
2460  TupleDesc newTupDesc = RelationGetDescr(NewHeap);
2461  HeapTuple copiedTuple;
2462  int i;
2463 
2464  heap_deform_tuple(tuple, oldTupDesc, values, isnull);
2465 
2466  /* Be sure to null out any dropped columns */
2467  for (i = 0; i < newTupDesc->natts; i++)
2468  {
2469  if (TupleDescAttr(newTupDesc, i)->attisdropped)
2470  isnull[i] = true;
2471  }
2472 
2473  copiedTuple = heap_form_tuple(newTupDesc, values, isnull);
2474 
2475  /* The heap rewrite module does the rest */
2476  rewrite_heap_tuple(rwstate, tuple, copiedTuple);
2477 
2478  heap_freetuple(copiedTuple);
2479 }
#define RelationGetDescr(relation)
Definition: rel.h:503
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1249
static Datum values[MAXATTR]
Definition: bootstrap.c:166
int i
void rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple, HeapTuple new_tuple)
Definition: rewriteheap.c:361

◆ SampleHeapTupleVisible()

static bool SampleHeapTupleVisible ( TableScanDesc  scan,
Buffer  buffer,
HeapTuple  tuple,
OffsetNumber  tupoffset 
)
static

Definition at line 2485 of file heapam_handler.c.

References heap_beginscan(), heap_endscan(), heap_fetch_toast_slice(), heap_get_latest_tid(), heap_getnextslot(), heap_getnextslot_tidrange(), heap_index_delete_tuples(), heap_multi_insert(), heap_rescan(), heap_set_tidrange(), heap_vacuum_rel(), heapam_estimate_rel_size(), heapam_fetch_row_version(), heapam_index_build_range_scan(), heapam_index_fetch_begin(), heapam_index_fetch_end(), heapam_index_fetch_reset(), heapam_index_fetch_tuple(), heapam_index_validate_scan(), heapam_relation_copy_data(), heapam_relation_copy_for_cluster(), heapam_relation_needs_toast_table(), heapam_relation_nontransactional_truncate(), heapam_relation_set_new_filenode(), heapam_relation_toast_am(), heapam_scan_analyze_next_block(), heapam_scan_analyze_next_tuple(), heapam_scan_bitmap_next_block(), heapam_scan_bitmap_next_tuple(), heapam_scan_sample_next_block(), heapam_scan_sample_next_tuple(), heapam_slot_callbacks(), heapam_tuple_complete_speculative(), heapam_tuple_delete(), heapam_tuple_insert(), heapam_tuple_insert_speculative(), heapam_tuple_lock(), heapam_tuple_satisfies_snapshot(), heapam_tuple_tid_valid(), heapam_tuple_update(), HeapTupleSatisfiesVisibility(), TableScanDescData::rs_flags, HeapScanDescData::rs_ntuples, TableScanDescData::rs_snapshot, HeapScanDescData::rs_vistuples, SO_ALLOW_PAGEMODE, T_TableAmRoutine, table_block_parallelscan_estimate(), table_block_parallelscan_initialize(), table_block_parallelscan_reinitialize(), table_block_relation_size(), and TableAmRoutine::type.

Referenced by heapam_scan_sample_next_tuple().

2488 {
2489  HeapScanDesc hscan = (HeapScanDesc) scan;
2490 
2491  if (scan->rs_flags & SO_ALLOW_PAGEMODE)
2492  {
2493  /*
2494  * In pageatatime mode, heapgetpage() already did visibility checks,
2495  * so just look at the info it left in rs_vistuples[].
2496  *
2497  * We use a binary search over the known-sorted array. Note: we could
2498  * save some effort if we insisted that NextSampleTuple select tuples
2499  * in increasing order, but it's not clear that there would be enough
2500  * gain to justify the restriction.
2501  */
2502  int start = 0,
2503  end = hscan->rs_ntuples - 1;
2504 
2505  while (start <= end)
2506  {
2507  int mid = (start + end) / 2;
2508  OffsetNumber curoffset = hscan->rs_vistuples[mid];
2509 
2510  if (tupoffset == curoffset)
2511  return true;
2512  else if (tupoffset < curoffset)
2513  end = mid - 1;
2514  else
2515  start = mid + 1;
2516  }
2517 
2518  return false;
2519  }
2520  else
2521  {
2522  /* Otherwise, we have to check the tuple individually. */
2523  return HeapTupleSatisfiesVisibility(tuple, scan->rs_snapshot,
2524  buffer);
2525  }
2526 }
uint32 rs_flags
Definition: relscan.h:47
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
uint16 OffsetNumber
Definition: off.h:24
int rs_ntuples
Definition: heapam.h:76
OffsetNumber rs_vistuples[MaxHeapTuplesPerPage]
Definition: heapam.h:77
struct SnapshotData * rs_snapshot
Definition: relscan.h:35
bool HeapTupleSatisfiesVisibility(HeapTuple tup, Snapshot snapshot, Buffer buffer)

Variable Documentation

◆ heapam_methods

static const TableAmRoutine heapam_methods
static

Definition at line 58 of file heapam_handler.c.

Referenced by GetHeapamTableAmRoutine().