PostgreSQL Source Code  git master
heapam_handler.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * heapam_handler.c
4  * heap table access method code
5  *
6  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/access/heap/heapam_handler.c
12  *
13  *
14  * NOTES
15  * This files wires up the lower level heapam.c et al routines with the
16  * tableam abstraction.
17  *
18  *-------------------------------------------------------------------------
19  */
20 #include "postgres.h"
21 
22 #include "access/genam.h"
23 #include "access/heapam.h"
24 #include "access/heaptoast.h"
25 #include "access/multixact.h"
26 #include "access/rewriteheap.h"
27 #include "access/syncscan.h"
28 #include "access/tableam.h"
29 #include "access/tsmapi.h"
30 #include "access/xact.h"
31 #include "catalog/catalog.h"
32 #include "catalog/index.h"
33 #include "catalog/storage.h"
34 #include "catalog/storage_xlog.h"
35 #include "commands/progress.h"
36 #include "executor/executor.h"
37 #include "miscadmin.h"
38 #include "pgstat.h"
39 #include "storage/bufmgr.h"
40 #include "storage/bufpage.h"
41 #include "storage/lmgr.h"
42 #include "storage/predicate.h"
43 #include "storage/procarray.h"
44 #include "storage/smgr.h"
45 #include "utils/builtins.h"
46 #include "utils/rel.h"
47 
48 static void reform_and_rewrite_tuple(HeapTuple tuple,
49  Relation OldHeap, Relation NewHeap,
50  Datum *values, bool *isnull, RewriteState rwstate);
51 
52 static bool SampleHeapTupleVisible(TableScanDesc scan, Buffer buffer,
53  HeapTuple tuple,
54  OffsetNumber tupoffset);
55 
57 
59 
60 
61 /* ------------------------------------------------------------------------
62  * Slot related callbacks for heap AM
63  * ------------------------------------------------------------------------
64  */
65 
66 static const TupleTableSlotOps *
68 {
69  return &TTSOpsBufferHeapTuple;
70 }
71 
72 
73 /* ------------------------------------------------------------------------
74  * Index Scan Callbacks for heap AM
75  * ------------------------------------------------------------------------
76  */
77 
78 static IndexFetchTableData *
80 {
82 
83  hscan->xs_base.rel = rel;
84  hscan->xs_cbuf = InvalidBuffer;
85 
86  return &hscan->xs_base;
87 }
88 
89 static void
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 }
100 
101 static void
103 {
104  IndexFetchHeapData *hscan = (IndexFetchHeapData *) scan;
105 
107 
108  pfree(hscan);
109 }
110 
111 static bool
113  ItemPointer tid,
114  Snapshot snapshot,
115  TupleTableSlot *slot,
116  bool *call_again, bool *all_dead)
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 }
172 
173 
174 /* ------------------------------------------------------------------------
175  * Callbacks for non-modifying operations on individual tuples for heap AM
176  * ------------------------------------------------------------------------
177  */
178 
179 static bool
181  ItemPointer tid,
182  Snapshot snapshot,
183  TupleTableSlot *slot)
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 }
202 
203 static bool
205 {
206  HeapScanDesc hscan = (HeapScanDesc) scan;
207 
208  return ItemPointerIsValid(tid) &&
210 }
211 
212 static bool
214  Snapshot snapshot)
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 }
233 
234 
235 /* ----------------------------------------------------------------------------
236  * Functions for manipulations of physical tuples for heap AM.
237  * ----------------------------------------------------------------------------
238  */
239 
240 static void
242  int options, BulkInsertState bistate)
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 }
258 
259 static void
261  CommandId cid, int options,
262  BulkInsertState bistate, uint32 specToken)
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 }
281 
282 static void
284  uint32 specToken, bool succeeded)
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 }
298 
299 static TM_Result
301  Snapshot snapshot, Snapshot crosscheck, bool wait,
302  TM_FailureData *tmfd, bool changingPart)
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 }
311 
312 
313 static TM_Result
315  CommandId cid, Snapshot snapshot, Snapshot crosscheck,
316  bool wait, TM_FailureData *tmfd,
317  LockTupleMode *lockmode, bool *update_indexes)
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 }
346 
347 static TM_Result
350  LockWaitPolicy wait_policy, uint8 flags,
351  TM_FailureData *tmfd)
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 %u is uncommitted in tuple (%u,%u) to be updated in table \"%s\"",
428  SnapshotDirty.xmin,
431  RelationGetRelationName(relation))));
432 
433  /*
434  * If tuple is being updated by other transaction then we
435  * have to wait for its commit/abort, or die trying.
436  */
437  if (TransactionIdIsValid(SnapshotDirty.xmax))
438  {
439  ReleaseBuffer(buffer);
440  switch (wait_policy)
441  {
442  case LockWaitBlock:
443  XactLockTableWait(SnapshotDirty.xmax,
444  relation, &tuple->t_self,
446  break;
447  case LockWaitSkip:
448  if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
449  /* skip instead of waiting */
450  return TM_WouldBlock;
451  break;
452  case LockWaitError:
453  if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
454  ereport(ERROR,
455  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
456  errmsg("could not obtain lock on row in relation \"%s\"",
457  RelationGetRelationName(relation))));
458  break;
459  }
460  continue; /* loop back to repeat heap_fetch */
461  }
462 
463  /*
464  * If tuple was inserted by our own transaction, we have
465  * to check cmin against cid: cmin >= current CID means
466  * our command cannot see the tuple, so we should ignore
467  * it. Otherwise heap_lock_tuple() will throw an error,
468  * and so would any later attempt to update or delete the
469  * tuple. (We need not check cmax because
470  * HeapTupleSatisfiesDirty will consider a tuple deleted
471  * by our transaction dead, regardless of cmax.) We just
472  * checked that priorXmax == xmin, so we can test that
473  * variable instead of doing HeapTupleHeaderGetXmin again.
474  */
475  if (TransactionIdIsCurrentTransactionId(priorXmax) &&
476  HeapTupleHeaderGetCmin(tuple->t_data) >= cid)
477  {
478  tmfd->xmax = priorXmax;
479 
480  /*
481  * Cmin is the problematic value, so store that. See
482  * above.
483  */
484  tmfd->cmax = HeapTupleHeaderGetCmin(tuple->t_data);
485  ReleaseBuffer(buffer);
486  return TM_SelfModified;
487  }
488 
489  /*
490  * This is a live tuple, so try to lock it again.
491  */
492  ReleaseBuffer(buffer);
493  goto tuple_lock_retry;
494  }
495 
496  /*
497  * If the referenced slot was actually empty, the latest
498  * version of the row must have been deleted, so we need do
499  * nothing.
500  */
501  if (tuple->t_data == NULL)
502  {
503  return TM_Deleted;
504  }
505 
506  /*
507  * As above, if xmin isn't what we're expecting, do nothing.
508  */
510  priorXmax))
511  {
512  if (BufferIsValid(buffer))
513  ReleaseBuffer(buffer);
514  return TM_Deleted;
515  }
516 
517  /*
518  * If we get here, the tuple was found but failed
519  * SnapshotDirty. Assuming the xmin is either a committed xact
520  * or our own xact (as it certainly should be if we're trying
521  * to modify the tuple), this must mean that the row was
522  * updated or deleted by either a committed xact or our own
523  * xact. If it was deleted, we can ignore it; if it was
524  * updated then chain up to the next version and repeat the
525  * whole process.
526  *
527  * As above, it should be safe to examine xmax and t_ctid
528  * without the buffer content lock, because they can't be
529  * changing.
530  */
531  if (ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
532  {
533  /* deleted, so forget about it */
534  if (BufferIsValid(buffer))
535  ReleaseBuffer(buffer);
536  return TM_Deleted;
537  }
538 
539  /* updated, so look at the updated row */
540  *tid = tuple->t_data->t_ctid;
541  /* updated row should have xmin matching this xmax */
542  priorXmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
543  if (BufferIsValid(buffer))
544  ReleaseBuffer(buffer);
545  /* loop back to fetch next in chain */
546  }
547  }
548  else
549  {
550  /* tuple was deleted, so give up */
551  return TM_Deleted;
552  }
553  }
554 
555  slot->tts_tableOid = RelationGetRelid(relation);
556  tuple->t_tableOid = slot->tts_tableOid;
557 
558  /* store in slot, transferring existing pin */
559  ExecStorePinnedBufferHeapTuple(tuple, slot, buffer);
560 
561  return result;
562 }
563 
564 
565 /* ------------------------------------------------------------------------
566  * DDL related callbacks for heap AM.
567  * ------------------------------------------------------------------------
568  */
569 
570 static void
572  const RelFileNode *newrnode,
573  char persistence,
574  TransactionId *freezeXid,
575  MultiXactId *minmulti)
576 {
577  SMgrRelation srel;
578 
579  /*
580  * Initialize to the minimum XID that could put tuples in the table. We
581  * know that no xacts older than RecentXmin are still running, so that
582  * will do.
583  */
584  *freezeXid = RecentXmin;
585 
586  /*
587  * Similarly, initialize the minimum Multixact to the first value that
588  * could possibly be stored in tuples in the table. Running transactions
589  * could reuse values from their local cache, so we are careful to
590  * consider all currently running multis.
591  *
592  * XXX this could be refined further, but is it worth the hassle?
593  */
594  *minmulti = GetOldestMultiXactId();
595 
596  srel = RelationCreateStorage(*newrnode, persistence);
597 
598  /*
599  * If required, set up an init fork for an unlogged table so that it can
600  * be correctly reinitialized on restart. An immediate sync is required
601  * even if the page has been logged, because the write did not go through
602  * shared_buffers and therefore a concurrent checkpoint may have moved the
603  * redo pointer past our xlog record. Recovery may as well remove it
604  * while replaying, for example, XLOG_DBASE_CREATE or XLOG_TBLSPC_CREATE
605  * record. Therefore, logging is necessary even if wal_level=minimal.
606  */
607  if (persistence == RELPERSISTENCE_UNLOGGED)
608  {
609  Assert(rel->rd_rel->relkind == RELKIND_RELATION ||
610  rel->rd_rel->relkind == RELKIND_MATVIEW ||
611  rel->rd_rel->relkind == RELKIND_TOASTVALUE);
612  smgrcreate(srel, INIT_FORKNUM, false);
613  log_smgrcreate(newrnode, INIT_FORKNUM);
615  }
616 
617  smgrclose(srel);
618 }
619 
620 static void
622 {
623  RelationTruncate(rel, 0);
624 }
625 
626 static void
628 {
629  SMgrRelation dstrel;
630 
631  dstrel = smgropen(*newrnode, rel->rd_backend);
632 
633  /*
634  * Since we copy the file directly without looking at the shared buffers,
635  * we'd better first flush out any pages of the source relation that are
636  * in shared buffers. We assume no new changes will be made while we are
637  * holding exclusive lock on the rel.
638  */
640 
641  /*
642  * Create and copy all forks of the relation, and schedule unlinking of
643  * old physical files.
644  *
645  * NOTE: any conflict in relfilenode value will be caught in
646  * RelationCreateStorage().
647  */
648  RelationCreateStorage(*newrnode, rel->rd_rel->relpersistence);
649 
650  /* copy main fork */
652  rel->rd_rel->relpersistence);
653 
654  /* copy those extra forks that exist */
655  for (ForkNumber forkNum = MAIN_FORKNUM + 1;
656  forkNum <= MAX_FORKNUM; forkNum++)
657  {
658  if (smgrexists(RelationGetSmgr(rel), forkNum))
659  {
660  smgrcreate(dstrel, forkNum, false);
661 
662  /*
663  * WAL log creation if the relation is persistent, or this is the
664  * init fork of an unlogged relation.
665  */
666  if (RelationIsPermanent(rel) ||
667  (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
668  forkNum == INIT_FORKNUM))
669  log_smgrcreate(newrnode, forkNum);
670  RelationCopyStorage(RelationGetSmgr(rel), dstrel, forkNum,
671  rel->rd_rel->relpersistence);
672  }
673  }
674 
675 
676  /* drop old relation, and close new one */
677  RelationDropStorage(rel);
678  smgrclose(dstrel);
679 }
680 
681 static void
683  Relation OldIndex, bool use_sort,
684  TransactionId OldestXmin,
685  TransactionId *xid_cutoff,
686  MultiXactId *multi_cutoff,
687  double *num_tuples,
688  double *tups_vacuumed,
689  double *tups_recently_dead)
690 {
691  RewriteState rwstate;
692  IndexScanDesc indexScan;
693  TableScanDesc tableScan;
694  HeapScanDesc heapScan;
695  bool is_system_catalog;
696  Tuplesortstate *tuplesort;
697  TupleDesc oldTupDesc = RelationGetDescr(OldHeap);
698  TupleDesc newTupDesc = RelationGetDescr(NewHeap);
699  TupleTableSlot *slot;
700  int natts;
701  Datum *values;
702  bool *isnull;
704  BlockNumber prev_cblock = InvalidBlockNumber;
705 
706  /* Remember if it's a system catalog */
707  is_system_catalog = IsSystemRelation(OldHeap);
708 
709  /*
710  * Valid smgr_targblock implies something already wrote to the relation.
711  * This may be harmless, but this function hasn't planned for it.
712  */
714 
715  /* Preallocate values/isnull arrays */
716  natts = newTupDesc->natts;
717  values = (Datum *) palloc(natts * sizeof(Datum));
718  isnull = (bool *) palloc(natts * sizeof(bool));
719 
720  /* Initialize the rewrite operation */
721  rwstate = begin_heap_rewrite(OldHeap, NewHeap, OldestXmin, *xid_cutoff,
722  *multi_cutoff);
723 
724 
725  /* Set up sorting if wanted */
726  if (use_sort)
727  tuplesort = tuplesort_begin_cluster(oldTupDesc, OldIndex,
729  NULL, false);
730  else
731  tuplesort = NULL;
732 
733  /*
734  * Prepare to scan the OldHeap. To ensure we see recently-dead tuples
735  * that still need to be copied, we scan with SnapshotAny and use
736  * HeapTupleSatisfiesVacuum for the visibility test.
737  */
738  if (OldIndex != NULL && !use_sort)
739  {
740  const int ci_index[] = {
743  };
744  int64 ci_val[2];
745 
746  /* Set phase and OIDOldIndex to columns */
748  ci_val[1] = RelationGetRelid(OldIndex);
749  pgstat_progress_update_multi_param(2, ci_index, ci_val);
750 
751  tableScan = NULL;
752  heapScan = NULL;
753  indexScan = index_beginscan(OldHeap, OldIndex, SnapshotAny, 0, 0);
754  index_rescan(indexScan, NULL, 0, NULL, 0);
755  }
756  else
757  {
758  /* In scan-and-sort mode and also VACUUM FULL, set phase */
761 
762  tableScan = table_beginscan(OldHeap, SnapshotAny, 0, (ScanKey) NULL);
763  heapScan = (HeapScanDesc) tableScan;
764  indexScan = NULL;
765 
766  /* Set total heap blocks */
768  heapScan->rs_nblocks);
769  }
770 
771  slot = table_slot_create(OldHeap, NULL);
772  hslot = (BufferHeapTupleTableSlot *) slot;
773 
774  /*
775  * Scan through the OldHeap, either in OldIndex order or sequentially;
776  * copy each tuple into the NewHeap, or transiently to the tuplesort
777  * module. Note that we don't bother sorting dead tuples (they won't get
778  * to the new table anyway).
779  */
780  for (;;)
781  {
782  HeapTuple tuple;
783  Buffer buf;
784  bool isdead;
785 
787 
788  if (indexScan != NULL)
789  {
790  if (!index_getnext_slot(indexScan, ForwardScanDirection, slot))
791  break;
792 
793  /* Since we used no scan keys, should never need to recheck */
794  if (indexScan->xs_recheck)
795  elog(ERROR, "CLUSTER does not support lossy index conditions");
796  }
797  else
798  {
799  if (!table_scan_getnextslot(tableScan, ForwardScanDirection, slot))
800  {
801  /*
802  * If the last pages of the scan were empty, we would go to
803  * the next phase while heap_blks_scanned != heap_blks_total.
804  * Instead, to ensure that heap_blks_scanned is equivalent to
805  * total_heap_blks after the table scan phase, this parameter
806  * is manually updated to the correct value when the table
807  * scan finishes.
808  */
810  heapScan->rs_nblocks);
811  break;
812  }
813 
814  /*
815  * In scan-and-sort mode and also VACUUM FULL, set heap blocks
816  * scanned
817  *
818  * Note that heapScan may start at an offset and wrap around, i.e.
819  * rs_startblock may be >0, and rs_cblock may end with a number
820  * below rs_startblock. To prevent showing this wraparound to the
821  * user, we offset rs_cblock by rs_startblock (modulo rs_nblocks).
822  */
823  if (prev_cblock != heapScan->rs_cblock)
824  {
826  (heapScan->rs_cblock +
827  heapScan->rs_nblocks -
828  heapScan->rs_startblock
829  ) % heapScan->rs_nblocks + 1);
830  prev_cblock = heapScan->rs_cblock;
831  }
832  }
833 
834  tuple = ExecFetchSlotHeapTuple(slot, false, NULL);
835  buf = hslot->buffer;
836 
838 
839  switch (HeapTupleSatisfiesVacuum(tuple, OldestXmin, buf))
840  {
841  case HEAPTUPLE_DEAD:
842  /* Definitely dead */
843  isdead = true;
844  break;
846  *tups_recently_dead += 1;
847  /* fall through */
848  case HEAPTUPLE_LIVE:
849  /* Live or recently dead, must copy it */
850  isdead = false;
851  break;
853 
854  /*
855  * Since we hold exclusive lock on the relation, normally the
856  * only way to see this is if it was inserted earlier in our
857  * own transaction. However, it can happen in system
858  * catalogs, since we tend to release write lock before commit
859  * there. Give a warning if neither case applies; but in any
860  * case we had better copy it.
861  */
862  if (!is_system_catalog &&
864  elog(WARNING, "concurrent insert in progress within table \"%s\"",
865  RelationGetRelationName(OldHeap));
866  /* treat as live */
867  isdead = false;
868  break;
870 
871  /*
872  * Similar situation to INSERT_IN_PROGRESS case.
873  */
874  if (!is_system_catalog &&
876  elog(WARNING, "concurrent delete in progress within table \"%s\"",
877  RelationGetRelationName(OldHeap));
878  /* treat as recently dead */
879  *tups_recently_dead += 1;
880  isdead = false;
881  break;
882  default:
883  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
884  isdead = false; /* keep compiler quiet */
885  break;
886  }
887 
889 
890  if (isdead)
891  {
892  *tups_vacuumed += 1;
893  /* heap rewrite module still needs to see it... */
894  if (rewrite_heap_dead_tuple(rwstate, tuple))
895  {
896  /* A previous recently-dead tuple is now known dead */
897  *tups_vacuumed += 1;
898  *tups_recently_dead -= 1;
899  }
900  continue;
901  }
902 
903  *num_tuples += 1;
904  if (tuplesort != NULL)
905  {
906  tuplesort_putheaptuple(tuplesort, tuple);
907 
908  /*
909  * In scan-and-sort mode, report increase in number of tuples
910  * scanned
911  */
913  *num_tuples);
914  }
915  else
916  {
917  const int ct_index[] = {
920  };
921  int64 ct_val[2];
922 
923  reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
924  values, isnull, rwstate);
925 
926  /*
927  * In indexscan mode and also VACUUM FULL, report increase in
928  * number of tuples scanned and written
929  */
930  ct_val[0] = *num_tuples;
931  ct_val[1] = *num_tuples;
932  pgstat_progress_update_multi_param(2, ct_index, ct_val);
933  }
934  }
935 
936  if (indexScan != NULL)
937  index_endscan(indexScan);
938  if (tableScan != NULL)
939  table_endscan(tableScan);
940  if (slot)
942 
943  /*
944  * In scan-and-sort mode, complete the sort, then read out all live tuples
945  * from the tuplestore and write them to the new relation.
946  */
947  if (tuplesort != NULL)
948  {
949  double n_tuples = 0;
950 
951  /* Report that we are now sorting tuples */
954 
955  tuplesort_performsort(tuplesort);
956 
957  /* Report that we are now writing new heap */
960 
961  for (;;)
962  {
963  HeapTuple tuple;
964 
966 
967  tuple = tuplesort_getheaptuple(tuplesort, true);
968  if (tuple == NULL)
969  break;
970 
971  n_tuples += 1;
973  OldHeap, NewHeap,
974  values, isnull,
975  rwstate);
976  /* Report n_tuples */
978  n_tuples);
979  }
980 
981  tuplesort_end(tuplesort);
982  }
983 
984  /* Write out any remaining tuples, and fsync if needed */
985  end_heap_rewrite(rwstate);
986 
987  /* Clean up */
988  pfree(values);
989  pfree(isnull);
990 }
991 
992 static bool
994  BufferAccessStrategy bstrategy)
995 {
996  HeapScanDesc hscan = (HeapScanDesc) scan;
997 
998  /*
999  * We must maintain a pin on the target page's buffer to ensure that
1000  * concurrent activity - e.g. HOT pruning - doesn't delete tuples out from
1001  * under us. Hence, pin the page until we are done looking at it. We
1002  * also choose to hold sharelock on the buffer throughout --- we could
1003  * release and re-acquire sharelock for each tuple, but since we aren't
1004  * doing much work per tuple, the extra lock traffic is probably better
1005  * avoided.
1006  */
1007  hscan->rs_cblock = blockno;
1008  hscan->rs_cindex = FirstOffsetNumber;
1009  hscan->rs_cbuf = ReadBufferExtended(scan->rs_rd, MAIN_FORKNUM,
1010  blockno, RBM_NORMAL, bstrategy);
1012 
1013  /* in heap all blocks can contain tuples, so always return true */
1014  return true;
1015 }
1016 
1017 static bool
1019  double *liverows, double *deadrows,
1020  TupleTableSlot *slot)
1021 {
1022  HeapScanDesc hscan = (HeapScanDesc) scan;
1023  Page targpage;
1024  OffsetNumber maxoffset;
1025  BufferHeapTupleTableSlot *hslot;
1026 
1027  Assert(TTS_IS_BUFFERTUPLE(slot));
1028 
1029  hslot = (BufferHeapTupleTableSlot *) slot;
1030  targpage = BufferGetPage(hscan->rs_cbuf);
1031  maxoffset = PageGetMaxOffsetNumber(targpage);
1032 
1033  /* Inner loop over all tuples on the selected page */
1034  for (; hscan->rs_cindex <= maxoffset; hscan->rs_cindex++)
1035  {
1036  ItemId itemid;
1037  HeapTuple targtuple = &hslot->base.tupdata;
1038  bool sample_it = false;
1039 
1040  itemid = PageGetItemId(targpage, hscan->rs_cindex);
1041 
1042  /*
1043  * We ignore unused and redirect line pointers. DEAD line pointers
1044  * should be counted as dead, because we need vacuum to run to get rid
1045  * of them. Note that this rule agrees with the way that
1046  * heap_page_prune() counts things.
1047  */
1048  if (!ItemIdIsNormal(itemid))
1049  {
1050  if (ItemIdIsDead(itemid))
1051  *deadrows += 1;
1052  continue;
1053  }
1054 
1055  ItemPointerSet(&targtuple->t_self, hscan->rs_cblock, hscan->rs_cindex);
1056 
1057  targtuple->t_tableOid = RelationGetRelid(scan->rs_rd);
1058  targtuple->t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
1059  targtuple->t_len = ItemIdGetLength(itemid);
1060 
1061  switch (HeapTupleSatisfiesVacuum(targtuple, OldestXmin,
1062  hscan->rs_cbuf))
1063  {
1064  case HEAPTUPLE_LIVE:
1065  sample_it = true;
1066  *liverows += 1;
1067  break;
1068 
1069  case HEAPTUPLE_DEAD:
1071  /* Count dead and recently-dead rows */
1072  *deadrows += 1;
1073  break;
1074 
1076 
1077  /*
1078  * Insert-in-progress rows are not counted. We assume that
1079  * when the inserting transaction commits or aborts, it will
1080  * send a stats message to increment the proper count. This
1081  * works right only if that transaction ends after we finish
1082  * analyzing the table; if things happen in the other order,
1083  * its stats update will be overwritten by ours. However, the
1084  * error will be large only if the other transaction runs long
1085  * enough to insert many tuples, so assuming it will finish
1086  * after us is the safer option.
1087  *
1088  * A special case is that the inserting transaction might be
1089  * our own. In this case we should count and sample the row,
1090  * to accommodate users who load a table and analyze it in one
1091  * transaction. (pgstat_report_analyze has to adjust the
1092  * numbers we send to the stats collector to make this come
1093  * out right.)
1094  */
1096  {
1097  sample_it = true;
1098  *liverows += 1;
1099  }
1100  break;
1101 
1103 
1104  /*
1105  * We count and sample delete-in-progress rows the same as
1106  * live ones, so that the stats counters come out right if the
1107  * deleting transaction commits after us, per the same
1108  * reasoning given above.
1109  *
1110  * If the delete was done by our own transaction, however, we
1111  * must count the row as dead to make pgstat_report_analyze's
1112  * stats adjustments come out right. (Note: this works out
1113  * properly when the row was both inserted and deleted in our
1114  * xact.)
1115  *
1116  * The net effect of these choices is that we act as though an
1117  * IN_PROGRESS transaction hasn't happened yet, except if it
1118  * is our own transaction, which we assume has happened.
1119  *
1120  * This approach ensures that we behave sanely if we see both
1121  * the pre-image and post-image rows for a row being updated
1122  * by a concurrent transaction: we will sample the pre-image
1123  * but not the post-image. We also get sane results if the
1124  * concurrent transaction never commits.
1125  */
1127  *deadrows += 1;
1128  else
1129  {
1130  sample_it = true;
1131  *liverows += 1;
1132  }
1133  break;
1134 
1135  default:
1136  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1137  break;
1138  }
1139 
1140  if (sample_it)
1141  {
1142  ExecStoreBufferHeapTuple(targtuple, slot, hscan->rs_cbuf);
1143  hscan->rs_cindex++;
1144 
1145  /* note that we leave the buffer locked here! */
1146  return true;
1147  }
1148  }
1149 
1150  /* Now release the lock and pin on the page */
1151  UnlockReleaseBuffer(hscan->rs_cbuf);
1152  hscan->rs_cbuf = InvalidBuffer;
1153 
1154  /* also prevent old slot contents from having pin on page */
1155  ExecClearTuple(slot);
1156 
1157  return false;
1158 }
1159 
1160 static double
1162  Relation indexRelation,
1163  IndexInfo *indexInfo,
1164  bool allow_sync,
1165  bool anyvisible,
1166  bool progress,
1167  BlockNumber start_blockno,
1168  BlockNumber numblocks,
1170  void *callback_state,
1171  TableScanDesc scan)
1172 {
1173  HeapScanDesc hscan;
1174  bool is_system_catalog;
1175  bool checking_uniqueness;
1176  HeapTuple heapTuple;
1178  bool isnull[INDEX_MAX_KEYS];
1179  double reltuples;
1180  ExprState *predicate;
1181  TupleTableSlot *slot;
1182  EState *estate;
1183  ExprContext *econtext;
1184  Snapshot snapshot;
1185  bool need_unregister_snapshot = false;
1186  TransactionId OldestXmin;
1187  BlockNumber previous_blkno = InvalidBlockNumber;
1188  BlockNumber root_blkno = InvalidBlockNumber;
1189  OffsetNumber root_offsets[MaxHeapTuplesPerPage];
1190 
1191  /*
1192  * sanity checks
1193  */
1194  Assert(OidIsValid(indexRelation->rd_rel->relam));
1195 
1196  /* Remember if it's a system catalog */
1197  is_system_catalog = IsSystemRelation(heapRelation);
1198 
1199  /* See whether we're verifying uniqueness/exclusion properties */
1200  checking_uniqueness = (indexInfo->ii_Unique ||
1201  indexInfo->ii_ExclusionOps != NULL);
1202 
1203  /*
1204  * "Any visible" mode is not compatible with uniqueness checks; make sure
1205  * only one of those is requested.
1206  */
1207  Assert(!(anyvisible && checking_uniqueness));
1208 
1209  /*
1210  * Need an EState for evaluation of index expressions and partial-index
1211  * predicates. Also a slot to hold the current tuple.
1212  */
1213  estate = CreateExecutorState();
1214  econtext = GetPerTupleExprContext(estate);
1215  slot = table_slot_create(heapRelation, NULL);
1216 
1217  /* Arrange for econtext's scan tuple to be the tuple under test */
1218  econtext->ecxt_scantuple = slot;
1219 
1220  /* Set up execution state for predicate, if any. */
1221  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
1222 
1223  /*
1224  * Prepare for scan of the base relation. In a normal index build, we use
1225  * SnapshotAny because we must retrieve all tuples and do our own time
1226  * qual checks (because we have to index RECENTLY_DEAD tuples). In a
1227  * concurrent build, or during bootstrap, we take a regular MVCC snapshot
1228  * and index whatever's live according to that.
1229  */
1230  OldestXmin = InvalidTransactionId;
1231 
1232  /* okay to ignore lazy VACUUMs here */
1233  if (!IsBootstrapProcessingMode() && !indexInfo->ii_Concurrent)
1234  OldestXmin = GetOldestNonRemovableTransactionId(heapRelation);
1235 
1236  if (!scan)
1237  {
1238  /*
1239  * Serial index build.
1240  *
1241  * Must begin our own heap scan in this case. We may also need to
1242  * register a snapshot whose lifetime is under our direct control.
1243  */
1244  if (!TransactionIdIsValid(OldestXmin))
1245  {
1247  need_unregister_snapshot = true;
1248  }
1249  else
1250  snapshot = SnapshotAny;
1251 
1252  scan = table_beginscan_strat(heapRelation, /* relation */
1253  snapshot, /* snapshot */
1254  0, /* number of keys */
1255  NULL, /* scan key */
1256  true, /* buffer access strategy OK */
1257  allow_sync); /* syncscan OK? */
1258  }
1259  else
1260  {
1261  /*
1262  * Parallel index build.
1263  *
1264  * Parallel case never registers/unregisters own snapshot. Snapshot
1265  * is taken from parallel heap scan, and is SnapshotAny or an MVCC
1266  * snapshot, based on same criteria as serial case.
1267  */
1269  Assert(allow_sync);
1270  snapshot = scan->rs_snapshot;
1271  }
1272 
1273  hscan = (HeapScanDesc) scan;
1274 
1275  /*
1276  * Must have called GetOldestNonRemovableTransactionId() if using
1277  * SnapshotAny. Shouldn't have for an MVCC snapshot. (It's especially
1278  * worth checking this for parallel builds, since ambuild routines that
1279  * support parallel builds must work these details out for themselves.)
1280  */
1281  Assert(snapshot == SnapshotAny || IsMVCCSnapshot(snapshot));
1282  Assert(snapshot == SnapshotAny ? TransactionIdIsValid(OldestXmin) :
1283  !TransactionIdIsValid(OldestXmin));
1284  Assert(snapshot == SnapshotAny || !anyvisible);
1285 
1286  /* Publish number of blocks to scan */
1287  if (progress)
1288  {
1289  BlockNumber nblocks;
1290 
1291  if (hscan->rs_base.rs_parallel != NULL)
1292  {
1294 
1296  nblocks = pbscan->phs_nblocks;
1297  }
1298  else
1299  nblocks = hscan->rs_nblocks;
1300 
1302  nblocks);
1303  }
1304 
1305  /* set our scan endpoints */
1306  if (!allow_sync)
1307  heap_setscanlimits(scan, start_blockno, numblocks);
1308  else
1309  {
1310  /* syncscan can only be requested on whole relation */
1311  Assert(start_blockno == 0);
1312  Assert(numblocks == InvalidBlockNumber);
1313  }
1314 
1315  reltuples = 0;
1316 
1317  /*
1318  * Scan all tuples in the base relation.
1319  */
1320  while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1321  {
1322  bool tupleIsAlive;
1323 
1325 
1326  /* Report scan progress, if asked to. */
1327  if (progress)
1328  {
1329  BlockNumber blocks_done = heapam_scan_get_blocks_done(hscan);
1330 
1331  if (blocks_done != previous_blkno)
1332  {
1334  blocks_done);
1335  previous_blkno = blocks_done;
1336  }
1337  }
1338 
1339  /*
1340  * When dealing with a HOT-chain of updated tuples, we want to index
1341  * the values of the live tuple (if any), but index it under the TID
1342  * of the chain's root tuple. This approach is necessary to preserve
1343  * the HOT-chain structure in the heap. So we need to be able to find
1344  * the root item offset for every tuple that's in a HOT-chain. When
1345  * first reaching a new page of the relation, call
1346  * heap_get_root_tuples() to build a map of root item offsets on the
1347  * page.
1348  *
1349  * It might look unsafe to use this information across buffer
1350  * lock/unlock. However, we hold ShareLock on the table so no
1351  * ordinary insert/update/delete should occur; and we hold pin on the
1352  * buffer continuously while visiting the page, so no pruning
1353  * operation can occur either.
1354  *
1355  * In cases with only ShareUpdateExclusiveLock on the table, it's
1356  * possible for some HOT tuples to appear that we didn't know about
1357  * when we first read the page. To handle that case, we re-obtain the
1358  * list of root offsets when a HOT tuple points to a root item that we
1359  * don't know about.
1360  *
1361  * Also, although our opinions about tuple liveness could change while
1362  * we scan the page (due to concurrent transaction commits/aborts),
1363  * the chain root locations won't, so this info doesn't need to be
1364  * rebuilt after waiting for another transaction.
1365  *
1366  * Note the implied assumption that there is no more than one live
1367  * tuple per HOT-chain --- else we could create more than one index
1368  * entry pointing to the same root tuple.
1369  */
1370  if (hscan->rs_cblock != root_blkno)
1371  {
1372  Page page = BufferGetPage(hscan->rs_cbuf);
1373 
1375  heap_get_root_tuples(page, root_offsets);
1377 
1378  root_blkno = hscan->rs_cblock;
1379  }
1380 
1381  if (snapshot == SnapshotAny)
1382  {
1383  /* do our own time qual check */
1384  bool indexIt;
1385  TransactionId xwait;
1386 
1387  recheck:
1388 
1389  /*
1390  * We could possibly get away with not locking the buffer here,
1391  * since caller should hold ShareLock on the relation, but let's
1392  * be conservative about it. (This remark is still correct even
1393  * with HOT-pruning: our pin on the buffer prevents pruning.)
1394  */
1396 
1397  /*
1398  * The criteria for counting a tuple as live in this block need to
1399  * match what analyze.c's heapam_scan_analyze_next_tuple() does,
1400  * otherwise CREATE INDEX and ANALYZE may produce wildly different
1401  * reltuples values, e.g. when there are many recently-dead
1402  * tuples.
1403  */
1404  switch (HeapTupleSatisfiesVacuum(heapTuple, OldestXmin,
1405  hscan->rs_cbuf))
1406  {
1407  case HEAPTUPLE_DEAD:
1408  /* Definitely dead, we can ignore it */
1409  indexIt = false;
1410  tupleIsAlive = false;
1411  break;
1412  case HEAPTUPLE_LIVE:
1413  /* Normal case, index and unique-check it */
1414  indexIt = true;
1415  tupleIsAlive = true;
1416  /* Count it as live, too */
1417  reltuples += 1;
1418  break;
1420 
1421  /*
1422  * If tuple is recently deleted then we must index it
1423  * anyway to preserve MVCC semantics. (Pre-existing
1424  * transactions could try to use the index after we finish
1425  * building it, and may need to see such tuples.)
1426  *
1427  * However, if it was HOT-updated then we must only index
1428  * the live tuple at the end of the HOT-chain. Since this
1429  * breaks semantics for pre-existing snapshots, mark the
1430  * index as unusable for them.
1431  *
1432  * We don't count recently-dead tuples in reltuples, even
1433  * if we index them; see heapam_scan_analyze_next_tuple().
1434  */
1435  if (HeapTupleIsHotUpdated(heapTuple))
1436  {
1437  indexIt = false;
1438  /* mark the index as unsafe for old snapshots */
1439  indexInfo->ii_BrokenHotChain = true;
1440  }
1441  else
1442  indexIt = true;
1443  /* In any case, exclude the tuple from unique-checking */
1444  tupleIsAlive = false;
1445  break;
1447 
1448  /*
1449  * In "anyvisible" mode, this tuple is visible and we
1450  * don't need any further checks.
1451  */
1452  if (anyvisible)
1453  {
1454  indexIt = true;
1455  tupleIsAlive = true;
1456  reltuples += 1;
1457  break;
1458  }
1459 
1460  /*
1461  * Since caller should hold ShareLock or better, normally
1462  * the only way to see this is if it was inserted earlier
1463  * in our own transaction. However, it can happen in
1464  * system catalogs, since we tend to release write lock
1465  * before commit there. Give a warning if neither case
1466  * applies.
1467  */
1468  xwait = HeapTupleHeaderGetXmin(heapTuple->t_data);
1470  {
1471  if (!is_system_catalog)
1472  elog(WARNING, "concurrent insert in progress within table \"%s\"",
1473  RelationGetRelationName(heapRelation));
1474 
1475  /*
1476  * If we are performing uniqueness checks, indexing
1477  * such a tuple could lead to a bogus uniqueness
1478  * failure. In that case we wait for the inserting
1479  * transaction to finish and check again.
1480  */
1481  if (checking_uniqueness)
1482  {
1483  /*
1484  * Must drop the lock on the buffer before we wait
1485  */
1487  XactLockTableWait(xwait, heapRelation,
1488  &heapTuple->t_self,
1491  goto recheck;
1492  }
1493  }
1494  else
1495  {
1496  /*
1497  * For consistency with
1498  * heapam_scan_analyze_next_tuple(), count
1499  * HEAPTUPLE_INSERT_IN_PROGRESS tuples as live only
1500  * when inserted by our own transaction.
1501  */
1502  reltuples += 1;
1503  }
1504 
1505  /*
1506  * We must index such tuples, since if the index build
1507  * commits then they're good.
1508  */
1509  indexIt = true;
1510  tupleIsAlive = true;
1511  break;
1513 
1514  /*
1515  * As with INSERT_IN_PROGRESS case, this is unexpected
1516  * unless it's our own deletion or a system catalog; but
1517  * in anyvisible mode, this tuple is visible.
1518  */
1519  if (anyvisible)
1520  {
1521  indexIt = true;
1522  tupleIsAlive = false;
1523  reltuples += 1;
1524  break;
1525  }
1526 
1527  xwait = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
1529  {
1530  if (!is_system_catalog)
1531  elog(WARNING, "concurrent delete in progress within table \"%s\"",
1532  RelationGetRelationName(heapRelation));
1533 
1534  /*
1535  * If we are performing uniqueness checks, assuming
1536  * the tuple is dead could lead to missing a
1537  * uniqueness violation. In that case we wait for the
1538  * deleting transaction to finish and check again.
1539  *
1540  * Also, if it's a HOT-updated tuple, we should not
1541  * index it but rather the live tuple at the end of
1542  * the HOT-chain. However, the deleting transaction
1543  * could abort, possibly leaving this tuple as live
1544  * after all, in which case it has to be indexed. The
1545  * only way to know what to do is to wait for the
1546  * deleting transaction to finish and check again.
1547  */
1548  if (checking_uniqueness ||
1549  HeapTupleIsHotUpdated(heapTuple))
1550  {
1551  /*
1552  * Must drop the lock on the buffer before we wait
1553  */
1555  XactLockTableWait(xwait, heapRelation,
1556  &heapTuple->t_self,
1559  goto recheck;
1560  }
1561 
1562  /*
1563  * Otherwise index it but don't check for uniqueness,
1564  * the same as a RECENTLY_DEAD tuple.
1565  */
1566  indexIt = true;
1567 
1568  /*
1569  * Count HEAPTUPLE_DELETE_IN_PROGRESS tuples as live,
1570  * if they were not deleted by the current
1571  * transaction. That's what
1572  * heapam_scan_analyze_next_tuple() does, and we want
1573  * the behavior to be consistent.
1574  */
1575  reltuples += 1;
1576  }
1577  else if (HeapTupleIsHotUpdated(heapTuple))
1578  {
1579  /*
1580  * It's a HOT-updated tuple deleted by our own xact.
1581  * We can assume the deletion will commit (else the
1582  * index contents don't matter), so treat the same as
1583  * RECENTLY_DEAD HOT-updated tuples.
1584  */
1585  indexIt = false;
1586  /* mark the index as unsafe for old snapshots */
1587  indexInfo->ii_BrokenHotChain = true;
1588  }
1589  else
1590  {
1591  /*
1592  * It's a regular tuple deleted by our own xact. Index
1593  * it, but don't check for uniqueness nor count in
1594  * reltuples, the same as a RECENTLY_DEAD tuple.
1595  */
1596  indexIt = true;
1597  }
1598  /* In any case, exclude the tuple from unique-checking */
1599  tupleIsAlive = false;
1600  break;
1601  default:
1602  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1603  indexIt = tupleIsAlive = false; /* keep compiler quiet */
1604  break;
1605  }
1606 
1608 
1609  if (!indexIt)
1610  continue;
1611  }
1612  else
1613  {
1614  /* heap_getnext did the time qual check */
1615  tupleIsAlive = true;
1616  reltuples += 1;
1617  }
1618 
1620 
1621  /* Set up for predicate or expression evaluation */
1622  ExecStoreBufferHeapTuple(heapTuple, slot, hscan->rs_cbuf);
1623 
1624  /*
1625  * In a partial index, discard tuples that don't satisfy the
1626  * predicate.
1627  */
1628  if (predicate != NULL)
1629  {
1630  if (!ExecQual(predicate, econtext))
1631  continue;
1632  }
1633 
1634  /*
1635  * For the current heap tuple, extract all the attributes we use in
1636  * this index, and note which are null. This also performs evaluation
1637  * of any expressions needed.
1638  */
1639  FormIndexDatum(indexInfo,
1640  slot,
1641  estate,
1642  values,
1643  isnull);
1644 
1645  /*
1646  * You'd think we should go ahead and build the index tuple here, but
1647  * some index AMs want to do further processing on the data first. So
1648  * pass the values[] and isnull[] arrays, instead.
1649  */
1650 
1651  if (HeapTupleIsHeapOnly(heapTuple))
1652  {
1653  /*
1654  * For a heap-only tuple, pretend its TID is that of the root. See
1655  * src/backend/access/heap/README.HOT for discussion.
1656  */
1657  ItemPointerData tid;
1658  OffsetNumber offnum;
1659 
1660  offnum = ItemPointerGetOffsetNumber(&heapTuple->t_self);
1661 
1662  /*
1663  * If a HOT tuple points to a root that we don't know about,
1664  * obtain root items afresh. If that still fails, report it as
1665  * corruption.
1666  */
1667  if (root_offsets[offnum - 1] == InvalidOffsetNumber)
1668  {
1669  Page page = BufferGetPage(hscan->rs_cbuf);
1670 
1672  heap_get_root_tuples(page, root_offsets);
1674  }
1675 
1676  if (!OffsetNumberIsValid(root_offsets[offnum - 1]))
1677  ereport(ERROR,
1679  errmsg_internal("failed to find parent tuple for heap-only tuple at (%u,%u) in table \"%s\"",
1680  ItemPointerGetBlockNumber(&heapTuple->t_self),
1681  offnum,
1682  RelationGetRelationName(heapRelation))));
1683 
1684  ItemPointerSet(&tid, ItemPointerGetBlockNumber(&heapTuple->t_self),
1685  root_offsets[offnum - 1]);
1686 
1687  /* Call the AM's callback routine to process the tuple */
1688  callback(indexRelation, &tid, values, isnull, tupleIsAlive,
1689  callback_state);
1690  }
1691  else
1692  {
1693  /* Call the AM's callback routine to process the tuple */
1694  callback(indexRelation, &heapTuple->t_self, values, isnull,
1695  tupleIsAlive, callback_state);
1696  }
1697  }
1698 
1699  /* Report scan progress one last time. */
1700  if (progress)
1701  {
1702  BlockNumber blks_done;
1703 
1704  if (hscan->rs_base.rs_parallel != NULL)
1705  {
1707 
1709  blks_done = pbscan->phs_nblocks;
1710  }
1711  else
1712  blks_done = hscan->rs_nblocks;
1713 
1715  blks_done);
1716  }
1717 
1718  table_endscan(scan);
1719 
1720  /* we can now forget our snapshot, if set and registered by us */
1721  if (need_unregister_snapshot)
1722  UnregisterSnapshot(snapshot);
1723 
1725 
1726  FreeExecutorState(estate);
1727 
1728  /* These may have been pointing to the now-gone estate */
1729  indexInfo->ii_ExpressionsState = NIL;
1730  indexInfo->ii_PredicateState = NULL;
1731 
1732  return reltuples;
1733 }
1734 
1735 static void
1737  Relation indexRelation,
1738  IndexInfo *indexInfo,
1739  Snapshot snapshot,
1741 {
1742  TableScanDesc scan;
1743  HeapScanDesc hscan;
1744  HeapTuple heapTuple;
1746  bool isnull[INDEX_MAX_KEYS];
1747  ExprState *predicate;
1748  TupleTableSlot *slot;
1749  EState *estate;
1750  ExprContext *econtext;
1751  BlockNumber root_blkno = InvalidBlockNumber;
1752  OffsetNumber root_offsets[MaxHeapTuplesPerPage];
1753  bool in_index[MaxHeapTuplesPerPage];
1754  BlockNumber previous_blkno = InvalidBlockNumber;
1755 
1756  /* state variables for the merge */
1757  ItemPointer indexcursor = NULL;
1758  ItemPointerData decoded;
1759  bool tuplesort_empty = false;
1760 
1761  /*
1762  * sanity checks
1763  */
1764  Assert(OidIsValid(indexRelation->rd_rel->relam));
1765 
1766  /*
1767  * Need an EState for evaluation of index expressions and partial-index
1768  * predicates. Also a slot to hold the current tuple.
1769  */
1770  estate = CreateExecutorState();
1771  econtext = GetPerTupleExprContext(estate);
1772  slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRelation),
1773  &TTSOpsHeapTuple);
1774 
1775  /* Arrange for econtext's scan tuple to be the tuple under test */
1776  econtext->ecxt_scantuple = slot;
1777 
1778  /* Set up execution state for predicate, if any. */
1779  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
1780 
1781  /*
1782  * Prepare for scan of the base relation. We need just those tuples
1783  * satisfying the passed-in reference snapshot. We must disable syncscan
1784  * here, because it's critical that we read from block zero forward to
1785  * match the sorted TIDs.
1786  */
1787  scan = table_beginscan_strat(heapRelation, /* relation */
1788  snapshot, /* snapshot */
1789  0, /* number of keys */
1790  NULL, /* scan key */
1791  true, /* buffer access strategy OK */
1792  false); /* syncscan not OK */
1793  hscan = (HeapScanDesc) scan;
1794 
1796  hscan->rs_nblocks);
1797 
1798  /*
1799  * Scan all tuples matching the snapshot.
1800  */
1801  while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1802  {
1803  ItemPointer heapcursor = &heapTuple->t_self;
1804  ItemPointerData rootTuple;
1805  OffsetNumber root_offnum;
1806 
1808 
1809  state->htups += 1;
1810 
1811  if ((previous_blkno == InvalidBlockNumber) ||
1812  (hscan->rs_cblock != previous_blkno))
1813  {
1815  hscan->rs_cblock);
1816  previous_blkno = hscan->rs_cblock;
1817  }
1818 
1819  /*
1820  * As commented in table_index_build_scan, we should index heap-only
1821  * tuples under the TIDs of their root tuples; so when we advance onto
1822  * a new heap page, build a map of root item offsets on the page.
1823  *
1824  * This complicates merging against the tuplesort output: we will
1825  * visit the live tuples in order by their offsets, but the root
1826  * offsets that we need to compare against the index contents might be
1827  * ordered differently. So we might have to "look back" within the
1828  * tuplesort output, but only within the current page. We handle that
1829  * by keeping a bool array in_index[] showing all the
1830  * already-passed-over tuplesort output TIDs of the current page. We
1831  * clear that array here, when advancing onto a new heap page.
1832  */
1833  if (hscan->rs_cblock != root_blkno)
1834  {
1835  Page page = BufferGetPage(hscan->rs_cbuf);
1836 
1838  heap_get_root_tuples(page, root_offsets);
1840 
1841  memset(in_index, 0, sizeof(in_index));
1842 
1843  root_blkno = hscan->rs_cblock;
1844  }
1845 
1846  /* Convert actual tuple TID to root TID */
1847  rootTuple = *heapcursor;
1848  root_offnum = ItemPointerGetOffsetNumber(heapcursor);
1849 
1850  if (HeapTupleIsHeapOnly(heapTuple))
1851  {
1852  root_offnum = root_offsets[root_offnum - 1];
1853  if (!OffsetNumberIsValid(root_offnum))
1854  ereport(ERROR,
1856  errmsg_internal("failed to find parent tuple for heap-only tuple at (%u,%u) in table \"%s\"",
1857  ItemPointerGetBlockNumber(heapcursor),
1858  ItemPointerGetOffsetNumber(heapcursor),
1859  RelationGetRelationName(heapRelation))));
1860  ItemPointerSetOffsetNumber(&rootTuple, root_offnum);
1861  }
1862 
1863  /*
1864  * "merge" by skipping through the index tuples until we find or pass
1865  * the current root tuple.
1866  */
1867  while (!tuplesort_empty &&
1868  (!indexcursor ||
1869  ItemPointerCompare(indexcursor, &rootTuple) < 0))
1870  {
1871  Datum ts_val;
1872  bool ts_isnull;
1873 
1874  if (indexcursor)
1875  {
1876  /*
1877  * Remember index items seen earlier on the current heap page
1878  */
1879  if (ItemPointerGetBlockNumber(indexcursor) == root_blkno)
1880  in_index[ItemPointerGetOffsetNumber(indexcursor) - 1] = true;
1881  }
1882 
1883  tuplesort_empty = !tuplesort_getdatum(state->tuplesort, true,
1884  &ts_val, &ts_isnull, NULL);
1885  Assert(tuplesort_empty || !ts_isnull);
1886  if (!tuplesort_empty)
1887  {
1888  itemptr_decode(&decoded, DatumGetInt64(ts_val));
1889  indexcursor = &decoded;
1890 
1891  /* If int8 is pass-by-ref, free (encoded) TID Datum memory */
1892 #ifndef USE_FLOAT8_BYVAL
1893  pfree(DatumGetPointer(ts_val));
1894 #endif
1895  }
1896  else
1897  {
1898  /* Be tidy */
1899  indexcursor = NULL;
1900  }
1901  }
1902 
1903  /*
1904  * If the tuplesort has overshot *and* we didn't see a match earlier,
1905  * then this tuple is missing from the index, so insert it.
1906  */
1907  if ((tuplesort_empty ||
1908  ItemPointerCompare(indexcursor, &rootTuple) > 0) &&
1909  !in_index[root_offnum - 1])
1910  {
1912 
1913  /* Set up for predicate or expression evaluation */
1914  ExecStoreHeapTuple(heapTuple, slot, false);
1915 
1916  /*
1917  * In a partial index, discard tuples that don't satisfy the
1918  * predicate.
1919  */
1920  if (predicate != NULL)
1921  {
1922  if (!ExecQual(predicate, econtext))
1923  continue;
1924  }
1925 
1926  /*
1927  * For the current heap tuple, extract all the attributes we use
1928  * in this index, and note which are null. This also performs
1929  * evaluation of any expressions needed.
1930  */
1931  FormIndexDatum(indexInfo,
1932  slot,
1933  estate,
1934  values,
1935  isnull);
1936 
1937  /*
1938  * You'd think we should go ahead and build the index tuple here,
1939  * but some index AMs want to do further processing on the data
1940  * first. So pass the values[] and isnull[] arrays, instead.
1941  */
1942 
1943  /*
1944  * If the tuple is already committed dead, you might think we
1945  * could suppress uniqueness checking, but this is no longer true
1946  * in the presence of HOT, because the insert is actually a proxy
1947  * for a uniqueness check on the whole HOT-chain. That is, the
1948  * tuple we have here could be dead because it was already
1949  * HOT-updated, and if so the updating transaction will not have
1950  * thought it should insert index entries. The index AM will
1951  * check the whole HOT-chain and correctly detect a conflict if
1952  * there is one.
1953  */
1954 
1955  index_insert(indexRelation,
1956  values,
1957  isnull,
1958  &rootTuple,
1959  heapRelation,
1960  indexInfo->ii_Unique ?
1962  false,
1963  indexInfo);
1964 
1965  state->tups_inserted += 1;
1966  }
1967  }
1968 
1969  table_endscan(scan);
1970 
1972 
1973  FreeExecutorState(estate);
1974 
1975  /* These may have been pointing to the now-gone estate */
1976  indexInfo->ii_ExpressionsState = NIL;
1977  indexInfo->ii_PredicateState = NULL;
1978 }
1979 
1980 /*
1981  * Return the number of blocks that have been read by this scan since
1982  * starting. This is meant for progress reporting rather than be fully
1983  * accurate: in a parallel scan, workers can be concurrently reading blocks
1984  * further ahead than what we report.
1985  */
1986 static BlockNumber
1988 {
1989  ParallelBlockTableScanDesc bpscan = NULL;
1990  BlockNumber startblock;
1991  BlockNumber blocks_done;
1992 
1993  if (hscan->rs_base.rs_parallel != NULL)
1994  {
1996  startblock = bpscan->phs_startblock;
1997  }
1998  else
1999  startblock = hscan->rs_startblock;
2000 
2001  /*
2002  * Might have wrapped around the end of the relation, if startblock was
2003  * not zero.
2004  */
2005  if (hscan->rs_cblock > startblock)
2006  blocks_done = hscan->rs_cblock - startblock;
2007  else
2008  {
2009  BlockNumber nblocks;
2010 
2011  nblocks = bpscan != NULL ? bpscan->phs_nblocks : hscan->rs_nblocks;
2012  blocks_done = nblocks - startblock +
2013  hscan->rs_cblock;
2014  }
2015 
2016  return blocks_done;
2017 }
2018 
2019 
2020 /* ------------------------------------------------------------------------
2021  * Miscellaneous callbacks for the heap AM
2022  * ------------------------------------------------------------------------
2023  */
2024 
2025 /*
2026  * Check to see whether the table needs a TOAST table. It does only if
2027  * (1) there are any toastable attributes, and (2) the maximum length
2028  * of a tuple could exceed TOAST_TUPLE_THRESHOLD. (We don't want to
2029  * create a toast table for something like "f1 varchar(20)".)
2030  */
2031 static bool
2033 {
2034  int32 data_length = 0;
2035  bool maxlength_unknown = false;
2036  bool has_toastable_attrs = false;
2037  TupleDesc tupdesc = rel->rd_att;
2038  int32 tuple_length;
2039  int i;
2040 
2041  for (i = 0; i < tupdesc->natts; i++)
2042  {
2043  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2044 
2045  if (att->attisdropped)
2046  continue;
2047  data_length = att_align_nominal(data_length, att->attalign);
2048  if (att->attlen > 0)
2049  {
2050  /* Fixed-length types are never toastable */
2051  data_length += att->attlen;
2052  }
2053  else
2054  {
2055  int32 maxlen = type_maximum_size(att->atttypid,
2056  att->atttypmod);
2057 
2058  if (maxlen < 0)
2059  maxlength_unknown = true;
2060  else
2061  data_length += maxlen;
2062  if (att->attstorage != TYPSTORAGE_PLAIN)
2063  has_toastable_attrs = true;
2064  }
2065  }
2066  if (!has_toastable_attrs)
2067  return false; /* nothing to toast? */
2068  if (maxlength_unknown)
2069  return true; /* any unlimited-length attrs? */
2070  tuple_length = MAXALIGN(SizeofHeapTupleHeader +
2071  BITMAPLEN(tupdesc->natts)) +
2072  MAXALIGN(data_length);
2073  return (tuple_length > TOAST_TUPLE_THRESHOLD);
2074 }
2075 
2076 /*
2077  * TOAST tables for heap relations are just heap relations.
2078  */
2079 static Oid
2081 {
2082  return rel->rd_rel->relam;
2083 }
2084 
2085 
2086 /* ------------------------------------------------------------------------
2087  * Planner related callbacks for the heap AM
2088  * ------------------------------------------------------------------------
2089  */
2090 
2091 #define HEAP_OVERHEAD_BYTES_PER_TUPLE \
2092  (MAXALIGN(SizeofHeapTupleHeader) + sizeof(ItemIdData))
2093 #define HEAP_USABLE_BYTES_PER_PAGE \
2094  (BLCKSZ - SizeOfPageHeaderData)
2095 
2096 static void
2098  BlockNumber *pages, double *tuples,
2099  double *allvisfrac)
2100 {
2101  table_block_relation_estimate_size(rel, attr_widths, pages,
2102  tuples, allvisfrac,
2105 }
2106 
2107 
2108 /* ------------------------------------------------------------------------
2109  * Executor related callbacks for the heap AM
2110  * ------------------------------------------------------------------------
2111  */
2112 
2113 static bool
2115  TBMIterateResult *tbmres)
2116 {
2117  HeapScanDesc hscan = (HeapScanDesc) scan;
2118  BlockNumber page = tbmres->blockno;
2119  Buffer buffer;
2120  Snapshot snapshot;
2121  int ntup;
2122 
2123  hscan->rs_cindex = 0;
2124  hscan->rs_ntuples = 0;
2125 
2126  /*
2127  * Ignore any claimed entries past what we think is the end of the
2128  * relation. It may have been extended after the start of our scan (we
2129  * only hold an AccessShareLock, and it could be inserts from this
2130  * backend).
2131  */
2132  if (page >= hscan->rs_nblocks)
2133  return false;
2134 
2135  /*
2136  * Acquire pin on the target heap page, trading in any pin we held before.
2137  */
2138  hscan->rs_cbuf = ReleaseAndReadBuffer(hscan->rs_cbuf,
2139  scan->rs_rd,
2140  page);
2141  hscan->rs_cblock = page;
2142  buffer = hscan->rs_cbuf;
2143  snapshot = scan->rs_snapshot;
2144 
2145  ntup = 0;
2146 
2147  /*
2148  * Prune and repair fragmentation for the whole page, if possible.
2149  */
2150  heap_page_prune_opt(scan->rs_rd, buffer);
2151 
2152  /*
2153  * We must hold share lock on the buffer content while examining tuple
2154  * visibility. Afterwards, however, the tuples we have found to be
2155  * visible are guaranteed good as long as we hold the buffer pin.
2156  */
2157  LockBuffer(buffer, BUFFER_LOCK_SHARE);
2158 
2159  /*
2160  * We need two separate strategies for lossy and non-lossy cases.
2161  */
2162  if (tbmres->ntuples >= 0)
2163  {
2164  /*
2165  * Bitmap is non-lossy, so we just look through the offsets listed in
2166  * tbmres; but we have to follow any HOT chain starting at each such
2167  * offset.
2168  */
2169  int curslot;
2170 
2171  for (curslot = 0; curslot < tbmres->ntuples; curslot++)
2172  {
2173  OffsetNumber offnum = tbmres->offsets[curslot];
2174  ItemPointerData tid;
2175  HeapTupleData heapTuple;
2176 
2177  ItemPointerSet(&tid, page, offnum);
2178  if (heap_hot_search_buffer(&tid, scan->rs_rd, buffer, snapshot,
2179  &heapTuple, NULL, true))
2180  hscan->rs_vistuples[ntup++] = ItemPointerGetOffsetNumber(&tid);
2181  }
2182  }
2183  else
2184  {
2185  /*
2186  * Bitmap is lossy, so we must examine each line pointer on the page.
2187  * But we can ignore HOT chains, since we'll check each tuple anyway.
2188  */
2189  Page dp = (Page) BufferGetPage(buffer);
2190  OffsetNumber maxoff = PageGetMaxOffsetNumber(dp);
2191  OffsetNumber offnum;
2192 
2193  for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum))
2194  {
2195  ItemId lp;
2196  HeapTupleData loctup;
2197  bool valid;
2198 
2199  lp = PageGetItemId(dp, offnum);
2200  if (!ItemIdIsNormal(lp))
2201  continue;
2202  loctup.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
2203  loctup.t_len = ItemIdGetLength(lp);
2204  loctup.t_tableOid = scan->rs_rd->rd_id;
2205  ItemPointerSet(&loctup.t_self, page, offnum);
2206  valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
2207  if (valid)
2208  {
2209  hscan->rs_vistuples[ntup++] = offnum;
2210  PredicateLockTID(scan->rs_rd, &loctup.t_self, snapshot,
2211  HeapTupleHeaderGetXmin(loctup.t_data));
2212  }
2213  HeapCheckForSerializableConflictOut(valid, scan->rs_rd, &loctup,
2214  buffer, snapshot);
2215  }
2216  }
2217 
2218  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2219 
2220  Assert(ntup <= MaxHeapTuplesPerPage);
2221  hscan->rs_ntuples = ntup;
2222 
2223  return ntup > 0;
2224 }
2225 
2226 static bool
2228  TBMIterateResult *tbmres,
2229  TupleTableSlot *slot)
2230 {
2231  HeapScanDesc hscan = (HeapScanDesc) scan;
2232  OffsetNumber targoffset;
2233  Page dp;
2234  ItemId lp;
2235 
2236  /*
2237  * Out of range? If so, nothing more to look at on this page
2238  */
2239  if (hscan->rs_cindex < 0 || hscan->rs_cindex >= hscan->rs_ntuples)
2240  return false;
2241 
2242  targoffset = hscan->rs_vistuples[hscan->rs_cindex];
2243  dp = (Page) BufferGetPage(hscan->rs_cbuf);
2244  lp = PageGetItemId(dp, targoffset);
2245  Assert(ItemIdIsNormal(lp));
2246 
2247  hscan->rs_ctup.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
2248  hscan->rs_ctup.t_len = ItemIdGetLength(lp);
2249  hscan->rs_ctup.t_tableOid = scan->rs_rd->rd_id;
2250  ItemPointerSet(&hscan->rs_ctup.t_self, hscan->rs_cblock, targoffset);
2251 
2253 
2254  /*
2255  * Set up the result slot to point to this tuple. Note that the slot
2256  * acquires a pin on the buffer.
2257  */
2259  slot,
2260  hscan->rs_cbuf);
2261 
2262  hscan->rs_cindex++;
2263 
2264  return true;
2265 }
2266 
2267 static bool
2269 {
2270  HeapScanDesc hscan = (HeapScanDesc) scan;
2271  TsmRoutine *tsm = scanstate->tsmroutine;
2272  BlockNumber blockno;
2273 
2274  /* return false immediately if relation is empty */
2275  if (hscan->rs_nblocks == 0)
2276  return false;
2277 
2278  if (tsm->NextSampleBlock)
2279  {
2280  blockno = tsm->NextSampleBlock(scanstate, hscan->rs_nblocks);
2281  hscan->rs_cblock = blockno;
2282  }
2283  else
2284  {
2285  /* scanning table sequentially */
2286 
2287  if (hscan->rs_cblock == InvalidBlockNumber)
2288  {
2289  Assert(!hscan->rs_inited);
2290  blockno = hscan->rs_startblock;
2291  }
2292  else
2293  {
2294  Assert(hscan->rs_inited);
2295 
2296  blockno = hscan->rs_cblock + 1;
2297 
2298  if (blockno >= hscan->rs_nblocks)
2299  {
2300  /* wrap to beginning of rel, might not have started at 0 */
2301  blockno = 0;
2302  }
2303 
2304  /*
2305  * Report our new scan position for synchronization purposes.
2306  *
2307  * Note: we do this before checking for end of scan so that the
2308  * final state of the position hint is back at the start of the
2309  * rel. That's not strictly necessary, but otherwise when you run
2310  * the same query multiple times the starting position would shift
2311  * a little bit backwards on every invocation, which is confusing.
2312  * We don't guarantee any specific ordering in general, though.
2313  */
2314  if (scan->rs_flags & SO_ALLOW_SYNC)
2315  ss_report_location(scan->rs_rd, blockno);
2316 
2317  if (blockno == hscan->rs_startblock)
2318  {
2319  blockno = InvalidBlockNumber;
2320  }
2321  }
2322  }
2323 
2324  if (!BlockNumberIsValid(blockno))
2325  {
2326  if (BufferIsValid(hscan->rs_cbuf))
2327  ReleaseBuffer(hscan->rs_cbuf);
2328  hscan->rs_cbuf = InvalidBuffer;
2329  hscan->rs_cblock = InvalidBlockNumber;
2330  hscan->rs_inited = false;
2331 
2332  return false;
2333  }
2334 
2335  heapgetpage(scan, blockno);
2336  hscan->rs_inited = true;
2337 
2338  return true;
2339 }
2340 
2341 static bool
2343  TupleTableSlot *slot)
2344 {
2345  HeapScanDesc hscan = (HeapScanDesc) scan;
2346  TsmRoutine *tsm = scanstate->tsmroutine;
2347  BlockNumber blockno = hscan->rs_cblock;
2348  bool pagemode = (scan->rs_flags & SO_ALLOW_PAGEMODE) != 0;
2349 
2350  Page page;
2351  bool all_visible;
2352  OffsetNumber maxoffset;
2353 
2354  /*
2355  * When not using pagemode, we must lock the buffer during tuple
2356  * visibility checks.
2357  */
2358  if (!pagemode)
2360 
2361  page = (Page) BufferGetPage(hscan->rs_cbuf);
2362  all_visible = PageIsAllVisible(page) &&
2364  maxoffset = PageGetMaxOffsetNumber(page);
2365 
2366  for (;;)
2367  {
2368  OffsetNumber tupoffset;
2369 
2371 
2372  /* Ask the tablesample method which tuples to check on this page. */
2373  tupoffset = tsm->NextSampleTuple(scanstate,
2374  blockno,
2375  maxoffset);
2376 
2377  if (OffsetNumberIsValid(tupoffset))
2378  {
2379  ItemId itemid;
2380  bool visible;
2381  HeapTuple tuple = &(hscan->rs_ctup);
2382 
2383  /* Skip invalid tuple pointers. */
2384  itemid = PageGetItemId(page, tupoffset);
2385  if (!ItemIdIsNormal(itemid))
2386  continue;
2387 
2388  tuple->t_data = (HeapTupleHeader) PageGetItem(page, itemid);
2389  tuple->t_len = ItemIdGetLength(itemid);
2390  ItemPointerSet(&(tuple->t_self), blockno, tupoffset);
2391 
2392 
2393  if (all_visible)
2394  visible = true;
2395  else
2396  visible = SampleHeapTupleVisible(scan, hscan->rs_cbuf,
2397  tuple, tupoffset);
2398 
2399  /* in pagemode, heapgetpage did this for us */
2400  if (!pagemode)
2401  HeapCheckForSerializableConflictOut(visible, scan->rs_rd, tuple,
2402  hscan->rs_cbuf, scan->rs_snapshot);
2403 
2404  /* Try next tuple from same page. */
2405  if (!visible)
2406  continue;
2407 
2408  /* Found visible tuple, return it. */
2409  if (!pagemode)
2411 
2412  ExecStoreBufferHeapTuple(tuple, slot, hscan->rs_cbuf);
2413 
2414  /* Count successfully-fetched tuples as heap fetches */
2416 
2417  return true;
2418  }
2419  else
2420  {
2421  /*
2422  * If we get here, it means we've exhausted the items on this page
2423  * and it's time to move to the next.
2424  */
2425  if (!pagemode)
2427 
2428  ExecClearTuple(slot);
2429  return false;
2430  }
2431  }
2432 
2433  Assert(0);
2434 }
2435 
2436 
2437 /* ----------------------------------------------------------------------------
2438  * Helper functions for the above.
2439  * ----------------------------------------------------------------------------
2440  */
2441 
2442 /*
2443  * Reconstruct and rewrite the given tuple
2444  *
2445  * We cannot simply copy the tuple as-is, for several reasons:
2446  *
2447  * 1. We'd like to squeeze out the values of any dropped columns, both
2448  * to save space and to ensure we have no corner-case failures. (It's
2449  * possible for example that the new table hasn't got a TOAST table
2450  * and so is unable to store any large values of dropped cols.)
2451  *
2452  * 2. The tuple might not even be legal for the new table; this is
2453  * currently only known to happen as an after-effect of ALTER TABLE
2454  * SET WITHOUT OIDS.
2455  *
2456  * So, we must reconstruct the tuple from component Datums.
2457  */
2458 static void
2460  Relation OldHeap, Relation NewHeap,
2461  Datum *values, bool *isnull, RewriteState rwstate)
2462 {
2463  TupleDesc oldTupDesc = RelationGetDescr(OldHeap);
2464  TupleDesc newTupDesc = RelationGetDescr(NewHeap);
2465  HeapTuple copiedTuple;
2466  int i;
2467 
2468  heap_deform_tuple(tuple, oldTupDesc, values, isnull);
2469 
2470  /* Be sure to null out any dropped columns */
2471  for (i = 0; i < newTupDesc->natts; i++)
2472  {
2473  if (TupleDescAttr(newTupDesc, i)->attisdropped)
2474  isnull[i] = true;
2475  }
2476 
2477  copiedTuple = heap_form_tuple(newTupDesc, values, isnull);
2478 
2479  /* The heap rewrite module does the rest */
2480  rewrite_heap_tuple(rwstate, tuple, copiedTuple);
2481 
2482  heap_freetuple(copiedTuple);
2483 }
2484 
2485 /*
2486  * Check visibility of the tuple.
2487  */
2488 static bool
2490  HeapTuple tuple,
2491  OffsetNumber tupoffset)
2492 {
2493  HeapScanDesc hscan = (HeapScanDesc) scan;
2494 
2495  if (scan->rs_flags & SO_ALLOW_PAGEMODE)
2496  {
2497  /*
2498  * In pageatatime mode, heapgetpage() already did visibility checks,
2499  * so just look at the info it left in rs_vistuples[].
2500  *
2501  * We use a binary search over the known-sorted array. Note: we could
2502  * save some effort if we insisted that NextSampleTuple select tuples
2503  * in increasing order, but it's not clear that there would be enough
2504  * gain to justify the restriction.
2505  */
2506  int start = 0,
2507  end = hscan->rs_ntuples - 1;
2508 
2509  while (start <= end)
2510  {
2511  int mid = (start + end) / 2;
2512  OffsetNumber curoffset = hscan->rs_vistuples[mid];
2513 
2514  if (tupoffset == curoffset)
2515  return true;
2516  else if (tupoffset < curoffset)
2517  end = mid - 1;
2518  else
2519  start = mid + 1;
2520  }
2521 
2522  return false;
2523  }
2524  else
2525  {
2526  /* Otherwise, we have to check the tuple individually. */
2527  return HeapTupleSatisfiesVisibility(tuple, scan->rs_snapshot,
2528  buffer);
2529  }
2530 }
2531 
2532 
2533 /* ------------------------------------------------------------------------
2534  * Definition of the heap table access method.
2535  * ------------------------------------------------------------------------
2536  */
2537 
2538 static const TableAmRoutine heapam_methods = {
2540 
2541  .slot_callbacks = heapam_slot_callbacks,
2542 
2543  .scan_begin = heap_beginscan,
2544  .scan_end = heap_endscan,
2545  .scan_rescan = heap_rescan,
2546  .scan_getnextslot = heap_getnextslot,
2547 
2548  .scan_set_tidrange = heap_set_tidrange,
2549  .scan_getnextslot_tidrange = heap_getnextslot_tidrange,
2550 
2551  .parallelscan_estimate = table_block_parallelscan_estimate,
2552  .parallelscan_initialize = table_block_parallelscan_initialize,
2553  .parallelscan_reinitialize = table_block_parallelscan_reinitialize,
2554 
2555  .index_fetch_begin = heapam_index_fetch_begin,
2556  .index_fetch_reset = heapam_index_fetch_reset,
2557  .index_fetch_end = heapam_index_fetch_end,
2558  .index_fetch_tuple = heapam_index_fetch_tuple,
2559 
2560  .tuple_insert = heapam_tuple_insert,
2561  .tuple_insert_speculative = heapam_tuple_insert_speculative,
2562  .tuple_complete_speculative = heapam_tuple_complete_speculative,
2563  .multi_insert = heap_multi_insert,
2564  .tuple_delete = heapam_tuple_delete,
2565  .tuple_update = heapam_tuple_update,
2566  .tuple_lock = heapam_tuple_lock,
2567 
2568  .tuple_fetch_row_version = heapam_fetch_row_version,
2569  .tuple_get_latest_tid = heap_get_latest_tid,
2570  .tuple_tid_valid = heapam_tuple_tid_valid,
2571  .tuple_satisfies_snapshot = heapam_tuple_satisfies_snapshot,
2572  .index_delete_tuples = heap_index_delete_tuples,
2573 
2574  .relation_set_new_filenode = heapam_relation_set_new_filenode,
2575  .relation_nontransactional_truncate = heapam_relation_nontransactional_truncate,
2576  .relation_copy_data = heapam_relation_copy_data,
2577  .relation_copy_for_cluster = heapam_relation_copy_for_cluster,
2578  .relation_vacuum = heap_vacuum_rel,
2579  .scan_analyze_next_block = heapam_scan_analyze_next_block,
2580  .scan_analyze_next_tuple = heapam_scan_analyze_next_tuple,
2581  .index_build_range_scan = heapam_index_build_range_scan,
2582  .index_validate_scan = heapam_index_validate_scan,
2583 
2584  .relation_size = table_block_relation_size,
2585  .relation_needs_toast_table = heapam_relation_needs_toast_table,
2586  .relation_toast_am = heapam_relation_toast_am,
2587  .relation_fetch_toast_slice = heap_fetch_toast_slice,
2588 
2589  .relation_estimate_size = heapam_estimate_rel_size,
2590 
2591  .scan_bitmap_next_block = heapam_scan_bitmap_next_block,
2592  .scan_bitmap_next_tuple = heapam_scan_bitmap_next_tuple,
2593  .scan_sample_next_block = heapam_scan_sample_next_block,
2594  .scan_sample_next_tuple = heapam_scan_sample_next_tuple
2595 };
2596 
2597 
2598 const TableAmRoutine *
2600 {
2601  return &heapam_methods;
2602 }
2603 
2604 Datum
2606 {
2608 }
void pgstat_progress_update_param(int index, int64 val)
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
uint32 BlockNumber
Definition: block.h:31
#define InvalidBlockNumber
Definition: block.h:33
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
static Datum values[MAXATTR]
Definition: bootstrap.c:156
int Buffer
Definition: buf.h:23
#define InvalidBuffer
Definition: buf.h:25
Buffer ReleaseAndReadBuffer(Buffer buffer, Relation relation, BlockNumber blockNum)
Definition: bufmgr.c:1628
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3768
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3791
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4007
void FlushRelationBuffers(Relation rel)
Definition: bufmgr.c:3512
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:741
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
@ RBM_NORMAL
Definition: bufmgr.h:39
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
Pointer Page
Definition: bufpage.h:78
#define PageIsAllVisible(page)
Definition: bufpage.h:384
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:356
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:234
#define PageGetItem(page, itemId)
Definition: bufpage.h:339
unsigned int uint32
Definition: c.h:441
#define MAXALIGN(LEN)
Definition: c.h:757
signed int int32
Definition: c.h:429
TransactionId MultiXactId
Definition: c.h:597
unsigned char uint8
Definition: c.h:439
uint32 CommandId
Definition: c.h:601
uint32 TransactionId
Definition: c.h:587
#define OidIsValid(objectId)
Definition: c.h:710
bool IsSystemRelation(Relation relation)
Definition: catalog.c:74
CommandId HeapTupleHeaderGetCmin(HeapTupleHeader tup)
Definition: combocid.c:104
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
int errcode(int sqlerrcode)
Definition: elog.c:698
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define WARNING
Definition: elog.h:30
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:774
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1392
const TupleTableSlotOps TTSOpsBufferHeapTuple
Definition: execTuples.c:86
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1352
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:84
TupleTableSlot * ExecStorePinnedBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1418
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
EState * CreateExecutorState(void)
Definition: execUtils.c:90
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define GetPerTupleExprContext(estate)
Definition: executor.h:533
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:396
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
int32 type_maximum_size(Oid type_oid, int32 typemod)
Definition: format_type.c:408
@ UNIQUE_CHECK_NO
Definition: genam.h:116
@ UNIQUE_CHECK_YES
Definition: genam.h:117
int maintenance_work_mem
Definition: globals.c:126
void heap_finish_speculative(Relation relation, ItemPointer tid)
Definition: heapam.c:5728
void heap_insert(Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
Definition: heapam.c:2060
TM_Result heap_update(Relation relation, ItemPointer otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode)
Definition: heapam.c:3153
TM_Result heap_delete(Relation relation, ItemPointer tid, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
Definition: heapam.c:2700
bool heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition: heapam.c:1389
void heap_endscan(TableScanDesc sscan)
Definition: heapam.c:1307
void heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params, bool allow_strat, bool allow_sync, bool allow_pagemode)
Definition: heapam.c:1270
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
bool heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
Definition: heapam.c:1710
bool heap_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition: heapam.c:1492
void heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid, ItemPointer maxtid)
Definition: heapam.c:1419
void heap_abort_speculative(Relation relation, ItemPointer tid)
Definition: heapam.c:5819
TableScanDesc heap_beginscan(Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelTableScanDesc parallel_scan, uint32 flags)
Definition: heapam.c:1185
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf)
Definition: heapam.c:1595
void heapgetpage(TableScanDesc sscan, BlockNumber page)
Definition: heapam.c:371
TransactionId heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
Definition: heapam.c:7307
void heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples, CommandId cid, int options, BulkInsertState bistate)
Definition: heapam.c:2302
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:4228
void heap_get_latest_tid(TableScanDesc sscan, ItemPointer tid)
Definition: heapam.c:1862
void heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
Definition: heapam.c:348
void HeapCheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: heapam.c:9839
#define HEAP_INSERT_SPECULATIVE
Definition: heapam.h:37
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
@ HEAPTUPLE_RECENTLY_DEAD
Definition: heapam.h:97
@ HEAPTUPLE_INSERT_IN_PROGRESS
Definition: heapam.h:98
@ HEAPTUPLE_LIVE
Definition: heapam.h:96
@ HEAPTUPLE_DELETE_IN_PROGRESS
Definition: heapam.h:99
@ HEAPTUPLE_DEAD
Definition: heapam.h:95
static bool heapam_scan_analyze_next_block(TableScanDesc scan, BlockNumber blockno, BufferAccessStrategy bstrategy)
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 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)
#define HEAP_OVERHEAD_BYTES_PER_TUPLE
static void heapam_relation_copy_data(Relation rel, const RelFileNode *newrnode)
static void heapam_estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
static IndexFetchTableData * heapam_index_fetch_begin(Relation rel)
static const TableAmRoutine heapam_methods
static void heapam_index_validate_scan(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, Snapshot snapshot, ValidateIndexState *state)
static bool heapam_index_fetch_tuple(struct IndexFetchTableData *scan, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot, bool *call_again, bool *all_dead)
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 void heapam_tuple_insert_speculative(Relation relation, TupleTableSlot *slot, CommandId cid, int options, BulkInsertState bistate, uint32 specToken)
static bool heapam_scan_sample_next_block(TableScanDesc scan, SampleScanState *scanstate)
static void heapam_tuple_insert(Relation relation, TupleTableSlot *slot, CommandId cid, int options, BulkInsertState bistate)
static TM_Result heapam_tuple_delete(Relation relation, ItemPointer tid, CommandId cid, Snapshot snapshot, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
static void heapam_index_fetch_reset(IndexFetchTableData *scan)
static Oid heapam_relation_toast_am(Relation rel)
static bool heapam_relation_needs_toast_table(Relation rel)
static BlockNumber heapam_scan_get_blocks_done(HeapScanDesc hscan)
static bool heapam_scan_bitmap_next_block(TableScanDesc scan, TBMIterateResult *tbmres)
const TableAmRoutine * GetHeapamTableAmRoutine(void)
static bool heapam_scan_analyze_next_tuple(TableScanDesc scan, TransactionId OldestXmin, double *liverows, double *deadrows, TupleTableSlot *slot)
static bool SampleHeapTupleVisible(TableScanDesc scan, Buffer buffer, HeapTuple tuple, OffsetNumber tupoffset)
static void heapam_relation_set_new_filenode(Relation rel, const RelFileNode *newrnode, char persistence, TransactionId *freezeXid, MultiXactId *minmulti)
static bool heapam_scan_sample_next_tuple(TableScanDesc scan, SampleScanState *scanstate, TupleTableSlot *slot)
static const TupleTableSlotOps * heapam_slot_callbacks(Relation relation)
static bool heapam_tuple_tid_valid(TableScanDesc scan, ItemPointer tid)
#define HEAP_USABLE_BYTES_PER_PAGE
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_index_fetch_end(IndexFetchTableData *scan)
static void heapam_tuple_complete_speculative(Relation relation, TupleTableSlot *slot, uint32 specToken, bool succeeded)
static void reform_and_rewrite_tuple(HeapTuple tuple, Relation OldHeap, Relation NewHeap, Datum *values, bool *isnull, RewriteState rwstate)
static bool heapam_fetch_row_version(Relation relation, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot)
static bool heapam_scan_bitmap_next_tuple(TableScanDesc scan, TBMIterateResult *tbmres, TupleTableSlot *slot)
static void heapam_relation_nontransactional_truncate(Relation rel)
static bool heapam_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot, Snapshot snapshot)
Datum heap_tableam_handler(PG_FUNCTION_ARGS)
bool HeapTupleSatisfiesVisibility(HeapTuple tup, Snapshot snapshot, Buffer buffer)
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
void heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize, int32 sliceoffset, int32 slicelength, struct varlena *result)
Definition: heaptoast.c:626
#define TOAST_TUPLE_THRESHOLD
Definition: heaptoast.h:48
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1249
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define HeapTupleHeaderSetSpeculativeToken(tup, token)
Definition: htup_details.h:435
#define SizeofHeapTupleHeader
Definition: htup_details.h:184
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:308
#define BITMAPLEN(NATTS)
Definition: htup_details.h:541
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:679
#define HeapTupleIsHotUpdated(tuple)
Definition: htup_details.h:670
#define MaxHeapTuplesPerPage
Definition: htup_details.h:568
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:360
#define HeapTupleHeaderIsSpeculative(tup)
Definition: htup_details.h:424
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2672
static void itemptr_decode(ItemPointer itemptr, int64 encoded)
Definition: index.h:206
bool index_getnext_slot(IndexScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition: indexam.c:616
bool index_insert(Relation indexRelation, Datum *values, bool *isnull, ItemPointer heap_t_ctid, Relation heapRelation, IndexUniqueCheck checkUnique, bool indexUnchanged, IndexInfo *indexInfo)
Definition: indexam.c:176
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:205
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:323
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:297
int i
Definition: isn.c:73
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
#define ItemIdIsDead(itemId)
Definition: itemid.h:113
int32 ItemPointerCompare(ItemPointer arg1, ItemPointer arg2)
Definition: itemptr.c:52
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
#define ItemPointerCopy(fromPointer, toPointer)
Definition: itemptr.h:161
#define ItemPointerIndicatesMovedPartitions(pointer)
Definition: itemptr.h:184
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127
#define ItemPointerSetOffsetNumber(pointer, offsetNumber)
Definition: itemptr.h:148
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
Assert(fmt[strlen(fmt) - 1] !='\n')
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:640
bool ConditionalXactLockTableWait(TransactionId xid)
Definition: lmgr.c:713
@ XLTW_FetchUpdated
Definition: lmgr.h:33
@ XLTW_InsertIndexUnique
Definition: lmgr.h:32
LockWaitPolicy
Definition: lockoptions.h:37
@ LockWaitSkip
Definition: lockoptions.h:41
@ LockWaitBlock
Definition: lockoptions.h:39
@ LockWaitError
Definition: lockoptions.h:43
LockTupleMode
Definition: lockoptions.h:50
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
void pfree(void *pointer)
Definition: mcxt.c:1169
void * palloc0(Size size)
Definition: mcxt.c:1093
void * palloc(Size size)
Definition: mcxt.c:1062
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:406
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
MultiXactId GetOldestMultiXactId(void)
Definition: multixact.c:2506
@ T_TableAmRoutine
Definition: nodes.h:521
#define InvalidOffsetNumber
Definition: off.h:26
#define OffsetNumberIsValid(offsetNumber)
Definition: off.h:39
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
uint16 OffsetNumber
Definition: off.h:24
#define FirstOffsetNumber
Definition: off.h:27
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:42
static PgChecksumMode mode
Definition: pg_checksums.c:65
#define INDEX_MAX_KEYS
#define NIL
Definition: pg_list.h:65
static char * buf
Definition: pg_test_fsync.c:69
int progress
Definition: pgbench.c:271
#define pgstat_count_heap_fetch(rel)
Definition: pgstat.h:1062
#define pgstat_count_heap_getnext(rel)
Definition: pgstat.h:1057
uintptr_t Datum
Definition: postgres.h:411
#define DatumGetPointer(X)
Definition: postgres.h:593
#define DatumGetInt64(X)
Definition: postgres.h:651
unsigned int Oid
Definition: postgres_ext.h:31
void PredicateLockTID(Relation relation, ItemPointer tid, Snapshot snapshot, TransactionId tuple_xid)
Definition: predicate.c:2614
TransactionId GetOldestNonRemovableTransactionId(Relation rel)
Definition: procarray.c:2005
#define PROGRESS_CLUSTER_INDEX_RELID
Definition: progress.h:57
#define PROGRESS_CLUSTER_HEAP_BLKS_SCANNED
Definition: progress.h:61
#define PROGRESS_CLUSTER_PHASE_SORT_TUPLES
Definition: progress.h:67
#define PROGRESS_CLUSTER_PHASE_SEQ_SCAN_HEAP
Definition: progress.h:65
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
#define PROGRESS_CLUSTER_PHASE
Definition: progress.h:56
#define PROGRESS_CLUSTER_HEAP_TUPLES_SCANNED
Definition: progress.h:58
#define PROGRESS_CLUSTER_TOTAL_HEAP_BLKS
Definition: progress.h:60
#define PROGRESS_CLUSTER_HEAP_TUPLES_WRITTEN
Definition: progress.h:59
#define PROGRESS_CLUSTER_PHASE_INDEX_SCAN_HEAP
Definition: progress.h:66
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:119
#define PROGRESS_CLUSTER_PHASE_WRITE_NEW_HEAP
Definition: progress.h:68
void heap_get_root_tuples(Page page, OffsetNumber *root_offsets)
Definition: pruneheap.c:994
void heap_page_prune_opt(Relation relation, Buffer buffer)
Definition: pruneheap.c:87
#define RelationGetRelid(relation)
Definition: rel.h:477
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:544
#define RelationGetDescr(relation)
Definition: rel.h:503
#define RelationGetRelationName(relation)
Definition: rel.h:511
#define RelationGetTargetBlock(relation)
Definition: rel.h:574
#define RelationIsPermanent(relation)
Definition: rel.h:590
ForkNumber
Definition: relpath.h:41
@ MAIN_FORKNUM
Definition: relpath.h:43
@ INIT_FORKNUM
Definition: relpath.h:46
#define MAX_FORKNUM
Definition: relpath.h:55
struct ParallelBlockTableScanDescData * ParallelBlockTableScanDesc
Definition: relscan.h:85
void end_heap_rewrite(RewriteState state)
Definition: rewriteheap.c:300
bool rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
Definition: rewriteheap.c:563
RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap, TransactionId oldest_xmin, TransactionId freeze_xid, MultiXactId cutoff_multi)
Definition: rewriteheap.c:237
void rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple, HeapTuple new_tuple)
Definition: rewriteheap.c:361
@ ForwardScanDirection
Definition: sdir.h:26
void smgrimmedsync(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:660
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition: smgr.c:333
void smgrclose(SMgrRelation reln)
Definition: smgr.c:256
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:247
SMgrRelation smgropen(RelFileNode rnode, BackendId backend)
Definition: smgr.c:146
TransactionId RecentXmin
Definition: snapmgr.c:113
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:867
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:825
#define SnapshotAny
Definition: snapmgr.h:67
#define InitDirtySnapshot(snapshotdata)
Definition: snapmgr.h:74
#define IsMVCCSnapshot(snapshot)
Definition: snapmgr.h:96
void RelationCopyStorage(SMgrRelation src, SMgrRelation dst, ForkNumber forkNum, char relpersistence)
Definition: storage.c:414
void log_smgrcreate(const RelFileNode *rnode, ForkNumber forkNum)
Definition: storage.c:175
void RelationDropStorage(Relation rel)
Definition: storage.c:195
void RelationTruncate(Relation rel, BlockNumber nblocks)
Definition: storage.c:277
SMgrRelation RelationCreateStorage(RelFileNode rnode, char relpersistence)
Definition: storage.c:118
HeapTupleTableSlot base
Definition: tuptable.h:259
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:235
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:227
int rs_ntuples
Definition: heapam.h:76
bool rs_inited
Definition: heapam.h:58
Buffer rs_cbuf
Definition: heapam.h:60
BlockNumber rs_startblock
Definition: heapam.h:53
HeapTupleData rs_ctup
Definition: heapam.h:66
OffsetNumber rs_vistuples[MaxHeapTuplesPerPage]
Definition: heapam.h:77
BlockNumber rs_nblocks
Definition: heapam.h:52
BlockNumber rs_cblock
Definition: heapam.h:59
TableScanDescData rs_base
Definition: heapam.h:49
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66
ItemPointerData t_ctid
Definition: htup_details.h:160
HeapTupleData tupdata
Definition: tuptable.h:253
HeapTuple tuple
Definition: tuptable.h:250
Buffer xs_cbuf
Definition: heapam.h:88
IndexFetchTableData xs_base
Definition: heapam.h:86
bool ii_Unique
Definition: execnodes.h:173
bool ii_BrokenHotChain
Definition: execnodes.h:176
ExprState * ii_PredicateState
Definition: execnodes.h:165
Oid * ii_ExclusionOps
Definition: execnodes.h:166
bool ii_Concurrent
Definition: execnodes.h:175
List * ii_ExpressionsState
Definition: execnodes.h:163
List * ii_Predicate
Definition: execnodes.h:164
TupleDesc rd_att
Definition: rel.h:110
Oid rd_id
Definition: rel.h:111
BackendId rd_backend
Definition: rel.h:59
Form_pg_class rd_rel
Definition: rel.h:109
struct TsmRoutine * tsmroutine
Definition: execnodes.h:1404
TransactionId xmin
Definition: snapshot.h:157
TransactionId xmax
Definition: snapshot.h:158
bool takenDuringRecovery
Definition: snapshot.h:184
OffsetNumber offsets[FLEXIBLE_ARRAY_MEMBER]
Definition: tidbitmap.h:46
BlockNumber blockno
Definition: tidbitmap.h:42
bool traversed
Definition: tableam.h:129
TransactionId xmax
Definition: tableam.h:127
CommandId cmax
Definition: tableam.h:128
ItemPointerData ctid
Definition: tableam.h:126
NodeTag type
Definition: tableam.h:269
Relation rs_rd
Definition: relscan.h:34
uint32 rs_flags
Definition: relscan.h:47
struct SnapshotData * rs_snapshot
Definition: relscan.h:35
struct ParallelTableScanDescData * rs_parallel
Definition: relscan.h:49
NextSampleTuple_function NextSampleTuple
Definition: tsmapi.h:74
NextSampleBlock_function NextSampleBlock
Definition: tsmapi.h:73
Oid tts_tableOid
Definition: tuptable.h:131
ItemPointerData tts_tid
Definition: tuptable.h:130
Definition: regguts.h:318
void ss_report_location(Relation rel, BlockNumber location)
Definition: syncscan.c:288
Size table_block_parallelscan_initialize(Relation rel, ParallelTableScanDesc pscan)
Definition: tableam.c:400
void table_block_parallelscan_reinitialize(Relation rel, ParallelTableScanDesc pscan)
Definition: tableam.c:418
uint64 table_block_relation_size(Relation rel, ForkNumber forkNumber)
Definition: tableam.c:628
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
Size table_block_parallelscan_estimate(Relation rel)
Definition: tableam.c:394
void table_block_relation_estimate_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac, Size overhead_bytes_per_tuple, Size usable_bytes_per_page)
Definition: tableam.c:665
@ SO_ALLOW_PAGEMODE
Definition: tableam.h:61
@ SO_ALLOW_SYNC
Definition: tableam.h:59
static TableScanDesc table_beginscan(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key)
Definition: tableam.h:885
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:993
TM_Result
Definition: tableam.h:72
@ TM_Ok
Definition: tableam.h:77
@ TM_Deleted
Definition: tableam.h:92
@ TM_WouldBlock
Definition: tableam.h:102
@ TM_Updated
Definition: tableam.h:89
@ TM_SelfModified
Definition: tableam.h:83
static TableScanDesc table_beginscan_strat(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key, bool allow_strat, bool allow_sync)
Definition: tableam.h:909
#define TUPLE_LOCK_FLAG_FIND_LAST_VERSION
Definition: tableam.h:244
void(* IndexBuildCallback)(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *state)
Definition: tableam.h:248
static bool table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:1034
#define TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS
Definition: tableam.h:242
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:48
#define InvalidTransactionId
Definition: transam.h:31
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
#define TransactionIdIsValid(xid)
Definition: transam.h:41
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:2043
HeapTuple tuplesort_getheaptuple(Tuplesortstate *state, bool forward)
Definition: tuplesort.c:2445
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1467
Tuplesortstate * tuplesort_begin_cluster(TupleDesc tupDesc, Relation indexRel, int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:970
bool tuplesort_getdatum(Tuplesortstate *state, bool forward, Datum *val, bool *isNull, Datum *abbrev)
Definition: tuplesort.c:2494
void tuplesort_putheaptuple(Tuplesortstate *state, HeapTuple tup)
Definition: tuplesort.c:1709
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:148
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
#define TTS_IS_BUFFERTUPLE(slot)
Definition: tuptable.h:231
void heap_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy)
Definition: vacuumlazy.c:482
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:920