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 2042 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 2044 of file heapam_handler.c.

Referenced by heapam_estimate_rel_size().

Function Documentation

◆ GetHeapamTableAmRoutine()

const TableAmRoutine* GetHeapamTableAmRoutine ( void  )

Definition at line 2547 of file heapam_handler.c.

References heapam_methods.

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

2548 {
2549  return &heapam_methods;
2550 }
static const TableAmRoutine heapam_methods

◆ heap_tableam_handler()

Datum heap_tableam_handler ( PG_FUNCTION_ARGS  )

Definition at line 2553 of file heapam_handler.c.

References PG_RETURN_POINTER.

2554 {
2556 }
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:360
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 2048 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().

2051 {
2052  table_block_relation_estimate_size(rel, attr_widths, pages,
2053  tuples, allvisfrac,
2056 }
#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:668

◆ 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:1394
ItemPointerData t_self
Definition: htup.h:65
#define TTS_IS_BUFFERTUPLE(slot)
Definition: tuptable.h:231
#define Assert(condition)
Definition: c.h:745
TupleTableSlot * ExecStorePinnedBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1388
HeapTupleTableSlot base
Definition: tuptable.h:259
HeapTupleData tupdata
Definition: tuptable.h:253
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ 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 1133 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(), GetOldestXmin(), 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, InvalidTransactionId, IsBootstrapProcessingMode, IsMVCCSnapshot, IsSystemRelation(), ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, ItemPointerSet, LockBuffer(), MaxHeapTuplesPerPage, MemoryContextReset(), NIL, OffsetNumberIsValid, OidIsValid, OldestXmin, pgstat_progress_update_param(), ParallelBlockTableScanDescData::phs_nblocks, PROCARRAY_FLAGS_VACUUM, 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().

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

◆ 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:1056

◆ 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:3518
Buffer xs_cbuf
Definition: heapam.h:82
#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:1509
ItemPointerData t_self
Definition: htup.h:65
Buffer xs_cbuf
Definition: heapam.h:82
#define TTS_IS_BUFFERTUPLE(slot)
Definition: tuptable.h:231
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3757
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1362
#define IsMVCCSnapshot(snapshot)
Definition: snapmgr.h:97
#define Assert(condition)
Definition: c.h:745
Buffer ReleaseAndReadBuffer(Buffer buffer, Relation relation, BlockNumber blockNum)
Definition: bufmgr.c:1532
#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:73
#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:456
IndexFetchTableData xs_base
Definition: heapam.h:80

◆ heapam_index_validate_scan()

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

Definition at line 1688 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().

1693 {
1694  TableScanDesc scan;
1695  HeapScanDesc hscan;
1696  HeapTuple heapTuple;
1698  bool isnull[INDEX_MAX_KEYS];
1699  ExprState *predicate;
1700  TupleTableSlot *slot;
1701  EState *estate;
1702  ExprContext *econtext;
1703  BlockNumber root_blkno = InvalidBlockNumber;
1704  OffsetNumber root_offsets[MaxHeapTuplesPerPage];
1705  bool in_index[MaxHeapTuplesPerPage];
1706  BlockNumber previous_blkno = InvalidBlockNumber;
1707 
1708  /* state variables for the merge */
1709  ItemPointer indexcursor = NULL;
1710  ItemPointerData decoded;
1711  bool tuplesort_empty = false;
1712 
1713  /*
1714  * sanity checks
1715  */
1716  Assert(OidIsValid(indexRelation->rd_rel->relam));
1717 
1718  /*
1719  * Need an EState for evaluation of index expressions and partial-index
1720  * predicates. Also a slot to hold the current tuple.
1721  */
1722  estate = CreateExecutorState();
1723  econtext = GetPerTupleExprContext(estate);
1724  slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRelation),
1725  &TTSOpsHeapTuple);
1726 
1727  /* Arrange for econtext's scan tuple to be the tuple under test */
1728  econtext->ecxt_scantuple = slot;
1729 
1730  /* Set up execution state for predicate, if any. */
1731  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
1732 
1733  /*
1734  * Prepare for scan of the base relation. We need just those tuples
1735  * satisfying the passed-in reference snapshot. We must disable syncscan
1736  * here, because it's critical that we read from block zero forward to
1737  * match the sorted TIDs.
1738  */
1739  scan = table_beginscan_strat(heapRelation, /* relation */
1740  snapshot, /* snapshot */
1741  0, /* number of keys */
1742  NULL, /* scan key */
1743  true, /* buffer access strategy OK */
1744  false); /* syncscan not OK */
1745  hscan = (HeapScanDesc) scan;
1746 
1748  hscan->rs_nblocks);
1749 
1750  /*
1751  * Scan all tuples matching the snapshot.
1752  */
1753  while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1754  {
1755  ItemPointer heapcursor = &heapTuple->t_self;
1756  ItemPointerData rootTuple;
1757  OffsetNumber root_offnum;
1758 
1760 
1761  state->htups += 1;
1762 
1763  if ((previous_blkno == InvalidBlockNumber) ||
1764  (hscan->rs_cblock != previous_blkno))
1765  {
1767  hscan->rs_cblock);
1768  previous_blkno = hscan->rs_cblock;
1769  }
1770 
1771  /*
1772  * As commented in table_index_build_scan, we should index heap-only
1773  * tuples under the TIDs of their root tuples; so when we advance onto
1774  * a new heap page, build a map of root item offsets on the page.
1775  *
1776  * This complicates merging against the tuplesort output: we will
1777  * visit the live tuples in order by their offsets, but the root
1778  * offsets that we need to compare against the index contents might be
1779  * ordered differently. So we might have to "look back" within the
1780  * tuplesort output, but only within the current page. We handle that
1781  * by keeping a bool array in_index[] showing all the
1782  * already-passed-over tuplesort output TIDs of the current page. We
1783  * clear that array here, when advancing onto a new heap page.
1784  */
1785  if (hscan->rs_cblock != root_blkno)
1786  {
1787  Page page = BufferGetPage(hscan->rs_cbuf);
1788 
1790  heap_get_root_tuples(page, root_offsets);
1792 
1793  memset(in_index, 0, sizeof(in_index));
1794 
1795  root_blkno = hscan->rs_cblock;
1796  }
1797 
1798  /* Convert actual tuple TID to root TID */
1799  rootTuple = *heapcursor;
1800  root_offnum = ItemPointerGetOffsetNumber(heapcursor);
1801 
1802  if (HeapTupleIsHeapOnly(heapTuple))
1803  {
1804  root_offnum = root_offsets[root_offnum - 1];
1805  if (!OffsetNumberIsValid(root_offnum))
1806  ereport(ERROR,
1808  errmsg_internal("failed to find parent tuple for heap-only tuple at (%u,%u) in table \"%s\"",
1809  ItemPointerGetBlockNumber(heapcursor),
1810  ItemPointerGetOffsetNumber(heapcursor),
1811  RelationGetRelationName(heapRelation))));
1812  ItemPointerSetOffsetNumber(&rootTuple, root_offnum);
1813  }
1814 
1815  /*
1816  * "merge" by skipping through the index tuples until we find or pass
1817  * the current root tuple.
1818  */
1819  while (!tuplesort_empty &&
1820  (!indexcursor ||
1821  ItemPointerCompare(indexcursor, &rootTuple) < 0))
1822  {
1823  Datum ts_val;
1824  bool ts_isnull;
1825 
1826  if (indexcursor)
1827  {
1828  /*
1829  * Remember index items seen earlier on the current heap page
1830  */
1831  if (ItemPointerGetBlockNumber(indexcursor) == root_blkno)
1832  in_index[ItemPointerGetOffsetNumber(indexcursor) - 1] = true;
1833  }
1834 
1835  tuplesort_empty = !tuplesort_getdatum(state->tuplesort, true,
1836  &ts_val, &ts_isnull, NULL);
1837  Assert(tuplesort_empty || !ts_isnull);
1838  if (!tuplesort_empty)
1839  {
1840  itemptr_decode(&decoded, DatumGetInt64(ts_val));
1841  indexcursor = &decoded;
1842 
1843  /* If int8 is pass-by-ref, free (encoded) TID Datum memory */
1844 #ifndef USE_FLOAT8_BYVAL
1845  pfree(DatumGetPointer(ts_val));
1846 #endif
1847  }
1848  else
1849  {
1850  /* Be tidy */
1851  indexcursor = NULL;
1852  }
1853  }
1854 
1855  /*
1856  * If the tuplesort has overshot *and* we didn't see a match earlier,
1857  * then this tuple is missing from the index, so insert it.
1858  */
1859  if ((tuplesort_empty ||
1860  ItemPointerCompare(indexcursor, &rootTuple) > 0) &&
1861  !in_index[root_offnum - 1])
1862  {
1864 
1865  /* Set up for predicate or expression evaluation */
1866  ExecStoreHeapTuple(heapTuple, slot, false);
1867 
1868  /*
1869  * In a partial index, discard tuples that don't satisfy the
1870  * predicate.
1871  */
1872  if (predicate != NULL)
1873  {
1874  if (!ExecQual(predicate, econtext))
1875  continue;
1876  }
1877 
1878  /*
1879  * For the current heap tuple, extract all the attributes we use
1880  * in this index, and note which are null. This also performs
1881  * evaluation of any expressions needed.
1882  */
1883  FormIndexDatum(indexInfo,
1884  slot,
1885  estate,
1886  values,
1887  isnull);
1888 
1889  /*
1890  * You'd think we should go ahead and build the index tuple here,
1891  * but some index AMs want to do further processing on the data
1892  * first. So pass the values[] and isnull[] arrays, instead.
1893  */
1894 
1895  /*
1896  * If the tuple is already committed dead, you might think we
1897  * could suppress uniqueness checking, but this is no longer true
1898  * in the presence of HOT, because the insert is actually a proxy
1899  * for a uniqueness check on the whole HOT-chain. That is, the
1900  * tuple we have here could be dead because it was already
1901  * HOT-updated, and if so the updating transaction will not have
1902  * thought it should insert index entries. The index AM will
1903  * check the whole HOT-chain and correctly detect a conflict if
1904  * there is one.
1905  */
1906 
1907  index_insert(indexRelation,
1908  values,
1909  isnull,
1910  &rootTuple,
1911  heapRelation,
1912  indexInfo->ii_Unique ?
1914  indexInfo);
1915 
1916  state->tups_inserted += 1;
1917  }
1918  }
1919 
1920  table_endscan(scan);
1921 
1923 
1924  FreeExecutorState(estate);
1925 
1926  /* These may have been pointing to the now-gone estate */
1927  indexInfo->ii_ExpressionsState = NIL;
1928  indexInfo->ii_PredicateState = NULL;
1929 }
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:2571
#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:2418
BlockNumber rs_cblock
Definition: heapam.h:59
List * ii_Predicate
Definition: execnodes.h:163
#define RelationGetDescr(relation)
Definition: rel.h:482
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1208
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3231
ExprState * ii_PredicateState
Definition: execnodes.h:164
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:234
#define MaxHeapTuplesPerPage
Definition: htup_details.h:574
int errcode(int sqlerrcode)
Definition: elog.c:610
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:136
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:370
#define OidIsValid(objectId)
Definition: c.h:651
static TableScanDesc table_beginscan_strat(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key, bool allow_strat, bool allow_sync)
Definition: tableam.h:779
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:73
uint16 OffsetNumber
Definition: off.h:24
void FreeExecutorState(EState *estate)
Definition: execUtils.c:191
#define GetPerTupleExprContext(estate)
Definition: executor.h:507
List * ii_ExpressionsState
Definition: execnodes.h:162
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define DatumGetInt64(X)
Definition: postgres.h:607
Tuplesortstate * tuplesort
Definition: index.h:35
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1286
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
#define RelationGetRelationName(relation)
Definition: rel.h:490
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:520
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
void heap_get_root_tuples(Page page, OffsetNumber *root_offsets)
Definition: pruneheap.c:745
EState * CreateExecutorState(void)
Definition: execUtils.c:89
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:45
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
uintptr_t Datum
Definition: postgres.h:367
BlockNumber rs_nblocks
Definition: heapam.h:52
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3757
static void itemptr_decode(ItemPointer itemptr, int64 encoded)
Definition: index.h:191
#define ereport(elevel,...)
Definition: elog.h:144
Buffer rs_cbuf
Definition: heapam.h:60
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
bool ii_Unique
Definition: execnodes.h:172
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:685
#define Assert(condition)
Definition: c.h:745
double tups_inserted
Definition: index.h:37
#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:549
double htups
Definition: index.h:37
#define ItemPointerSetOffsetNumber(pointer, offsetNumber)
Definition: itemptr.h:148
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:863
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#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:99
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1322
Pointer Page
Definition: bufpage.h:78
bool index_insert(Relation indexRelation, Datum *values, bool *isnull, ItemPointer heap_t_ctid, Relation heapRelation, IndexUniqueCheck checkUnique, IndexInfo *indexInfo)
Definition: indexam.c:176

◆ 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, RelationData::rd_smgr, RelationCopyStorage(), RelationCreateStorage(), RelationDropStorage(), RelationOpenSmgr, smgrclose(), smgrcreate(), smgrexists(), and smgropen().

Referenced by SampleHeapTupleVisible().

624 {
625  SMgrRelation dstrel;
626 
627  dstrel = smgropen(*newrnode, rel->rd_backend);
628  RelationOpenSmgr(rel);
629 
630  /*
631  * Since we copy the file directly without looking at the shared buffers,
632  * we'd better first flush out any pages of the source relation that are
633  * in shared buffers. We assume no new changes will be made while we are
634  * holding exclusive lock on the rel.
635  */
637 
638  /*
639  * Create and copy all forks of the relation, and schedule unlinking of
640  * old physical files.
641  *
642  * NOTE: any conflict in relfilenode value will be caught in
643  * RelationCreateStorage().
644  */
645  RelationCreateStorage(*newrnode, rel->rd_rel->relpersistence);
646 
647  /* copy main fork */
649  rel->rd_rel->relpersistence);
650 
651  /* copy those extra forks that exist */
652  for (ForkNumber forkNum = MAIN_FORKNUM + 1;
653  forkNum <= MAX_FORKNUM; forkNum++)
654  {
655  if (smgrexists(rel->rd_smgr, forkNum))
656  {
657  smgrcreate(dstrel, forkNum, false);
658 
659  /*
660  * WAL log creation if the relation is persistent, or this is the
661  * init fork of an unlogged relation.
662  */
663  if (rel->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT ||
664  (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
665  forkNum == INIT_FORKNUM))
666  log_smgrcreate(newrnode, forkNum);
667  RelationCopyStorage(rel->rd_smgr, dstrel, forkNum,
668  rel->rd_rel->relpersistence);
669  }
670  }
671 
672 
673  /* drop old relation, and close new one */
674  RelationDropStorage(rel);
675  smgrclose(dstrel);
676 }
void smgrclose(SMgrRelation reln)
Definition: smgr.c:257
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition: smgr.c:334
struct SMgrRelationData * rd_smgr
Definition: rel.h:57
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:248
Form_pg_class rd_rel
Definition: rel.h:109
#define RelationOpenSmgr(relation)
Definition: rel.h:513
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:408
BackendId rd_backend
Definition: rel.h:59
void FlushRelationBuffers(Relation rel)
Definition: bufmgr.c:3259
#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 679 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, 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().

687 {
688  RewriteState rwstate;
689  IndexScanDesc indexScan;
690  TableScanDesc tableScan;
691  HeapScanDesc heapScan;
692  bool is_system_catalog;
693  Tuplesortstate *tuplesort;
694  TupleDesc oldTupDesc = RelationGetDescr(OldHeap);
695  TupleDesc newTupDesc = RelationGetDescr(NewHeap);
696  TupleTableSlot *slot;
697  int natts;
698  Datum *values;
699  bool *isnull;
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  break;
797 
798  /*
799  * In scan-and-sort mode and also VACUUM FULL, set heap blocks
800  * scanned
801  */
803  heapScan->rs_cblock + 1);
804  }
805 
806  tuple = ExecFetchSlotHeapTuple(slot, false, NULL);
807  buf = hslot->buffer;
808 
810 
811  switch (HeapTupleSatisfiesVacuum(tuple, OldestXmin, buf))
812  {
813  case HEAPTUPLE_DEAD:
814  /* Definitely dead */
815  isdead = true;
816  break;
818  *tups_recently_dead += 1;
819  /* fall through */
820  case HEAPTUPLE_LIVE:
821  /* Live or recently dead, must copy it */
822  isdead = false;
823  break;
825 
826  /*
827  * Since we hold exclusive lock on the relation, normally the
828  * only way to see this is if it was inserted earlier in our
829  * own transaction. However, it can happen in system
830  * catalogs, since we tend to release write lock before commit
831  * there. Give a warning if neither case applies; but in any
832  * case we had better copy it.
833  */
834  if (!is_system_catalog &&
836  elog(WARNING, "concurrent insert in progress within table \"%s\"",
837  RelationGetRelationName(OldHeap));
838  /* treat as live */
839  isdead = false;
840  break;
842 
843  /*
844  * Similar situation to INSERT_IN_PROGRESS case.
845  */
846  if (!is_system_catalog &&
848  elog(WARNING, "concurrent delete in progress within table \"%s\"",
849  RelationGetRelationName(OldHeap));
850  /* treat as recently dead */
851  *tups_recently_dead += 1;
852  isdead = false;
853  break;
854  default:
855  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
856  isdead = false; /* keep compiler quiet */
857  break;
858  }
859 
861 
862  if (isdead)
863  {
864  *tups_vacuumed += 1;
865  /* heap rewrite module still needs to see it... */
866  if (rewrite_heap_dead_tuple(rwstate, tuple))
867  {
868  /* A previous recently-dead tuple is now known dead */
869  *tups_vacuumed += 1;
870  *tups_recently_dead -= 1;
871  }
872  continue;
873  }
874 
875  *num_tuples += 1;
876  if (tuplesort != NULL)
877  {
878  tuplesort_putheaptuple(tuplesort, tuple);
879 
880  /*
881  * In scan-and-sort mode, report increase in number of tuples
882  * scanned
883  */
885  *num_tuples);
886  }
887  else
888  {
889  const int ct_index[] = {
892  };
893  int64 ct_val[2];
894 
895  reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
896  values, isnull, rwstate);
897 
898  /*
899  * In indexscan mode and also VACUUM FULL, report increase in
900  * number of tuples scanned and written
901  */
902  ct_val[0] = *num_tuples;
903  ct_val[1] = *num_tuples;
904  pgstat_progress_update_multi_param(2, ct_index, ct_val);
905  }
906  }
907 
908  if (indexScan != NULL)
909  index_endscan(indexScan);
910  if (tableScan != NULL)
911  table_endscan(tableScan);
912  if (slot)
914 
915  /*
916  * In scan-and-sort mode, complete the sort, then read out all live tuples
917  * from the tuplestore and write them to the new relation.
918  */
919  if (tuplesort != NULL)
920  {
921  double n_tuples = 0;
922 
923  /* Report that we are now sorting tuples */
926 
927  tuplesort_performsort(tuplesort);
928 
929  /* Report that we are now writing new heap */
932 
933  for (;;)
934  {
935  HeapTuple tuple;
936 
938 
939  tuple = tuplesort_getheaptuple(tuplesort, true);
940  if (tuple == NULL)
941  break;
942 
943  n_tuples += 1;
945  OldHeap, NewHeap,
946  values, isnull,
947  rwstate);
948  /* Report n_tuples */
950  n_tuples);
951  }
952 
953  tuplesort_end(tuplesort);
954  }
955 
956  /* Write out any remaining tuples, and fsync if needed */
957  end_heap_rewrite(rwstate);
958 
959  /* Clean up */
960  pfree(values);
961  pfree(isnull);
962 }
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:1964
void end_heap_rewrite(RewriteState state)
Definition: rewriteheap.c:301
HeapTuple tuplesort_getheaptuple(Tuplesortstate *state, bool forward)
Definition: tuplesort.c:2369
bool IsSystemRelation(Relation relation)
Definition: catalog.c:68
#define PROGRESS_CLUSTER_HEAP_TUPLES_WRITTEN
Definition: progress.h:59
#define RelationGetDescr(relation)
Definition: rel.h:482
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)
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3231
Tuplesortstate * tuplesort_begin_cluster(TupleDesc tupDesc, Relation indexRel, int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:952
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:295
#define PROGRESS_CLUSTER_INDEX_RELID
Definition: progress.h:57
#define PROGRESS_CLUSTER_PHASE_WRITE_NEW_HEAP
Definition: progress.h:68
static bool table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:904
#define RelationGetTargetBlock(relation)
Definition: rel.h:541
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:73
HeapTupleHeader t_data
Definition: htup.h:68
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ERROR
Definition: elog.h:43
static TableScanDesc table_beginscan(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key)
Definition: tableam.h:755
#define PROGRESS_CLUSTER_PHASE_SORT_TUPLES
Definition: progress.h:67
static char * buf
Definition: pg_test_fsync.c:67
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
#define PROGRESS_CLUSTER_HEAP_TUPLES_SCANNED
Definition: progress.h:58
#define RelationGetRelationName(relation)
Definition: rel.h:490
static TransactionId OldestXmin
Definition: vacuumlazy.c:332
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:321
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1614
#define WARNING
Definition: elog.h:40
uintptr_t Datum
Definition: postgres.h:367
BlockNumber rs_nblocks
Definition: heapam.h:52
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3757
int maintenance_work_mem
Definition: globals.c:123
#define Assert(condition)
Definition: c.h:745
#define PROGRESS_CLUSTER_PHASE_INDEX_SCAN_HEAP
Definition: progress.h:66
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:313
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
Definition: pgstat.c:3253
#define InvalidBlockNumber
Definition: block.h:33
bool index_getnext_slot(IndexScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition: indexam.c:613
#define SnapshotAny
Definition: snapmgr.h:69
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:863
static Datum values[MAXATTR]
Definition: bootstrap.c:167
bool rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
Definition: rewriteheap.c:565
void * palloc(Size size)
Definition: mcxt.c:949
#define elog(elevel,...)
Definition: elog.h:214
void tuplesort_putheaptuple(Tuplesortstate *state, HeapTuple tup)
Definition: tuplesort.c:1630
#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:99
#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:1388
#define PROGRESS_CLUSTER_PHASE
Definition: progress.h:56
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:456
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:203

◆ heapam_relation_needs_toast_table()

static bool heapam_relation_needs_toast_table ( Relation  rel)
static

Definition at line 1983 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().

1984 {
1985  int32 data_length = 0;
1986  bool maxlength_unknown = false;
1987  bool has_toastable_attrs = false;
1988  TupleDesc tupdesc = rel->rd_att;
1989  int32 tuple_length;
1990  int i;
1991 
1992  for (i = 0; i < tupdesc->natts; i++)
1993  {
1994  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1995 
1996  if (att->attisdropped)
1997  continue;
1998  data_length = att_align_nominal(data_length, att->attalign);
1999  if (att->attlen > 0)
2000  {
2001  /* Fixed-length types are never toastable */
2002  data_length += att->attlen;
2003  }
2004  else
2005  {
2006  int32 maxlen = type_maximum_size(att->atttypid,
2007  att->atttypmod);
2008 
2009  if (maxlen < 0)
2010  maxlength_unknown = true;
2011  else
2012  data_length += maxlen;
2013  if (att->attstorage != TYPSTORAGE_PLAIN)
2014  has_toastable_attrs = true;
2015  }
2016  }
2017  if (!has_toastable_attrs)
2018  return false; /* nothing to toast? */
2019  if (maxlength_unknown)
2020  return true; /* any unlimited-length attrs? */
2021  tuple_length = MAXALIGN(SizeofHeapTupleHeader +
2022  BITMAPLEN(tupdesc->natts)) +
2023  MAXALIGN(data_length);
2024  return (tuple_length > TOAST_TUPLE_THRESHOLD);
2025 }
#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:547
signed int int32
Definition: c.h:362
int32 type_maximum_size(Oid type_oid, int32 typemod)
Definition: format_type.c:408
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
#define TOAST_TUPLE_THRESHOLD
Definition: heaptoast.h:48
TupleDesc rd_att
Definition: rel.h:110
#define MAXALIGN(LEN)
Definition: c.h:698
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:257
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition: smgr.c:334
TransactionId RecentXmin
Definition: snapmgr.c:167
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:2489
#define Assert(condition)
Definition: c.h:745
void smgrimmedsync(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:643
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 2031 of file heapam_handler.c.

References RelationData::rd_rel.

Referenced by SampleHeapTupleVisible().

2032 {
2033  return rel->rd_rel->relam;
2034 }
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 965 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().

967 {
968  HeapScanDesc hscan = (HeapScanDesc) scan;
969 
970  /*
971  * We must maintain a pin on the target page's buffer to ensure that
972  * concurrent activity - e.g. HOT pruning - doesn't delete tuples out from
973  * under us. Hence, pin the page until we are done looking at it. We
974  * also choose to hold sharelock on the buffer throughout --- we could
975  * release and re-acquire sharelock for each tuple, but since we aren't
976  * doing much work per tuple, the extra lock traffic is probably better
977  * avoided.
978  */
979  hscan->rs_cblock = blockno;
980  hscan->rs_cindex = FirstOffsetNumber;
982  blockno, RBM_NORMAL, bstrategy);
984 
985  /* in heap all blocks can contain tuples, so always return true */
986  return true;
987 }
BlockNumber rs_cblock
Definition: heapam.h:59
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:653
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:73
#define FirstOffsetNumber
Definition: off.h:27
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3757
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 990 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().

993 {
994  HeapScanDesc hscan = (HeapScanDesc) scan;
995  Page targpage;
996  OffsetNumber maxoffset;
998 
999  Assert(TTS_IS_BUFFERTUPLE(slot));
1000 
1001  hslot = (BufferHeapTupleTableSlot *) slot;
1002  targpage = BufferGetPage(hscan->rs_cbuf);
1003  maxoffset = PageGetMaxOffsetNumber(targpage);
1004 
1005  /* Inner loop over all tuples on the selected page */
1006  for (; hscan->rs_cindex <= maxoffset; hscan->rs_cindex++)
1007  {
1008  ItemId itemid;
1009  HeapTuple targtuple = &hslot->base.tupdata;
1010  bool sample_it = false;
1011 
1012  itemid = PageGetItemId(targpage, hscan->rs_cindex);
1013 
1014  /*
1015  * We ignore unused and redirect line pointers. DEAD line pointers
1016  * should be counted as dead, because we need vacuum to run to get rid
1017  * of them. Note that this rule agrees with the way that
1018  * heap_page_prune() counts things.
1019  */
1020  if (!ItemIdIsNormal(itemid))
1021  {
1022  if (ItemIdIsDead(itemid))
1023  *deadrows += 1;
1024  continue;
1025  }
1026 
1027  ItemPointerSet(&targtuple->t_self, hscan->rs_cblock, hscan->rs_cindex);
1028 
1029  targtuple->t_tableOid = RelationGetRelid(scan->rs_rd);
1030  targtuple->t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
1031  targtuple->t_len = ItemIdGetLength(itemid);
1032 
1033  switch (HeapTupleSatisfiesVacuum(targtuple, OldestXmin,
1034  hscan->rs_cbuf))
1035  {
1036  case HEAPTUPLE_LIVE:
1037  sample_it = true;
1038  *liverows += 1;
1039  break;
1040 
1041  case HEAPTUPLE_DEAD:
1043  /* Count dead and recently-dead rows */
1044  *deadrows += 1;
1045  break;
1046 
1048 
1049  /*
1050  * Insert-in-progress rows are not counted. We assume that
1051  * when the inserting transaction commits or aborts, it will
1052  * send a stats message to increment the proper count. This
1053  * works right only if that transaction ends after we finish
1054  * analyzing the table; if things happen in the other order,
1055  * its stats update will be overwritten by ours. However, the
1056  * error will be large only if the other transaction runs long
1057  * enough to insert many tuples, so assuming it will finish
1058  * after us is the safer option.
1059  *
1060  * A special case is that the inserting transaction might be
1061  * our own. In this case we should count and sample the row,
1062  * to accommodate users who load a table and analyze it in one
1063  * transaction. (pgstat_report_analyze has to adjust the
1064  * numbers we send to the stats collector to make this come
1065  * out right.)
1066  */
1068  {
1069  sample_it = true;
1070  *liverows += 1;
1071  }
1072  break;
1073 
1075 
1076  /*
1077  * We count and sample delete-in-progress rows the same as
1078  * live ones, so that the stats counters come out right if the
1079  * deleting transaction commits after us, per the same
1080  * reasoning given above.
1081  *
1082  * If the delete was done by our own transaction, however, we
1083  * must count the row as dead to make pgstat_report_analyze's
1084  * stats adjustments come out right. (Note: this works out
1085  * properly when the row was both inserted and deleted in our
1086  * xact.)
1087  *
1088  * The net effect of these choices is that we act as though an
1089  * IN_PROGRESS transaction hasn't happened yet, except if it
1090  * is our own transaction, which we assume has happened.
1091  *
1092  * This approach ensures that we behave sanely if we see both
1093  * the pre-image and post-image rows for a row being updated
1094  * by a concurrent transaction: we will sample the pre-image
1095  * but not the post-image. We also get sane results if the
1096  * concurrent transaction never commits.
1097  */
1099  *deadrows += 1;
1100  else
1101  {
1102  sample_it = true;
1103  *liverows += 1;
1104  }
1105  break;
1106 
1107  default:
1108  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1109  break;
1110  }
1111 
1112  if (sample_it)
1113  {
1114  ExecStoreBufferHeapTuple(targtuple, slot, hscan->rs_cbuf);
1115  hscan->rs_cindex++;
1116 
1117  /* note that we leave the buffer locked here! */
1118  return true;
1119  }
1120  }
1121 
1122  /* Now release the lock and pin on the page */
1123  UnlockReleaseBuffer(hscan->rs_cbuf);
1124  hscan->rs_cbuf = InvalidBuffer;
1125 
1126  /* also prevent old slot contents from having pin on page */
1127  ExecClearTuple(slot);
1128 
1129  return false;
1130 }
#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:73
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:3541
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
static TransactionId OldestXmin
Definition: vacuumlazy.c:332
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:1362
Buffer rs_cbuf
Definition: heapam.h:60
#define Assert(condition)
Definition: c.h:745
#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:214
HeapTupleTableSlot base
Definition: tuptable.h:259
HeapTupleData tupdata
Definition: tuptable.h:253
#define RelationGetRelid(relation)
Definition: rel.h:456
#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 2065 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().

2067 {
2068  HeapScanDesc hscan = (HeapScanDesc) scan;
2069  BlockNumber page = tbmres->blockno;
2070  Buffer buffer;
2071  Snapshot snapshot;
2072  int ntup;
2073 
2074  hscan->rs_cindex = 0;
2075  hscan->rs_ntuples = 0;
2076 
2077  /*
2078  * Ignore any claimed entries past what we think is the end of the
2079  * relation. It may have been extended after the start of our scan (we
2080  * only hold an AccessShareLock, and it could be inserts from this
2081  * backend).
2082  */
2083  if (page >= hscan->rs_nblocks)
2084  return false;
2085 
2086  /*
2087  * Acquire pin on the target heap page, trading in any pin we held before.
2088  */
2089  hscan->rs_cbuf = ReleaseAndReadBuffer(hscan->rs_cbuf,
2090  scan->rs_rd,
2091  page);
2092  hscan->rs_cblock = page;
2093  buffer = hscan->rs_cbuf;
2094  snapshot = scan->rs_snapshot;
2095 
2096  ntup = 0;
2097 
2098  /*
2099  * Prune and repair fragmentation for the whole page, if possible.
2100  */
2101  heap_page_prune_opt(scan->rs_rd, buffer);
2102 
2103  /*
2104  * We must hold share lock on the buffer content while examining tuple
2105  * visibility. Afterwards, however, the tuples we have found to be
2106  * visible are guaranteed good as long as we hold the buffer pin.
2107  */
2108  LockBuffer(buffer, BUFFER_LOCK_SHARE);
2109 
2110  /*
2111  * We need two separate strategies for lossy and non-lossy cases.
2112  */
2113  if (tbmres->ntuples >= 0)
2114  {
2115  /*
2116  * Bitmap is non-lossy, so we just look through the offsets listed in
2117  * tbmres; but we have to follow any HOT chain starting at each such
2118  * offset.
2119  */
2120  int curslot;
2121 
2122  for (curslot = 0; curslot < tbmres->ntuples; curslot++)
2123  {
2124  OffsetNumber offnum = tbmres->offsets[curslot];
2125  ItemPointerData tid;
2126  HeapTupleData heapTuple;
2127 
2128  ItemPointerSet(&tid, page, offnum);
2129  if (heap_hot_search_buffer(&tid, scan->rs_rd, buffer, snapshot,
2130  &heapTuple, NULL, true))
2131  hscan->rs_vistuples[ntup++] = ItemPointerGetOffsetNumber(&tid);
2132  }
2133  }
2134  else
2135  {
2136  /*
2137  * Bitmap is lossy, so we must examine each line pointer on the page.
2138  * But we can ignore HOT chains, since we'll check each tuple anyway.
2139  */
2140  Page dp = (Page) BufferGetPage(buffer);
2141  OffsetNumber maxoff = PageGetMaxOffsetNumber(dp);
2142  OffsetNumber offnum;
2143 
2144  for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum))
2145  {
2146  ItemId lp;
2147  HeapTupleData loctup;
2148  bool valid;
2149 
2150  lp = PageGetItemId(dp, offnum);
2151  if (!ItemIdIsNormal(lp))
2152  continue;
2153  loctup.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
2154  loctup.t_len = ItemIdGetLength(lp);
2155  loctup.t_tableOid = scan->rs_rd->rd_id;
2156  ItemPointerSet(&loctup.t_self, page, offnum);
2157  valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
2158  if (valid)
2159  {
2160  hscan->rs_vistuples[ntup++] = offnum;
2161  PredicateLockTID(scan->rs_rd, &loctup.t_self, snapshot,
2162  HeapTupleHeaderGetXmin(loctup.t_data));
2163  }
2164  HeapCheckForSerializableConflictOut(valid, scan->rs_rd, &loctup,
2165  buffer, snapshot);
2166  }
2167  }
2168 
2169  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2170 
2171  Assert(ntup <= MaxHeapTuplesPerPage);
2172  hscan->rs_ntuples = ntup;
2173 
2174  return ntup > 0;
2175 }
#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:574
uint32 BlockNumber
Definition: block.h:31
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:73
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:1509
#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:70
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
BlockNumber rs_nblocks
Definition: heapam.h:52
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3757
void PredicateLockTID(Relation relation, ItemPointer tid, Snapshot snapshot, TransactionId tuple_xid)
Definition: predicate.c:2545
void HeapCheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: heapam.c:9016
Buffer rs_cbuf
Definition: heapam.h:60
#define Assert(condition)
Definition: c.h:745
OffsetNumber rs_vistuples[MaxHeapTuplesPerPage]
Definition: heapam.h:71
#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:1532
#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:73
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 2178 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().

2181 {
2182  HeapScanDesc hscan = (HeapScanDesc) scan;
2183  OffsetNumber targoffset;
2184  Page dp;
2185  ItemId lp;
2186 
2187  /*
2188  * Out of range? If so, nothing more to look at on this page
2189  */
2190  if (hscan->rs_cindex < 0 || hscan->rs_cindex >= hscan->rs_ntuples)
2191  return false;
2192 
2193  targoffset = hscan->rs_vistuples[hscan->rs_cindex];
2194  dp = (Page) BufferGetPage(hscan->rs_cbuf);
2195  lp = PageGetItemId(dp, targoffset);
2196  Assert(ItemIdIsNormal(lp));
2197 
2198  hscan->rs_ctup.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
2199  hscan->rs_ctup.t_len = ItemIdGetLength(lp);
2200  hscan->rs_ctup.t_tableOid = scan->rs_rd->rd_id;
2201  ItemPointerSet(&hscan->rs_ctup.t_self, hscan->rs_cblock, targoffset);
2202 
2204 
2205  /*
2206  * Set up the result slot to point to this tuple. Note that the slot
2207  * acquires a pin on the buffer.
2208  */
2210  slot,
2211  hscan->rs_cbuf);
2212 
2213  hscan->rs_cindex++;
2214 
2215  return true;
2216 }
BlockNumber rs_cblock
Definition: heapam.h:59
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:73
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:1407
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:70
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1362
Buffer rs_cbuf
Definition: heapam.h:60
#define Assert(condition)
Definition: c.h:745
OffsetNumber rs_vistuples[MaxHeapTuplesPerPage]
Definition: heapam.h:71
#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 1938 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().

1939 {
1940  ParallelBlockTableScanDesc bpscan = NULL;
1941  BlockNumber startblock;
1942  BlockNumber blocks_done;
1943 
1944  if (hscan->rs_base.rs_parallel != NULL)
1945  {
1947  startblock = bpscan->phs_startblock;
1948  }
1949  else
1950  startblock = hscan->rs_startblock;
1951 
1952  /*
1953  * Might have wrapped around the end of the relation, if startblock was
1954  * not zero.
1955  */
1956  if (hscan->rs_cblock > startblock)
1957  blocks_done = hscan->rs_cblock - startblock;
1958  else
1959  {
1960  BlockNumber nblocks;
1961 
1962  nblocks = bpscan != NULL ? bpscan->phs_nblocks : hscan->rs_nblocks;
1963  blocks_done = nblocks - startblock +
1964  hscan->rs_cblock;
1965  }
1966 
1967  return blocks_done;
1968 }
BlockNumber rs_cblock
Definition: heapam.h:59
struct ParallelBlockTableScanDescData * ParallelBlockTableScanDesc
Definition: relscan.h:82
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:46

◆ heapam_scan_sample_next_block()

static bool heapam_scan_sample_next_block ( TableScanDesc  scan,
SampleScanState scanstate 
)
static

Definition at line 2219 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().

2220 {
2221  HeapScanDesc hscan = (HeapScanDesc) scan;
2222  TsmRoutine *tsm = scanstate->tsmroutine;
2223  BlockNumber blockno;
2224 
2225  /* return false immediately if relation is empty */
2226  if (hscan->rs_nblocks == 0)
2227  return false;
2228 
2229  if (tsm->NextSampleBlock)
2230  {
2231  blockno = tsm->NextSampleBlock(scanstate, hscan->rs_nblocks);
2232  hscan->rs_cblock = blockno;
2233  }
2234  else
2235  {
2236  /* scanning table sequentially */
2237 
2238  if (hscan->rs_cblock == InvalidBlockNumber)
2239  {
2240  Assert(!hscan->rs_inited);
2241  blockno = hscan->rs_startblock;
2242  }
2243  else
2244  {
2245  Assert(hscan->rs_inited);
2246 
2247  blockno = hscan->rs_cblock + 1;
2248 
2249  if (blockno >= hscan->rs_nblocks)
2250  {
2251  /* wrap to beginning of rel, might not have started at 0 */
2252  blockno = 0;
2253  }
2254 
2255  /*
2256  * Report our new scan position for synchronization purposes.
2257  *
2258  * Note: we do this before checking for end of scan so that the
2259  * final state of the position hint is back at the start of the
2260  * rel. That's not strictly necessary, but otherwise when you run
2261  * the same query multiple times the starting position would shift
2262  * a little bit backwards on every invocation, which is confusing.
2263  * We don't guarantee any specific ordering in general, though.
2264  */
2265  if (scan->rs_flags & SO_ALLOW_SYNC)
2266  ss_report_location(scan->rs_rd, blockno);
2267 
2268  if (blockno == hscan->rs_startblock)
2269  {
2270  blockno = InvalidBlockNumber;
2271  }
2272  }
2273  }
2274 
2275  if (!BlockNumberIsValid(blockno))
2276  {
2277  if (BufferIsValid(hscan->rs_cbuf))
2278  ReleaseBuffer(hscan->rs_cbuf);
2279  hscan->rs_cbuf = InvalidBuffer;
2280  hscan->rs_cblock = InvalidBlockNumber;
2281  hscan->rs_inited = false;
2282 
2283  return false;
2284  }
2285 
2286  heapgetpage(scan, blockno);
2287  hscan->rs_inited = true;
2288 
2289  return true;
2290 }
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:3518
uint32 rs_flags
Definition: relscan.h:43
void heapgetpage(TableScanDesc sscan, BlockNumber page)
Definition: heapam.c:353
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:73
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:745
#define InvalidBlockNumber
Definition: block.h:33
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
struct TsmRoutine * tsmroutine
Definition: execnodes.h:1358
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 2293 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().

2295 {
2296  HeapScanDesc hscan = (HeapScanDesc) scan;
2297  TsmRoutine *tsm = scanstate->tsmroutine;
2298  BlockNumber blockno = hscan->rs_cblock;
2299  bool pagemode = (scan->rs_flags & SO_ALLOW_PAGEMODE) != 0;
2300 
2301  Page page;
2302  bool all_visible;
2303  OffsetNumber maxoffset;
2304 
2305  /*
2306  * When not using pagemode, we must lock the buffer during tuple
2307  * visibility checks.
2308  */
2309  if (!pagemode)
2311 
2312  page = (Page) BufferGetPage(hscan->rs_cbuf);
2313  all_visible = PageIsAllVisible(page) &&
2315  maxoffset = PageGetMaxOffsetNumber(page);
2316 
2317  for (;;)
2318  {
2319  OffsetNumber tupoffset;
2320 
2322 
2323  /* Ask the tablesample method which tuples to check on this page. */
2324  tupoffset = tsm->NextSampleTuple(scanstate,
2325  blockno,
2326  maxoffset);
2327 
2328  if (OffsetNumberIsValid(tupoffset))
2329  {
2330  ItemId itemid;
2331  bool visible;
2332  HeapTuple tuple = &(hscan->rs_ctup);
2333 
2334  /* Skip invalid tuple pointers. */
2335  itemid = PageGetItemId(page, tupoffset);
2336  if (!ItemIdIsNormal(itemid))
2337  continue;
2338 
2339  tuple->t_data = (HeapTupleHeader) PageGetItem(page, itemid);
2340  tuple->t_len = ItemIdGetLength(itemid);
2341  ItemPointerSet(&(tuple->t_self), blockno, tupoffset);
2342 
2343 
2344  if (all_visible)
2345  visible = true;
2346  else
2347  visible = SampleHeapTupleVisible(scan, hscan->rs_cbuf,
2348  tuple, tupoffset);
2349 
2350  /* in pagemode, heapgetpage did this for us */
2351  if (!pagemode)
2352  HeapCheckForSerializableConflictOut(visible, scan->rs_rd, tuple,
2353  hscan->rs_cbuf, scan->rs_snapshot);
2354 
2355  /* Try next tuple from same page. */
2356  if (!visible)
2357  continue;
2358 
2359  /* Found visible tuple, return it. */
2360  if (!pagemode)
2362 
2363  ExecStoreBufferHeapTuple(tuple, slot, hscan->rs_cbuf);
2364 
2365  /* Count successfully-fetched tuples as heap fetches */
2367 
2368  return true;
2369  }
2370  else
2371  {
2372  /*
2373  * If we get here, it means we've exhausted the items on this page
2374  * and it's time to move to the next.
2375  */
2376  if (!pagemode)
2378 
2379  ExecClearTuple(slot);
2380  return false;
2381  }
2382  }
2383 
2384  Assert(0);
2385 }
#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:43
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:73
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:3757
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1362
void HeapCheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: heapam.c:9016
Buffer rs_cbuf
Definition: heapam.h:60
#define Assert(condition)
Definition: c.h:745
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
bool takenDuringRecovery
Definition: snapshot.h:184
struct TsmRoutine * tsmroutine
Definition: execnodes.h:1358
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:99
#define pgstat_count_heap_getnext(rel)
Definition: pgstat.h:1402
#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:5561
void pfree(void *pointer)
Definition: mcxt.c:1056
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1614
void heap_finish_speculative(Relation relation, ItemPointer tid)
Definition: heapam.c:5470
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:2437

◆ 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:1852
Oid tts_tableOid
Definition: tuptable.h:131
void pfree(void *pointer)
Definition: mcxt.c:1056
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:1614
ItemPointerData tts_tid
Definition: tuptable.h:130
#define RelationGetRelid(relation)
Definition: rel.h:456
#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:1852
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:1056
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:1614
ItemPointerData tts_tid
Definition: tuptable.h:130
#define RelationGetRelid(relation)
Definition: rel.h:456
#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:125
static PgChecksumMode mode
Definition: pg_checksums.c:61
#define InitDirtySnapshot(snapshotdata)
Definition: snapmgr.h:76
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:520
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:1394
CommandId cmax
Definition: tableam.h:127
#define HeapTupleHeaderIsSpeculative(tup)
Definition: htup_details.h:429
int errcode(int sqlerrcode)
Definition: elog.c:610
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3518
#define TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS
Definition: tableam.h:139
bool ConditionalXactLockTableWait(TransactionId xid)
Definition: lmgr.c:697
HeapTupleHeader t_data
Definition: htup.h:68
TransactionId xmax
Definition: tableam.h:126
#define ERROR
Definition: elog.h:43
ItemPointerData t_ctid
Definition: htup_details.h:160
ItemPointerData t_self
Definition: htup.h:65
#define RelationGetRelationName(relation)
Definition: rel.h:490
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:45
TM_Result
Definition: tableam.h:70
#define TTS_IS_BUFFERTUPLE(slot)
Definition: tuptable.h:231
#define ItemPointerIndicatesMovedPartitions(pointer)
Definition: itemptr.h:184
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:624
#define Assert(condition)
Definition: c.h:745
#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:141
TupleTableSlot * ExecStorePinnedBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1388
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:3968
int errmsg(const char *fmt,...)
Definition: elog.c:824
HeapTupleTableSlot base
Definition: tuptable.h:259
#define TransactionIdIsValid(xid)
Definition: transam.h:41
bool traversed
Definition: tableam.h:128
HeapTupleData tupdata
Definition: tuptable.h:253
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ 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:3757
#define Assert(condition)
Definition: c.h:745
#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:73
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:1056
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:1614
TM_Result
Definition: tableam.h:70
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:685
Definition: tableam.h:76
TM_Result heap_update(Relation relation, ItemPointer otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode)
Definition: heapam.c:2888
ItemPointerData tts_tid
Definition: tuptable.h:130
#define RelationGetRelid(relation)
Definition: rel.h:456
#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 2410 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().

2413 {
2414  TupleDesc oldTupDesc = RelationGetDescr(OldHeap);
2415  TupleDesc newTupDesc = RelationGetDescr(NewHeap);
2416  HeapTuple copiedTuple;
2417  int i;
2418 
2419  heap_deform_tuple(tuple, oldTupDesc, values, isnull);
2420 
2421  /* Be sure to null out any dropped columns */
2422  for (i = 0; i < newTupDesc->natts; i++)
2423  {
2424  if (TupleDescAttr(newTupDesc, i)->attisdropped)
2425  isnull[i] = true;
2426  }
2427 
2428  copiedTuple = heap_form_tuple(newTupDesc, values, isnull);
2429 
2430  /* The heap rewrite module does the rest */
2431  rewrite_heap_tuple(rwstate, tuple, copiedTuple);
2432 
2433  heap_freetuple(copiedTuple);
2434 }
#define RelationGetDescr(relation)
Definition: rel.h:482
#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:167
int i
void rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple, HeapTuple new_tuple)
Definition: rewriteheap.c:363

◆ SampleHeapTupleVisible()

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

Definition at line 2440 of file heapam_handler.c.

References heap_beginscan(), heap_compute_xid_horizon_for_tuples(), heap_endscan(), heap_fetch_toast_slice(), heap_get_latest_tid(), heap_getnextslot(), heap_multi_insert(), heap_rescan(), 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().

2443 {
2444  HeapScanDesc hscan = (HeapScanDesc) scan;
2445 
2446  if (scan->rs_flags & SO_ALLOW_PAGEMODE)
2447  {
2448  /*
2449  * In pageatatime mode, heapgetpage() already did visibility checks,
2450  * so just look at the info it left in rs_vistuples[].
2451  *
2452  * We use a binary search over the known-sorted array. Note: we could
2453  * save some effort if we insisted that NextSampleTuple select tuples
2454  * in increasing order, but it's not clear that there would be enough
2455  * gain to justify the restriction.
2456  */
2457  int start = 0,
2458  end = hscan->rs_ntuples - 1;
2459 
2460  while (start <= end)
2461  {
2462  int mid = (start + end) / 2;
2463  OffsetNumber curoffset = hscan->rs_vistuples[mid];
2464 
2465  if (tupoffset == curoffset)
2466  return true;
2467  else if (tupoffset < curoffset)
2468  end = mid - 1;
2469  else
2470  start = mid + 1;
2471  }
2472 
2473  return false;
2474  }
2475  else
2476  {
2477  /* Otherwise, we have to check the tuple individually. */
2478  return HeapTupleSatisfiesVisibility(tuple, scan->rs_snapshot,
2479  buffer);
2480  }
2481 }
uint32 rs_flags
Definition: relscan.h:43
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:73
uint16 OffsetNumber
Definition: off.h:24
int rs_ntuples
Definition: heapam.h:70
OffsetNumber rs_vistuples[MaxHeapTuplesPerPage]
Definition: heapam.h:71
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().