LCOV - differential code coverage report
Current view: top level - src/backend/access/heap - heapam_handler.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: 603a3335f2b60b2c798da5c627b3bb288b92a7bd vs e395fbd32a07557de4ac98088928c1749d4845d8 Lines: 93.0 % 820 763 57 763 4
Current Date: 2026-07-25 17:13:00 -0400 Functions: 100.0 % 32 32 1 31
Baseline: lcov-20260726-baseline Branches: 75.8 % 517 392 125 392
Baseline Date: 2026-07-25 19:16:42 +0200 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 92.4 % 92 85 7 85
(360..) days: 93.1 % 728 678 50 678
Function coverage date bins:
(30,360] days: 100.0 % 3 3 3
(360..) days: 100.0 % 29 29 1 28
Branch coverage date bins:
(30,360] days: 80.3 % 61 49 12 49
(360..) days: 75.2 % 456 343 113 343

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * heapam_handler.c
                                  4                 :                :  *    heap table access method code
                                  5                 :                :  *
                                  6                 :                :  * Portions Copyright (c) 1996-2026, 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 file 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/visibilitymap.h"
                                 31                 :                : #include "access/xact.h"
                                 32                 :                : #include "catalog/catalog.h"
                                 33                 :                : #include "catalog/index.h"
                                 34                 :                : #include "catalog/storage.h"
                                 35                 :                : #include "catalog/storage_xlog.h"
                                 36                 :                : #include "commands/progress.h"
                                 37                 :                : #include "executor/executor.h"
                                 38                 :                : #include "miscadmin.h"
                                 39                 :                : #include "pgstat.h"
                                 40                 :                : #include "storage/bufmgr.h"
                                 41                 :                : #include "storage/bufpage.h"
                                 42                 :                : #include "storage/lmgr.h"
                                 43                 :                : #include "storage/lock.h"
                                 44                 :                : #include "storage/predicate.h"
                                 45                 :                : #include "storage/procarray.h"
                                 46                 :                : #include "storage/smgr.h"
                                 47                 :                : #include "utils/builtins.h"
                                 48                 :                : #include "utils/rel.h"
                                 49                 :                : #include "utils/tuplesort.h"
                                 50                 :                : 
                                 51                 :                : static void reform_and_rewrite_tuple(HeapTuple tuple,
                                 52                 :                :                                      Relation OldHeap, Relation NewHeap,
                                 53                 :                :                                      Datum *values, bool *isnull, RewriteState rwstate);
                                 54                 :                : static void heap_insert_for_repack(HeapTuple tuple, Relation OldHeap,
                                 55                 :                :                                    Relation NewHeap, Datum *values, bool *isnull,
                                 56                 :                :                                    BulkInsertState bistate);
                                 57                 :                : static HeapTuple reform_tuple(HeapTuple tuple, Relation OldHeap,
                                 58                 :                :                               Relation NewHeap, Datum *values, bool *isnull);
                                 59                 :                : 
                                 60                 :                : static bool SampleHeapTupleVisible(TableScanDesc scan, Buffer buffer,
                                 61                 :                :                                    HeapTuple tuple,
                                 62                 :                :                                    OffsetNumber tupoffset);
                                 63                 :                : 
                                 64                 :                : static BlockNumber heapam_scan_get_blocks_done(HeapScanDesc hscan);
                                 65                 :                : 
                                 66                 :                : static bool BitmapHeapScanNextBlock(TableScanDesc scan,
                                 67                 :                :                                     bool *recheck,
                                 68                 :                :                                     uint64 *lossy_pages, uint64 *exact_pages);
                                 69                 :                : 
                                 70                 :                : 
                                 71                 :                : /* ------------------------------------------------------------------------
                                 72                 :                :  * Slot related callbacks for heap AM
                                 73                 :                :  * ------------------------------------------------------------------------
                                 74                 :                :  */
                                 75                 :                : 
                                 76                 :                : static const TupleTableSlotOps *
 2694 andres@anarazel.de         77                 :CBC    17529576 : heapam_slot_callbacks(Relation relation)
                                 78                 :                : {
                                 79                 :       17529576 :     return &TTSOpsBufferHeapTuple;
                                 80                 :                : }
                                 81                 :                : 
                                 82                 :                : 
                                 83                 :                : /* ------------------------------------------------------------------------
                                 84                 :                :  * Callbacks for non-modifying operations on individual tuples for heap AM
                                 85                 :                :  * ------------------------------------------------------------------------
                                 86                 :                :  */
                                 87                 :                : 
                                 88                 :                : static bool
 2680                            89                 :        2839286 : heapam_fetch_row_version(Relation relation,
                                 90                 :                :                          ItemPointer tid,
                                 91                 :                :                          Snapshot snapshot,
                                 92                 :                :                          TupleTableSlot *slot)
                                 93                 :                : {
                                 94                 :        2839286 :     BufferHeapTupleTableSlot *bslot = (BufferHeapTupleTableSlot *) slot;
                                 95                 :                :     Buffer      buffer;
                                 96                 :                : 
                                 97         [ -  + ]:        2839286 :     Assert(TTS_IS_BUFFERTUPLE(slot));
                                 98                 :                : 
                                 99                 :        2839286 :     bslot->base.tupdata.t_self = *tid;
 1565 tgl@sss.pgh.pa.us         100         [ +  + ]:        2839286 :     if (heap_fetch(relation, snapshot, &bslot->base.tupdata, &buffer, false))
                                101                 :                :     {
                                102                 :                :         /* store in slot, transferring existing pin */
 2680 andres@anarazel.de        103                 :        2838957 :         ExecStorePinnedBufferHeapTuple(&bslot->base.tupdata, slot, buffer);
                                104                 :        2838957 :         slot->tts_tableOid = RelationGetRelid(relation);
                                105                 :                : 
                                106                 :        2838957 :         return true;
                                107                 :                :     }
                                108                 :                : 
                                109                 :            321 :     return false;
                                110                 :                : }
                                111                 :                : 
                                112                 :                : static bool
 2627                           113                 :            468 : heapam_tuple_tid_valid(TableScanDesc scan, ItemPointer tid)
                                114                 :                : {
                                115                 :            468 :     HeapScanDesc hscan = (HeapScanDesc) scan;
                                116                 :                : 
                                117         [ +  + ]:            924 :     return ItemPointerIsValid(tid) &&
                                118         [ +  + ]:            456 :         ItemPointerGetBlockNumber(tid) < hscan->rs_nblocks;
                                119                 :                : }
                                120                 :                : 
                                121                 :                : static bool
 2694                           122                 :         773050 : heapam_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot,
                                123                 :                :                                 Snapshot snapshot)
                                124                 :                : {
                                125                 :         773050 :     BufferHeapTupleTableSlot *bslot = (BufferHeapTupleTableSlot *) slot;
                                126                 :                :     bool        res;
                                127                 :                : 
                                128         [ -  + ]:         773050 :     Assert(TTS_IS_BUFFERTUPLE(slot));
                                129         [ -  + ]:         773050 :     Assert(BufferIsValid(bslot->buffer));
                                130                 :                : 
                                131                 :                :     /*
                                132                 :                :      * We need buffer pin and lock to call HeapTupleSatisfiesVisibility.
                                133                 :                :      * Caller should be holding pin, but not lock.
                                134                 :                :      */
                                135                 :         773050 :     LockBuffer(bslot->buffer, BUFFER_LOCK_SHARE);
                                136                 :         773050 :     res = HeapTupleSatisfiesVisibility(bslot->base.tuple, snapshot,
                                137                 :                :                                        bslot->buffer);
                                138                 :         773050 :     LockBuffer(bslot->buffer, BUFFER_LOCK_UNLOCK);
                                139                 :                : 
                                140                 :         773050 :     return res;
                                141                 :                : }
                                142                 :                : 
                                143                 :                : 
                                144                 :                : /* ----------------------------------------------------------------------------
                                145                 :                :  *  Functions for manipulations of physical tuples for heap AM.
                                146                 :                :  * ----------------------------------------------------------------------------
                                147                 :                :  */
                                148                 :                : 
                                149                 :                : static void
 2682                           150                 :       10628199 : heapam_tuple_insert(Relation relation, TupleTableSlot *slot, CommandId cid,
                                151                 :                :                     uint32 options, BulkInsertState bistate)
                                152                 :                : {
                                153                 :       10628199 :     bool        shouldFree = true;
                                154                 :       10628199 :     HeapTuple   tuple = ExecFetchSlotHeapTuple(slot, true, &shouldFree);
                                155                 :                : 
                                156                 :                :     /* Update the tuple with table oid */
                                157                 :       10628199 :     slot->tts_tableOid = RelationGetRelid(relation);
                                158                 :       10628199 :     tuple->t_tableOid = slot->tts_tableOid;
                                159                 :                : 
                                160                 :                :     /* Perform the insertion, and copy the resulting ItemPointer */
                                161                 :       10628199 :     heap_insert(relation, tuple, cid, options, bistate);
                                162                 :       10628183 :     ItemPointerCopy(&tuple->t_self, &slot->tts_tid);
                                163                 :                : 
                                164         [ +  + ]:       10628183 :     if (shouldFree)
                                165                 :        2925364 :         pfree(tuple);
                                166                 :       10628183 : }
                                167                 :                : 
                                168                 :                : static void
 2675                           169                 :           2231 : heapam_tuple_insert_speculative(Relation relation, TupleTableSlot *slot,
                                170                 :                :                                 CommandId cid, uint32 options,
                                171                 :                :                                 BulkInsertState bistate, uint32 specToken)
                                172                 :                : {
 2682                           173                 :           2231 :     bool        shouldFree = true;
                                174                 :           2231 :     HeapTuple   tuple = ExecFetchSlotHeapTuple(slot, true, &shouldFree);
                                175                 :                : 
                                176                 :                :     /* Update the tuple with table oid */
                                177                 :           2231 :     slot->tts_tableOid = RelationGetRelid(relation);
                                178                 :           2231 :     tuple->t_tableOid = slot->tts_tableOid;
                                179                 :                : 
                                180                 :           2231 :     HeapTupleHeaderSetSpeculativeToken(tuple->t_data, specToken);
                                181                 :           2231 :     options |= HEAP_INSERT_SPECULATIVE;
                                182                 :                : 
                                183                 :                :     /* Perform the insertion, and copy the resulting ItemPointer */
                                184                 :           2231 :     heap_insert(relation, tuple, cid, options, bistate);
                                185                 :           2231 :     ItemPointerCopy(&tuple->t_self, &slot->tts_tid);
                                186                 :                : 
                                187         [ +  + ]:           2231 :     if (shouldFree)
                                188                 :             54 :         pfree(tuple);
                                189                 :           2231 : }
                                190                 :                : 
                                191                 :                : static void
 2675                           192                 :           2227 : heapam_tuple_complete_speculative(Relation relation, TupleTableSlot *slot,
                                193                 :                :                                   uint32 specToken, bool succeeded)
                                194                 :                : {
                                195                 :                :     /* adjust the tuple's state accordingly */
 2630                           196         [ +  + ]:           2227 :     if (succeeded)
 2682                           197                 :           2216 :         heap_finish_speculative(relation, &slot->tts_tid);
                                198                 :                :     else
                                199                 :             11 :         heap_abort_speculative(relation, &slot->tts_tid);
                                200                 :           2227 : }
                                201                 :                : 
                                202                 :                : static TM_Result
                                203                 :        1027733 : heapam_tuple_delete(Relation relation, ItemPointer tid, CommandId cid,
                                204                 :                :                     uint32 options, Snapshot snapshot, Snapshot crosscheck,
                                205                 :                :                     bool wait, TM_FailureData *tmfd)
                                206                 :                : {
                                207                 :                :     /*
                                208                 :                :      * Currently Deleting of index tuples are handled at vacuum, in case if
                                209                 :                :      * the storage itself is cleaning the dead tuples by itself, it is the
                                210                 :                :      * time to call the index tuple deletion also.
                                211                 :                :      */
  116 alvherre@kurilemu.de      212                 :        1027733 :     return heap_delete(relation, tid, cid, options, crosscheck, wait,
                                213                 :                :                        tmfd);
                                214                 :                : }
                                215                 :                : 
                                216                 :                : 
                                217                 :                : static TM_Result
 2682 andres@anarazel.de        218                 :        2244356 : heapam_tuple_update(Relation relation, ItemPointer otid, TupleTableSlot *slot,
                                219                 :                :                     CommandId cid, uint32 options,
                                220                 :                :                     Snapshot snapshot, Snapshot crosscheck,
                                221                 :                :                     bool wait, TM_FailureData *tmfd,
                                222                 :                :                     LockTupleMode *lockmode, TU_UpdateIndexes *update_indexes)
                                223                 :                : {
                                224                 :        2244356 :     bool        shouldFree = true;
                                225                 :        2244356 :     HeapTuple   tuple = ExecFetchSlotHeapTuple(slot, true, &shouldFree);
                                226                 :                :     TM_Result   result;
                                227                 :                : 
                                228                 :                :     /* Update the tuple with table oid */
                                229                 :        2244356 :     slot->tts_tableOid = RelationGetRelid(relation);
                                230                 :        2244356 :     tuple->t_tableOid = slot->tts_tableOid;
                                231                 :                : 
  116 alvherre@kurilemu.de      232                 :        2244356 :     result = heap_update(relation, otid, tuple, cid, options,
                                233                 :                :                          crosscheck, wait,
                                234                 :                :                          tmfd, lockmode, update_indexes);
 2682 andres@anarazel.de        235                 :        2244344 :     ItemPointerCopy(&tuple->t_self, &slot->tts_tid);
                                236                 :                : 
                                237                 :                :     /*
                                238                 :                :      * Decide whether new index entries are needed for the tuple
                                239                 :                :      *
                                240                 :                :      * Note: heap_update returns the tid (location) of the new tuple in the
                                241                 :                :      * t_self field.
                                242                 :                :      *
                                243                 :                :      * If the update is not HOT, we must update all indexes. If the update is
                                244                 :                :      * HOT, it could be that we updated summarized columns, so we either
                                245                 :                :      * update only summarized indexes, or none at all.
                                246                 :                :      */
 1224 tomas.vondra@postgre      247         [ +  + ]:        2244344 :     if (result != TM_Ok)
                                248                 :                :     {
                                249         [ -  + ]:            209 :         Assert(*update_indexes == TU_None);
                                250                 :            209 :         *update_indexes = TU_None;
                                251                 :                :     }
                                252         [ +  + ]:        2244135 :     else if (!HeapTupleIsHeapOnly(tuple))
                                253         [ -  + ]:        2173975 :         Assert(*update_indexes == TU_All);
                                254                 :                :     else
                                255   [ +  +  -  + ]:          70160 :         Assert((*update_indexes == TU_Summarizing) ||
                                256                 :                :                (*update_indexes == TU_None));
                                257                 :                : 
 2682 andres@anarazel.de        258         [ +  + ]:        2244344 :     if (shouldFree)
                                259                 :          31987 :         pfree(tuple);
                                260                 :                : 
                                261                 :        2244344 :     return result;
                                262                 :                : }
                                263                 :                : 
                                264                 :                : static TM_Result
                                265                 :         571513 : heapam_tuple_lock(Relation relation, ItemPointer tid, Snapshot snapshot,
                                266                 :                :                   TupleTableSlot *slot, CommandId cid, LockTupleMode mode,
                                267                 :                :                   LockWaitPolicy wait_policy, uint8 flags,
                                268                 :                :                   TM_FailureData *tmfd)
                                269                 :                : {
                                270                 :         571513 :     BufferHeapTupleTableSlot *bslot = (BufferHeapTupleTableSlot *) slot;
                                271                 :                :     TM_Result   result;
                                272                 :                :     Buffer      buffer;
                                273                 :         571513 :     HeapTuple   tuple = &bslot->base.tupdata;
                                274                 :                :     bool        follow_updates;
                                275                 :                : 
                                276                 :         571513 :     follow_updates = (flags & TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS) != 0;
                                277                 :         571513 :     tmfd->traversed = false;
                                278                 :                : 
                                279         [ +  - ]:         571513 :     Assert(TTS_IS_BUFFERTUPLE(slot));
                                280                 :                : 
                                281                 :         571513 : tuple_lock_retry:
  836 akorotkov@postgresql      282                 :         571704 :     tuple->t_self = *tid;
                                283                 :         571704 :     result = heap_lock_tuple(relation, tuple, cid, mode, wait_policy,
                                284                 :                :                              follow_updates, &buffer, tmfd);
                                285                 :                : 
 2682 andres@anarazel.de        286         [ +  + ]:         571691 :     if (result == TM_Updated &&
                                287         [ +  + ]:            234 :         (flags & TUPLE_LOCK_FLAG_FIND_LAST_VERSION))
                                288                 :                :     {
                                289                 :                :         /* Should not encounter speculative tuple on recheck */
 1210 akorotkov@postgresql      290         [ -  + ]:            214 :         Assert(!HeapTupleHeaderIsSpeculative(tuple->t_data));
                                291                 :                : 
  836                           292                 :            214 :         ReleaseBuffer(buffer);
                                293                 :                : 
 2682 andres@anarazel.de        294         [ +  - ]:            214 :         if (!ItemPointerEquals(&tmfd->ctid, &tuple->t_self))
                                295                 :                :         {
                                296                 :                :             SnapshotData SnapshotDirty;
                                297                 :                :             TransactionId priorXmax;
                                298                 :                : 
                                299                 :                :             /* it was updated, so look at the updated version */
                                300                 :            214 :             *tid = tmfd->ctid;
                                301                 :                :             /* updated row should have xmin matching this xmax */
                                302                 :            214 :             priorXmax = tmfd->xmax;
                                303                 :                : 
                                304                 :                :             /* signal that a tuple later in the chain is getting locked */
                                305                 :            214 :             tmfd->traversed = true;
                                306                 :                : 
                                307                 :                :             /*
                                308                 :                :              * fetch target tuple
                                309                 :                :              *
                                310                 :                :              * Loop here to deal with updated or busy tuples
                                311                 :                :              */
                                312                 :            214 :             InitDirtySnapshot(SnapshotDirty);
                                313                 :                :             for (;;)
                                314                 :                :             {
                                315         [ +  + ]:            249 :                 if (ItemPointerIndicatesMovedPartitions(tid))
                                316         [ +  - ]:             11 :                     ereport(ERROR,
                                317                 :                :                             (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                318                 :                :                              errmsg("tuple to be locked was already moved to another partition due to concurrent update")));
                                319                 :                : 
                                320                 :            238 :                 tuple->t_self = *tid;
 1565 tgl@sss.pgh.pa.us         321         [ +  + ]:            238 :                 if (heap_fetch(relation, &SnapshotDirty, tuple, &buffer, true))
                                322                 :                :                 {
                                323                 :                :                     /*
                                324                 :                :                      * If xmin isn't what we're expecting, the slot must have
                                325                 :                :                      * been recycled and reused for an unrelated tuple.  This
                                326                 :                :                      * implies that the latest version of the row was deleted,
                                327                 :                :                      * so we need do nothing.  (Should be safe to examine xmin
                                328                 :                :                      * without getting buffer's content lock.  We assume
                                329                 :                :                      * reading a TransactionId to be atomic, and Xmin never
                                330                 :                :                      * changes in an existing tuple, except to invalid or
                                331                 :                :                      * frozen, and neither of those can match priorXmax.)
                                332                 :                :                      */
 2682 andres@anarazel.de        333         [ -  + ]:            200 :                     if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple->t_data),
                                334                 :                :                                              priorXmax))
                                335                 :                :                     {
 2682 andres@anarazel.de        336                 :UBC           0 :                         ReleaseBuffer(buffer);
 2682 andres@anarazel.de        337                 :CBC          11 :                         return TM_Deleted;
                                338                 :                :                     }
                                339                 :                : 
                                340                 :                :                     /* otherwise xmin should not be dirty... */
                                341         [ -  + ]:            200 :                     if (TransactionIdIsValid(SnapshotDirty.xmin))
 2551 peter@eisentraut.org      342         [ #  # ]:UBC           0 :                         ereport(ERROR,
                                343                 :                :                                 (errcode(ERRCODE_DATA_CORRUPTED),
                                344                 :                :                                  errmsg_internal("t_xmin %u is uncommitted in tuple (%u,%u) to be updated in table \"%s\"",
                                345                 :                :                                                  SnapshotDirty.xmin,
                                346                 :                :                                                  ItemPointerGetBlockNumber(&tuple->t_self),
                                347                 :                :                                                  ItemPointerGetOffsetNumber(&tuple->t_self),
                                348                 :                :                                                  RelationGetRelationName(relation))));
                                349                 :                : 
                                350                 :                :                     /*
                                351                 :                :                      * If tuple is being updated by other transaction then we
                                352                 :                :                      * have to wait for its commit/abort, or die trying.
                                353                 :                :                      */
 2682 andres@anarazel.de        354         [ +  + ]:CBC         200 :                     if (TransactionIdIsValid(SnapshotDirty.xmax))
                                355                 :                :                     {
                                356                 :              2 :                         ReleaseBuffer(buffer);
                                357   [ -  +  +  - ]:              2 :                         switch (wait_policy)
                                358                 :                :                         {
 2682 andres@anarazel.de        359                 :UBC           0 :                             case LockWaitBlock:
                                360                 :              0 :                                 XactLockTableWait(SnapshotDirty.xmax,
                                361                 :              0 :                                                   relation, &tuple->t_self,
                                362                 :                :                                                   XLTW_FetchUpdated);
                                363                 :              0 :                                 break;
 2682 andres@anarazel.de        364                 :CBC           1 :                             case LockWaitSkip:
  499 fujii@postgresql.org      365         [ +  - ]:              1 :                                 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax, false))
                                366                 :                :                                     /* skip instead of waiting */
 2682 andres@anarazel.de        367                 :              1 :                                     return TM_WouldBlock;
 2682 andres@anarazel.de        368                 :UBC           0 :                                 break;
 2682 andres@anarazel.de        369                 :CBC           1 :                             case LockWaitError:
  418 fujii@postgresql.org      370         [ +  - ]:              1 :                                 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax, log_lock_failures))
 2682 andres@anarazel.de        371         [ +  - ]:              1 :                                     ereport(ERROR,
                                372                 :                :                                             (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                                373                 :                :                                              errmsg("could not obtain lock on row in relation \"%s\"",
                                374                 :                :                                                     RelationGetRelationName(relation))));
 2682 andres@anarazel.de        375                 :UBC           0 :                                 break;
                                376                 :                :                         }
                                377                 :              0 :                         continue;   /* loop back to repeat heap_fetch */
                                378                 :                :                     }
                                379                 :                : 
                                380                 :                :                     /*
                                381                 :                :                      * If tuple was inserted by our own transaction, we have
                                382                 :                :                      * to check cmin against cid: cmin >= current CID means
                                383                 :                :                      * our command cannot see the tuple, so we should ignore
                                384                 :                :                      * it. Otherwise heap_lock_tuple() will throw an error,
                                385                 :                :                      * and so would any later attempt to update or delete the
                                386                 :                :                      * tuple.  (We need not check cmax because
                                387                 :                :                      * HeapTupleSatisfiesDirty will consider a tuple deleted
                                388                 :                :                      * by our transaction dead, regardless of cmax.)  We just
                                389                 :                :                      * checked that priorXmax == xmin, so we can test that
                                390                 :                :                      * variable instead of doing HeapTupleHeaderGetXmin again.
                                391                 :                :                      */
 2682 andres@anarazel.de        392   [ +  +  +  - ]:CBC         205 :                     if (TransactionIdIsCurrentTransactionId(priorXmax) &&
                                393                 :              7 :                         HeapTupleHeaderGetCmin(tuple->t_data) >= cid)
                                394                 :                :                     {
 2667                           395                 :              7 :                         tmfd->xmax = priorXmax;
                                396                 :                : 
                                397                 :                :                         /*
                                398                 :                :                          * Cmin is the problematic value, so store that. See
                                399                 :                :                          * above.
                                400                 :                :                          */
                                401                 :              7 :                         tmfd->cmax = HeapTupleHeaderGetCmin(tuple->t_data);
 2682                           402                 :              7 :                         ReleaseBuffer(buffer);
 2667                           403                 :              7 :                         return TM_SelfModified;
                                404                 :                :                     }
                                405                 :                : 
                                406                 :                :                     /*
                                407                 :                :                      * This is a live tuple, so try to lock it again.
                                408                 :                :                      */
  836 akorotkov@postgresql      409                 :            191 :                     ReleaseBuffer(buffer);
 2682 andres@anarazel.de        410                 :            191 :                     goto tuple_lock_retry;
                                411                 :                :                 }
                                412                 :                : 
                                413                 :                :                 /*
                                414                 :                :                  * If the referenced slot was actually empty, the latest
                                415                 :                :                  * version of the row must have been deleted, so we need do
                                416                 :                :                  * nothing.
                                417                 :                :                  */
                                418         [ -  + ]:             38 :                 if (tuple->t_data == NULL)
                                419                 :                :                 {
  836 akorotkov@postgresql      420         [ #  # ]:UBC           0 :                     Assert(!BufferIsValid(buffer));
 2682 andres@anarazel.de        421                 :              0 :                     return TM_Deleted;
                                422                 :                :                 }
                                423                 :                : 
                                424                 :                :                 /*
                                425                 :                :                  * As above, if xmin isn't what we're expecting, do nothing.
                                426                 :                :                  */
 2682 andres@anarazel.de        427         [ -  + ]:CBC          38 :                 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple->t_data),
                                428                 :                :                                          priorXmax))
                                429                 :                :                 {
 1565 tgl@sss.pgh.pa.us         430                 :UBC           0 :                     ReleaseBuffer(buffer);
 2682 andres@anarazel.de        431                 :              0 :                     return TM_Deleted;
                                432                 :                :                 }
                                433                 :                : 
                                434                 :                :                 /*
                                435                 :                :                  * If we get here, the tuple was found but failed
                                436                 :                :                  * SnapshotDirty. Assuming the xmin is either a committed xact
                                437                 :                :                  * or our own xact (as it certainly should be if we're trying
                                438                 :                :                  * to modify the tuple), this must mean that the row was
                                439                 :                :                  * updated or deleted by either a committed xact or our own
                                440                 :                :                  * xact.  If it was deleted, we can ignore it; if it was
                                441                 :                :                  * updated then chain up to the next version and repeat the
                                442                 :                :                  * whole process.
                                443                 :                :                  *
                                444                 :                :                  * As above, it should be safe to examine xmax and t_ctid
                                445                 :                :                  * without the buffer content lock, because they can't be
                                446                 :                :                  * changing.  We'd better hold a buffer pin though.
                                447                 :                :                  */
 2682 andres@anarazel.de        448         [ +  + ]:CBC          38 :                 if (ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
                                449                 :                :                 {
                                450                 :                :                     /* deleted, so forget about it */
 1565 tgl@sss.pgh.pa.us         451                 :              3 :                     ReleaseBuffer(buffer);
 2682 andres@anarazel.de        452                 :              3 :                     return TM_Deleted;
                                453                 :                :                 }
                                454                 :                : 
                                455                 :                :                 /* updated, so look at the updated row */
                                456                 :             35 :                 *tid = tuple->t_data->t_ctid;
                                457                 :                :                 /* updated row should have xmin matching this xmax */
                                458                 :             35 :                 priorXmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
 1565 tgl@sss.pgh.pa.us         459                 :             35 :                 ReleaseBuffer(buffer);
                                460                 :                :                 /* loop back to fetch next in chain */
                                461                 :                :             }
                                462                 :                :         }
                                463                 :                :         else
                                464                 :                :         {
                                465                 :                :             /* tuple was deleted, so give up */
 2682 andres@anarazel.de        466                 :UBC           0 :             return TM_Deleted;
                                467                 :                :         }
                                468                 :                :     }
                                469                 :                : 
 2682 andres@anarazel.de        470                 :CBC      571477 :     slot->tts_tableOid = RelationGetRelid(relation);
                                471                 :         571477 :     tuple->t_tableOid = slot->tts_tableOid;
                                472                 :                : 
                                473                 :                :     /* store in slot, transferring existing pin */
  836 akorotkov@postgresql      474                 :         571477 :     ExecStorePinnedBufferHeapTuple(tuple, slot, buffer);
                                475                 :                : 
 2682 andres@anarazel.de        476                 :         571477 :     return result;
                                477                 :                : }
                                478                 :                : 
                                479                 :                : 
                                480                 :                : /* ------------------------------------------------------------------------
                                481                 :                :  * DDL related callbacks for heap AM.
                                482                 :                :  * ------------------------------------------------------------------------
                                483                 :                :  */
                                484                 :                : 
                                485                 :                : static void
 1481 rhaas@postgresql.org      486                 :          44068 : heapam_relation_set_new_filelocator(Relation rel,
                                487                 :                :                                     const RelFileLocator *newrlocator,
                                488                 :                :                                     char persistence,
                                489                 :                :                                     TransactionId *freezeXid,
                                490                 :                :                                     MultiXactId *minmulti)
                                491                 :                : {
                                492                 :                :     SMgrRelation srel;
                                493                 :                : 
                                494                 :                :     /*
                                495                 :                :      * Initialize to the minimum XID that could put tuples in the table. We
                                496                 :                :      * know that no xacts older than RecentXmin are still running, so that
                                497                 :                :      * will do.
                                498                 :                :      */
 2677 andres@anarazel.de        499                 :          44068 :     *freezeXid = RecentXmin;
                                500                 :                : 
                                501                 :                :     /*
                                502                 :                :      * Similarly, initialize the minimum Multixact to the first value that
                                503                 :                :      * could possibly be stored in tuples in the table.  Running transactions
                                504                 :                :      * could reuse values from their local cache, so we are careful to
                                505                 :                :      * consider all currently running multis.
                                506                 :                :      *
                                507                 :                :      * XXX this could be refined further, but is it worth the hassle?
                                508                 :                :      */
                                509                 :          44068 :     *minmulti = GetOldestMultiXactId();
                                510                 :                : 
 1481 rhaas@postgresql.org      511                 :          44068 :     srel = RelationCreateStorage(*newrlocator, persistence, true);
                                512                 :                : 
                                513                 :                :     /*
                                514                 :                :      * If required, set up an init fork for an unlogged table so that it can
                                515                 :                :      * be correctly reinitialized on restart.
                                516                 :                :      */
 2645 andres@anarazel.de        517         [ +  + ]:          44068 :     if (persistence == RELPERSISTENCE_UNLOGGED)
                                518                 :                :     {
 2677                           519   [ +  +  -  + ]:            181 :         Assert(rel->rd_rel->relkind == RELKIND_RELATION ||
                                520                 :                :                rel->rd_rel->relkind == RELKIND_TOASTVALUE);
 2645                           521                 :            181 :         smgrcreate(srel, INIT_FORKNUM, false);
 1481 rhaas@postgresql.org      522                 :            181 :         log_smgrcreate(newrlocator, INIT_FORKNUM);
                                523                 :                :     }
                                524                 :                : 
 2645 andres@anarazel.de        525                 :          44068 :     smgrclose(srel);
 2677                           526                 :          44068 : }
                                527                 :                : 
                                528                 :                : static void
                                529                 :            372 : heapam_relation_nontransactional_truncate(Relation rel)
                                530                 :                : {
                                531                 :            372 :     RelationTruncate(rel, 0);
                                532                 :            372 : }
                                533                 :                : 
                                534                 :                : static void
 1481 rhaas@postgresql.org      535                 :             67 : heapam_relation_copy_data(Relation rel, const RelFileLocator *newrlocator)
                                536                 :                : {
                                537                 :                :     SMgrRelation dstrel;
                                538                 :                : 
                                539                 :                :     /*
                                540                 :                :      * Since we copy the file directly without looking at the shared buffers,
                                541                 :                :      * we'd better first flush out any pages of the source relation that are
                                542                 :                :      * in shared buffers.  We assume no new changes will be made while we are
                                543                 :                :      * holding exclusive lock on the rel.
                                544                 :                :      */
 2645 andres@anarazel.de        545                 :             67 :     FlushRelationBuffers(rel);
                                546                 :                : 
                                547                 :                :     /*
                                548                 :                :      * Create and copy all forks of the relation, and schedule unlinking of
                                549                 :                :      * old physical files.
                                550                 :                :      *
                                551                 :                :      * NOTE: any conflict in relfilenumber value will be caught in
                                552                 :                :      * RelationCreateStorage().
                                553                 :                :      */
  895 heikki.linnakangas@i      554                 :             67 :     dstrel = RelationCreateStorage(*newrlocator, rel->rd_rel->relpersistence, true);
                                555                 :                : 
                                556                 :                :     /* copy main fork */
 1840 tgl@sss.pgh.pa.us         557                 :             67 :     RelationCopyStorage(RelationGetSmgr(rel), dstrel, MAIN_FORKNUM,
 2677 andres@anarazel.de        558                 :             67 :                         rel->rd_rel->relpersistence);
                                559                 :                : 
                                560                 :                :     /* copy those extra forks that exist */
                                561                 :             67 :     for (ForkNumber forkNum = MAIN_FORKNUM + 1;
                                562         [ +  + ]:            268 :          forkNum <= MAX_FORKNUM; forkNum++)
                                563                 :                :     {
 1840 tgl@sss.pgh.pa.us         564         [ +  + ]:            201 :         if (smgrexists(RelationGetSmgr(rel), forkNum))
                                565                 :                :         {
 2677 andres@anarazel.de        566                 :             23 :             smgrcreate(dstrel, forkNum, false);
                                567                 :                : 
                                568                 :                :             /*
                                569                 :                :              * WAL log creation if the relation is persistent, or this is the
                                570                 :                :              * init fork of an unlogged relation.
                                571                 :                :              */
 1952 bruce@momjian.us          572         [ +  + ]:             23 :             if (RelationIsPermanent(rel) ||
 2677 andres@anarazel.de        573   [ -  +  -  - ]:              8 :                 (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
                                574                 :                :                  forkNum == INIT_FORKNUM))
 1481 rhaas@postgresql.org      575                 :             15 :                 log_smgrcreate(newrlocator, forkNum);
 1840 tgl@sss.pgh.pa.us         576                 :             23 :             RelationCopyStorage(RelationGetSmgr(rel), dstrel, forkNum,
 2677 andres@anarazel.de        577                 :             23 :                                 rel->rd_rel->relpersistence);
                                578                 :                :         }
                                579                 :                :     }
                                580                 :                : 
                                581                 :                : 
                                582                 :                :     /* drop old relation, and close new one */
                                583                 :             67 :     RelationDropStorage(rel);
                                584                 :             67 :     smgrclose(dstrel);
                                585                 :             67 : }
                                586                 :                : 
                                587                 :                : static void
                                588                 :            409 : heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
                                589                 :                :                                  Relation OldIndex, bool use_sort,
                                590                 :                :                                  TransactionId OldestXmin,
                                591                 :                :                                  Snapshot snapshot,
                                592                 :                :                                  TransactionId *xid_cutoff,
                                593                 :                :                                  MultiXactId *multi_cutoff,
                                594                 :                :                                  double *num_tuples,
                                595                 :                :                                  double *tups_vacuumed,
                                596                 :                :                                  double *tups_recently_dead)
                                597                 :                : {
                                598                 :                :     RewriteState rwstate;
                                599                 :                :     BulkInsertState bistate;
                                600                 :                :     IndexScanDesc indexScan;
                                601                 :                :     TableScanDesc tableScan;
                                602                 :                :     HeapScanDesc heapScan;
                                603                 :                :     bool        is_system_catalog;
                                604                 :                :     Tuplesortstate *tuplesort;
                                605                 :            409 :     TupleDesc   oldTupDesc = RelationGetDescr(OldHeap);
                                606                 :            409 :     TupleDesc   newTupDesc = RelationGetDescr(NewHeap);
                                607                 :                :     TupleTableSlot *slot;
                                608                 :                :     int         natts;
                                609                 :                :     Datum      *values;
                                610                 :                :     bool       *isnull;
                                611                 :                :     BufferHeapTupleTableSlot *hslot;
 2067 fujii@postgresql.org      612                 :            409 :     BlockNumber prev_cblock = InvalidBlockNumber;
  111 alvherre@kurilemu.de      613                 :            409 :     bool        concurrent = snapshot != NULL;
                                614                 :                : 
                                615                 :                :     /* Remember if it's a system catalog */
 2677 andres@anarazel.de        616                 :            409 :     is_system_catalog = IsSystemRelation(OldHeap);
                                617                 :                : 
                                618                 :                :     /*
                                619                 :                :      * Valid smgr_targblock implies something already wrote to the relation.
                                620                 :                :      * This may be harmless, but this function hasn't planned for it.
                                621                 :                :      */
                                622   [ -  +  -  - ]:            409 :     Assert(RelationGetTargetBlock(NewHeap) == InvalidBlockNumber);
                                623                 :                : 
                                624                 :                :     /* Preallocate values/isnull arrays */
                                625                 :            409 :     natts = newTupDesc->natts;
  228 michael@paquier.xyz       626                 :            409 :     values = palloc_array(Datum, natts);
                                627                 :            409 :     isnull = palloc_array(bool, natts);
                                628                 :                : 
                                629                 :                :     /*
                                630                 :                :      * In non-concurrent mode, initialize the rewrite operation.  This is not
                                631                 :                :      * needed in concurrent mode.
                                632                 :                :      */
  111 alvherre@kurilemu.de      633         [ +  + ]:            409 :     if (!concurrent)
                                634                 :            402 :         rwstate = begin_heap_rewrite(OldHeap, NewHeap, OldestXmin,
                                635                 :                :                                      *xid_cutoff, *multi_cutoff);
                                636                 :                :     else
                                637                 :              7 :         rwstate = NULL;
                                638                 :                : 
                                639                 :                :     /* In concurrent mode, prepare for bulk-insert operation. */
                                640         [ +  + ]:            409 :     if (concurrent)
                                641                 :              7 :         bistate = GetBulkInsertState();
                                642                 :                :     else
                                643                 :            402 :         bistate = NULL;
                                644                 :                : 
                                645                 :                :     /* Set up sorting if wanted */
 2677 andres@anarazel.de        646         [ +  + ]:            409 :     if (use_sort)
 1142 pg@bowt.ie                647                 :             85 :         tuplesort = tuplesort_begin_cluster(oldTupDesc, OldIndex,
                                648                 :                :                                             maintenance_work_mem,
                                649                 :                :                                             NULL, TUPLESORT_NONE);
                                650                 :                :     else
 2677 andres@anarazel.de        651                 :            324 :         tuplesort = NULL;
                                652                 :                : 
                                653                 :                :     /*
                                654                 :                :      * Prepare to scan the OldHeap.  To ensure we see recently-dead tuples
                                655                 :                :      * that still need to be copied, we scan with SnapshotAny and use
                                656                 :                :      * HeapTupleSatisfiesVacuum for the visibility test.
                                657                 :                :      *
                                658                 :                :      * In the CONCURRENTLY case, we do regular MVCC visibility tests, using
                                659                 :                :      * the snapshot passed by the caller.
                                660                 :                :      */
                                661   [ +  +  +  + ]:            409 :     if (OldIndex != NULL && !use_sort)
                                662                 :             62 :     {
 2675                           663                 :             62 :         const int   ci_index[] = {
                                664                 :                :             PROGRESS_REPACK_PHASE,
                                665                 :                :             PROGRESS_REPACK_INDEX_RELID
                                666                 :                :         };
                                667                 :                :         int64       ci_val[2];
                                668                 :                : 
                                669                 :                :         /* Set phase and OIDOldIndex to columns */
  138 alvherre@kurilemu.de      670                 :             62 :         ci_val[0] = PROGRESS_REPACK_PHASE_INDEX_SCAN_HEAP;
 2677 andres@anarazel.de        671                 :             62 :         ci_val[1] = RelationGetRelid(OldIndex);
                                672                 :             62 :         pgstat_progress_update_multi_param(2, ci_index, ci_val);
                                673                 :                : 
                                674                 :             62 :         tableScan = NULL;
                                675                 :             62 :         heapScan = NULL;
  111 alvherre@kurilemu.de      676         [ +  + ]:             62 :         indexScan = index_beginscan(OldHeap, OldIndex,
                                677                 :                :                                     snapshot ? snapshot : SnapshotAny,
                                678                 :                :                                     NULL, 0, 0,
                                679                 :                :                                     SO_NONE);
 2677 andres@anarazel.de        680                 :             62 :         index_rescan(indexScan, NULL, 0, NULL, 0);
                                681                 :                :     }
                                682                 :                :     else
                                683                 :                :     {
                                684                 :                :         /* In scan-and-sort mode and also VACUUM FULL, set phase */
  138 alvherre@kurilemu.de      685                 :            347 :         pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
                                686                 :                :                                      PROGRESS_REPACK_PHASE_SEQ_SCAN_HEAP);
                                687                 :                : 
  111                           688         [ +  + ]:            347 :         tableScan = table_beginscan(OldHeap,
                                689                 :                :                                     snapshot ? snapshot : SnapshotAny,
                                690                 :                :                                     0, (ScanKey) NULL,
                                691                 :                :                                     SO_NONE);
 2677 andres@anarazel.de        692                 :            347 :         heapScan = (HeapScanDesc) tableScan;
                                693                 :            347 :         indexScan = NULL;
                                694                 :                : 
                                695                 :                :         /* Set total heap blocks */
  138 alvherre@kurilemu.de      696                 :            347 :         pgstat_progress_update_param(PROGRESS_REPACK_TOTAL_HEAP_BLKS,
 2677 andres@anarazel.de        697                 :            347 :                                      heapScan->rs_nblocks);
                                698                 :                :     }
                                699                 :                : 
                                700                 :            409 :     slot = table_slot_create(OldHeap, NULL);
                                701                 :            409 :     hslot = (BufferHeapTupleTableSlot *) slot;
                                702                 :                : 
                                703                 :                :     /*
                                704                 :                :      * Scan through the OldHeap, either in OldIndex order or sequentially;
                                705                 :                :      * copy each tuple into the NewHeap, or transiently to the tuplesort
                                706                 :                :      * module.  Note that we don't bother sorting dead tuples (they won't get
                                707                 :                :      * to the new table anyway).
                                708                 :                :      */
                                709                 :                :     for (;;)
                                710                 :         496074 :     {
                                711                 :                :         HeapTuple   tuple;
                                712                 :                :         Buffer      buf;
                                713                 :                :         bool        isdead;
                                714                 :                : 
                                715         [ -  + ]:         496483 :         CHECK_FOR_INTERRUPTS();
                                716                 :                : 
                                717         [ +  + ]:         496483 :         if (indexScan != NULL)
                                718                 :                :         {
                                719         [ +  + ]:           1204 :             if (!index_getnext_slot(indexScan, ForwardScanDirection, slot))
                                720                 :             62 :                 break;
                                721                 :                : 
                                722                 :                :             /* Since we used no scan keys, should never need to recheck */
                                723         [ -  + ]:           1142 :             if (indexScan->xs_recheck)
 2677 andres@anarazel.de        724         [ #  # ]:UBC           0 :                 elog(ERROR, "CLUSTER does not support lossy index conditions");
                                725                 :                :         }
                                726                 :                :         else
                                727                 :                :         {
 2677 andres@anarazel.de        728         [ +  + ]:CBC      495279 :             if (!table_scan_getnextslot(tableScan, ForwardScanDirection, slot))
                                729                 :                :             {
                                730                 :                :                 /*
                                731                 :                :                  * If the last pages of the scan were empty, we would go to
                                732                 :                :                  * the next phase while heap_blks_scanned != heap_blks_total.
                                733                 :                :                  * Instead, to ensure that heap_blks_scanned is equivalent to
                                734                 :                :                  * heap_blks_total after the table scan phase, this parameter
                                735                 :                :                  * is manually updated to the correct value when the table
                                736                 :                :                  * scan finishes.
                                737                 :                :                  */
  138 alvherre@kurilemu.de      738                 :            347 :                 pgstat_progress_update_param(PROGRESS_REPACK_HEAP_BLKS_SCANNED,
 2067 fujii@postgresql.org      739                 :            347 :                                              heapScan->rs_nblocks);
 2677 andres@anarazel.de        740                 :            347 :                 break;
                                741                 :                :             }
                                742                 :                : 
                                743                 :                :             /*
                                744                 :                :              * In scan-and-sort mode and also VACUUM FULL, set heap blocks
                                745                 :                :              * scanned
                                746                 :                :              *
                                747                 :                :              * Note that heapScan may start at an offset and wrap around, i.e.
                                748                 :                :              * rs_startblock may be >0, and rs_cblock may end with a number
                                749                 :                :              * below rs_startblock. To prevent showing this wraparound to the
                                750                 :                :              * user, we offset rs_cblock by rs_startblock (modulo rs_nblocks).
                                751                 :                :              */
 2067 fujii@postgresql.org      752         [ +  + ]:         494932 :             if (prev_cblock != heapScan->rs_cblock)
                                753                 :                :             {
  138 alvherre@kurilemu.de      754                 :           7159 :                 pgstat_progress_update_param(PROGRESS_REPACK_HEAP_BLKS_SCANNED,
 2067 fujii@postgresql.org      755                 :           7159 :                                              (heapScan->rs_cblock +
                                756                 :           7159 :                                               heapScan->rs_nblocks -
                                757                 :           7159 :                                               heapScan->rs_startblock
                                758                 :           7159 :                                               ) % heapScan->rs_nblocks + 1);
                                759                 :           7159 :                 prev_cblock = heapScan->rs_cblock;
                                760                 :                :             }
                                761                 :                :         }
                                762                 :                : 
 2677 andres@anarazel.de        763                 :         496074 :         tuple = ExecFetchSlotHeapTuple(slot, false, NULL);
                                764                 :         496074 :         buf = hslot->buffer;
                                765                 :                : 
                                766                 :                :         /*
                                767                 :                :          * In concurrent mode, our table or index scan has used regular MVCC
                                768                 :                :          * visibility test against a snapshot passed by caller; therefore we
                                769                 :                :          * don't need another visibility test.  In non-concurrent mode
                                770                 :                :          * however, we must test the visibility of each tuple we read.
                                771                 :                :          */
  111 alvherre@kurilemu.de      772         [ +  + ]:         496074 :         if (!concurrent)
                                773                 :                :         {
                                774                 :                :             /*
                                775                 :                :              * To be able to guarantee that we can set the hint bit, acquire
                                776                 :                :              * an exclusive lock on the old buffer. We need the hint bits, set
                                777                 :                :              * in heapam_relation_copy_for_cluster() ->
                                778                 :                :              * HeapTupleSatisfiesVacuum(), to be set, as otherwise
                                779                 :                :              * reform_and_rewrite_tuple() -> rewrite_heap_tuple() will get
                                780                 :                :              * confused. Specifically, rewrite_heap_tuple() checks for
                                781                 :                :              * HEAP_XMAX_INVALID in the old tuple to determine whether to
                                782                 :                :              * check the old-to-new mapping hash table.
                                783                 :                :              *
                                784                 :                :              * It'd be better if we somehow could avoid setting hint bits on
                                785                 :                :              * the old page. One reason to use VACUUM FULL are very bloated
                                786                 :                :              * tables - rewriting most of the old table during VACUUM FULL
                                787                 :                :              * doesn't exactly help...
                                788                 :                :              */
                                789                 :         496043 :             LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
                                790                 :                : 
                                791   [ +  +  +  +  :         496043 :             switch (HeapTupleSatisfiesVacuum(tuple, OldestXmin, buf))
                                              +  - ]
                                792                 :                :             {
                                793                 :          21322 :                 case HEAPTUPLE_DEAD:
                                794                 :                :                     /* Definitely dead */
                                795                 :          21322 :                     isdead = true;
                                796                 :          21322 :                     break;
                                797                 :          29282 :                 case HEAPTUPLE_RECENTLY_DEAD:
                                798                 :          29282 :                     *tups_recently_dead += 1;
                                799                 :                :                     pg_fallthrough;
                                800                 :         474577 :                 case HEAPTUPLE_LIVE:
                                801                 :                :                     /* Live or recently dead, must copy it */
                                802                 :         474577 :                     isdead = false;
                                803                 :         474577 :                     break;
                                804                 :            113 :                 case HEAPTUPLE_INSERT_IN_PROGRESS:
                                805                 :                : 
                                806                 :                :                     /*
                                807                 :                :                      * As long as we hold exclusive lock on the relation,
                                808                 :                :                      * normally the only way to see this is if it was inserted
                                809                 :                :                      * earlier in our own transaction.  However, it can happen
                                810                 :                :                      * in system catalogs, since we tend to release write lock
                                811                 :                :                      * before commit there. Give a warning if neither case
                                812                 :                :                      * applies; but in any case we had better copy it.
                                813                 :                :                      */
                                814         [ +  + ]:            113 :                     if (!is_system_catalog &&
                                815         [ -  + ]:             14 :                         !TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(tuple->t_data)))
  111 alvherre@kurilemu.de      816         [ #  # ]:UBC           0 :                         elog(WARNING, "concurrent insert in progress within table \"%s\"",
                                817                 :                :                              RelationGetRelationName(OldHeap));
                                818                 :                :                     /* treat as live */
  111 alvherre@kurilemu.de      819                 :CBC         113 :                     isdead = false;
                                820                 :            113 :                     break;
                                821                 :             31 :                 case HEAPTUPLE_DELETE_IN_PROGRESS:
                                822                 :                : 
                                823                 :                :                     /*
                                824                 :                :                      * Similar situation to INSERT_IN_PROGRESS case.
                                825                 :                :                      */
                                826         [ +  + ]:             31 :                     if (!is_system_catalog &&
                                827         [ -  + ]:             20 :                         !TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetUpdateXid(tuple->t_data)))
  111 alvherre@kurilemu.de      828         [ #  # ]:UBC           0 :                         elog(WARNING, "concurrent delete in progress within table \"%s\"",
                                829                 :                :                              RelationGetRelationName(OldHeap));
                                830                 :                :                     /* treat as recently dead */
  111 alvherre@kurilemu.de      831                 :CBC          31 :                     *tups_recently_dead += 1;
                                832                 :             31 :                     isdead = false;
                                833                 :             31 :                     break;
  111 alvherre@kurilemu.de      834                 :UBC           0 :                 default:
                                835         [ #  # ]:              0 :                     elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
                                836                 :                :                     isdead = false; /* keep compiler quiet */
                                837                 :                :                     break;
                                838                 :                :             }
                                839                 :                : 
  111 alvherre@kurilemu.de      840                 :CBC      496043 :             LockBuffer(buf, BUFFER_LOCK_UNLOCK);
                                841                 :                : 
                                842         [ +  + ]:         496043 :             if (isdead)
                                843                 :                :             {
 2677 andres@anarazel.de        844                 :          21322 :                 *tups_vacuumed += 1;
                                845                 :                :                 /* heap rewrite module still needs to see it... */
  111 alvherre@kurilemu.de      846         [ -  + ]:          21322 :                 if (rewrite_heap_dead_tuple(rwstate, tuple))
                                847                 :                :                 {
                                848                 :                :                     /* A previous recently-dead tuple is now known dead */
  111 alvherre@kurilemu.de      849                 :UBC           0 :                     *tups_vacuumed += 1;
                                850                 :              0 :                     *tups_recently_dead -= 1;
                                851                 :                :                 }
                                852                 :                : 
  111 alvherre@kurilemu.de      853                 :CBC       21322 :                 continue;
                                854                 :                :             }
                                855                 :                :         }
                                856                 :                : 
 2677 andres@anarazel.de        857                 :         474752 :         *num_tuples += 1;
                                858         [ +  + ]:         474752 :         if (tuplesort != NULL)
                                859                 :                :         {
                                860                 :         363322 :             tuplesort_putheaptuple(tuplesort, tuple);
                                861                 :                : 
                                862                 :                :             /*
                                863                 :                :              * In scan-and-sort mode, report increase in number of tuples
                                864                 :                :              * scanned
                                865                 :                :              */
  138 alvherre@kurilemu.de      866                 :         363322 :             pgstat_progress_update_param(PROGRESS_REPACK_HEAP_TUPLES_SCANNED,
 2677 andres@anarazel.de        867                 :         363322 :                                          *num_tuples);
                                868                 :                :         }
                                869                 :                :         else
                                870                 :                :         {
 2675                           871                 :         111430 :             const int   ct_index[] = {
                                872                 :                :                 PROGRESS_REPACK_HEAP_TUPLES_SCANNED,
                                873                 :                :                 PROGRESS_REPACK_HEAP_TUPLES_INSERTED
                                874                 :                :             };
                                875                 :                :             int64       ct_val[2];
                                876                 :                : 
  111 alvherre@kurilemu.de      877         [ +  + ]:         111430 :             if (!concurrent)
                                878                 :         111399 :                 reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
                                879                 :                :                                          values, isnull, rwstate);
                                880                 :                :             else
                                881                 :             31 :                 heap_insert_for_repack(tuple, OldHeap, NewHeap,
                                882                 :                :                                        values, isnull, bistate);
                                883                 :                : 
                                884                 :                :             /*
                                885                 :                :              * In indexscan mode and also VACUUM FULL, report increase in
                                886                 :                :              * number of tuples scanned and written
                                887                 :                :              */
 2677 andres@anarazel.de        888                 :         111430 :             ct_val[0] = *num_tuples;
                                889                 :         111430 :             ct_val[1] = *num_tuples;
                                890                 :         111430 :             pgstat_progress_update_multi_param(2, ct_index, ct_val);
                                891                 :                :         }
                                892                 :                :     }
                                893                 :                : 
                                894         [ +  + ]:            409 :     if (indexScan != NULL)
                                895                 :             62 :         index_endscan(indexScan);
                                896         [ +  + ]:            409 :     if (tableScan != NULL)
                                897                 :            347 :         table_endscan(tableScan);
                                898         [ +  - ]:            409 :     if (slot)
                                899                 :            409 :         ExecDropSingleTupleTableSlot(slot);
                                900                 :                : 
                                901                 :                :     /*
                                902                 :                :      * In scan-and-sort mode, complete the sort, then read out all live tuples
                                903                 :                :      * from the tuplestore and write them to the new relation.
                                904                 :                :      */
                                905         [ +  + ]:            409 :     if (tuplesort != NULL)
                                906                 :                :     {
 2675                           907                 :             85 :         double      n_tuples = 0;
                                908                 :                : 
                                909                 :                :         /* Report that we are now sorting tuples */
  138 alvherre@kurilemu.de      910                 :             85 :         pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
                                911                 :                :                                      PROGRESS_REPACK_PHASE_SORT_TUPLES);
                                912                 :                : 
 2677 andres@anarazel.de        913                 :             85 :         tuplesort_performsort(tuplesort);
                                914                 :                : 
                                915                 :                :         /* Report that we are now writing new heap */
  138 alvherre@kurilemu.de      916                 :             85 :         pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
                                917                 :                :                                      PROGRESS_REPACK_PHASE_WRITE_NEW_HEAP);
                                918                 :                : 
                                919                 :                :         for (;;)
 2677 andres@anarazel.de        920                 :         363322 :         {
                                921                 :                :             HeapTuple   tuple;
                                922                 :                : 
                                923         [ -  + ]:         363407 :             CHECK_FOR_INTERRUPTS();
                                924                 :                : 
                                925                 :         363407 :             tuple = tuplesort_getheaptuple(tuplesort, true);
                                926         [ +  + ]:         363407 :             if (tuple == NULL)
                                927                 :             85 :                 break;
                                928                 :                : 
                                929                 :         363322 :             n_tuples += 1;
  111 alvherre@kurilemu.de      930         [ +  - ]:         363322 :             if (!concurrent)
                                931                 :         363322 :                 reform_and_rewrite_tuple(tuple,
                                932                 :                :                                          OldHeap, NewHeap,
                                933                 :                :                                          values, isnull,
                                934                 :                :                                          rwstate);
                                935                 :                :             else
  111 alvherre@kurilemu.de      936                 :UBC           0 :                 heap_insert_for_repack(tuple, OldHeap, NewHeap,
                                937                 :                :                                        values, isnull, bistate);
                                938                 :                : 
                                939                 :                :             /* Report n_tuples */
  111 alvherre@kurilemu.de      940                 :CBC      363322 :             pgstat_progress_update_param(PROGRESS_REPACK_HEAP_TUPLES_INSERTED,
                                941                 :                :                                          n_tuples);
                                942                 :                :         }
                                943                 :                : 
 2677 andres@anarazel.de        944                 :             85 :         tuplesort_end(tuplesort);
                                945                 :                :     }
                                946                 :                : 
                                947                 :                :     /* Write out any remaining tuples, and fsync if needed */
  111 alvherre@kurilemu.de      948         [ +  + ]:            409 :     if (rwstate)
                                949                 :            402 :         end_heap_rewrite(rwstate);
                                950         [ +  + ]:            409 :     if (bistate)
                                951                 :              7 :         FreeBulkInsertState(bistate);
                                952                 :                : 
                                953                 :                :     /* Clean up */
 2677 andres@anarazel.de        954                 :            409 :     pfree(values);
                                955                 :            409 :     pfree(isnull);
                                956                 :            409 : }
                                957                 :                : 
                                958                 :                : /*
                                959                 :                :  * Prepare to analyze the next block in the read stream.  Returns false if
                                960                 :                :  * the stream is exhausted and true otherwise. The scan must have been started
                                961                 :                :  * with SO_TYPE_ANALYZE option.
                                962                 :                :  *
                                963                 :                :  * This routine holds a buffer pin and lock on the heap page.  They are held
                                964                 :                :  * until heapam_scan_analyze_next_tuple() returns false.  That is until all the
                                965                 :                :  * items of the heap page are analyzed.
                                966                 :                :  */
                                967                 :                : static bool
  839 tmunro@postgresql.or      968                 :         128058 : heapam_scan_analyze_next_block(TableScanDesc scan, ReadStream *stream)
                                969                 :                : {
 2675 andres@anarazel.de        970                 :         128058 :     HeapScanDesc hscan = (HeapScanDesc) scan;
                                971                 :                : 
                                972                 :                :     /*
                                973                 :                :      * We must maintain a pin on the target page's buffer to ensure that
                                974                 :                :      * concurrent activity - e.g. HOT pruning - doesn't delete tuples out from
                                975                 :                :      * under us.  It comes from the stream already pinned.   We also choose to
                                976                 :                :      * hold sharelock on the buffer throughout --- we could release and
                                977                 :                :      * re-acquire sharelock for each tuple, but since we aren't doing much
                                978                 :                :      * work per tuple, the extra lock traffic is probably better avoided.
                                979                 :                :      */
  839 tmunro@postgresql.or      980                 :         128058 :     hscan->rs_cbuf = read_stream_next_buffer(stream, NULL);
                                981         [ +  + ]:         128058 :     if (!BufferIsValid(hscan->rs_cbuf))
                                982                 :          11544 :         return false;
                                983                 :                : 
 2675 andres@anarazel.de        984                 :         116514 :     LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_SHARE);
                                985                 :                : 
  839 tmunro@postgresql.or      986                 :         116514 :     hscan->rs_cblock = BufferGetBlockNumber(hscan->rs_cbuf);
                                987                 :         116514 :     hscan->rs_cindex = FirstOffsetNumber;
                                988                 :         116514 :     return true;
                                989                 :                : }
                                990                 :                : 
                                991                 :                : static bool
  150 melanieplageman@gmai      992                 :        9613556 : heapam_scan_analyze_next_tuple(TableScanDesc scan,
                                993                 :                :                                double *liverows, double *deadrows,
                                994                 :                :                                TupleTableSlot *slot)
                                995                 :                : {
 2675 andres@anarazel.de        996                 :        9613556 :     HeapScanDesc hscan = (HeapScanDesc) scan;
                                997                 :                :     Page        targpage;
                                998                 :                :     OffsetNumber maxoffset;
                                999                 :                :     BufferHeapTupleTableSlot *hslot;
                               1000                 :                : 
                               1001         [ -  + ]:        9613556 :     Assert(TTS_IS_BUFFERTUPLE(slot));
                               1002                 :                : 
                               1003                 :        9613556 :     hslot = (BufferHeapTupleTableSlot *) slot;
                               1004                 :        9613556 :     targpage = BufferGetPage(hscan->rs_cbuf);
                               1005                 :        9613556 :     maxoffset = PageGetMaxOffsetNumber(targpage);
                               1006                 :                : 
                               1007                 :                :     /* Inner loop over all tuples on the selected page */
                               1008         [ +  + ]:       10554145 :     for (; hscan->rs_cindex <= maxoffset; hscan->rs_cindex++)
                               1009                 :                :     {
                               1010                 :                :         ItemId      itemid;
                               1011                 :       10437631 :         HeapTuple   targtuple = &hslot->base.tupdata;
                               1012                 :       10437631 :         bool        sample_it = false;
                               1013                 :                :         TransactionId dead_after;
                               1014                 :                : 
                               1015                 :       10437631 :         itemid = PageGetItemId(targpage, hscan->rs_cindex);
                               1016                 :                : 
                               1017                 :                :         /*
                               1018                 :                :          * We ignore unused and redirect line pointers.  DEAD line pointers
                               1019                 :                :          * should be counted as dead, because we need vacuum to run to get rid
                               1020                 :                :          * of them.  Note that this rule agrees with the way that
                               1021                 :                :          * heap_page_prune_and_freeze() counts things.
                               1022                 :                :          */
                               1023         [ +  + ]:       10437631 :         if (!ItemIdIsNormal(itemid))
                               1024                 :                :         {
                               1025         [ +  + ]:         435677 :             if (ItemIdIsDead(itemid))
                               1026                 :          14960 :                 *deadrows += 1;
                               1027                 :         435677 :             continue;
                               1028                 :                :         }
                               1029                 :                : 
                               1030                 :       10001954 :         ItemPointerSet(&targtuple->t_self, hscan->rs_cblock, hscan->rs_cindex);
                               1031                 :                : 
                               1032                 :       10001954 :         targtuple->t_tableOid = RelationGetRelid(scan->rs_rd);
                               1033                 :       10001954 :         targtuple->t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
                               1034                 :       10001954 :         targtuple->t_len = ItemIdGetLength(itemid);
                               1035                 :                : 
  150 melanieplageman@gmai     1036   [ +  +  +  +  :       10001954 :         switch (HeapTupleSatisfiesVacuumHorizon(targtuple,
                                                 - ]
                               1037                 :                :                                                 hscan->rs_cbuf,
                               1038                 :                :                                                 &dead_after))
                               1039                 :                :         {
 2675 andres@anarazel.de       1040                 :        8281430 :             case HEAPTUPLE_LIVE:
                               1041                 :        8281430 :                 sample_it = true;
                               1042                 :        8281430 :                 *liverows += 1;
                               1043                 :        8281430 :                 break;
                               1044                 :                : 
                               1045                 :         157404 :             case HEAPTUPLE_DEAD:
                               1046                 :                :             case HEAPTUPLE_RECENTLY_DEAD:
                               1047                 :                :                 /* Count dead and recently-dead rows */
                               1048                 :         157404 :                 *deadrows += 1;
                               1049                 :         157404 :                 break;
                               1050                 :                : 
                               1051                 :         572550 :             case HEAPTUPLE_INSERT_IN_PROGRESS:
                               1052                 :                : 
                               1053                 :                :                 /*
                               1054                 :                :                  * Insert-in-progress rows are not counted.  We assume that
                               1055                 :                :                  * when the inserting transaction commits or aborts, it will
                               1056                 :                :                  * send a stats message to increment the proper count.  This
                               1057                 :                :                  * works right only if that transaction ends after we finish
                               1058                 :                :                  * analyzing the table; if things happen in the other order,
                               1059                 :                :                  * its stats update will be overwritten by ours.  However, the
                               1060                 :                :                  * error will be large only if the other transaction runs long
                               1061                 :                :                  * enough to insert many tuples, so assuming it will finish
                               1062                 :                :                  * after us is the safer option.
                               1063                 :                :                  *
                               1064                 :                :                  * A special case is that the inserting transaction might be
                               1065                 :                :                  * our own.  In this case we should count and sample the row,
                               1066                 :                :                  * to accommodate users who load a table and analyze it in one
                               1067                 :                :                  * transaction.  (pgstat_report_analyze has to adjust the
                               1068                 :                :                  * numbers we report to the cumulative stats system to make
                               1069                 :                :                  * this come out right.)
                               1070                 :                :                  */
                               1071         [ +  + ]:         572550 :                 if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(targtuple->t_data)))
                               1072                 :                :                 {
                               1073                 :         226186 :                     sample_it = true;
                               1074                 :         226186 :                     *liverows += 1;
                               1075                 :                :                 }
                               1076                 :         572550 :                 break;
                               1077                 :                : 
                               1078                 :         990570 :             case HEAPTUPLE_DELETE_IN_PROGRESS:
                               1079                 :                : 
                               1080                 :                :                 /*
                               1081                 :                :                  * We count and sample delete-in-progress rows the same as
                               1082                 :                :                  * live ones, so that the stats counters come out right if the
                               1083                 :                :                  * deleting transaction commits after us, per the same
                               1084                 :                :                  * reasoning given above.
                               1085                 :                :                  *
                               1086                 :                :                  * If the delete was done by our own transaction, however, we
                               1087                 :                :                  * must count the row as dead to make pgstat_report_analyze's
                               1088                 :                :                  * stats adjustments come out right.  (Note: this works out
                               1089                 :                :                  * properly when the row was both inserted and deleted in our
                               1090                 :                :                  * xact.)
                               1091                 :                :                  *
                               1092                 :                :                  * The net effect of these choices is that we act as though an
                               1093                 :                :                  * IN_PROGRESS transaction hasn't happened yet, except if it
                               1094                 :                :                  * is our own transaction, which we assume has happened.
                               1095                 :                :                  *
                               1096                 :                :                  * This approach ensures that we behave sanely if we see both
                               1097                 :                :                  * the pre-image and post-image rows for a row being updated
                               1098                 :                :                  * by a concurrent transaction: we will sample the pre-image
                               1099                 :                :                  * but not the post-image.  We also get sane results if the
                               1100                 :                :                  * concurrent transaction never commits.
                               1101                 :                :                  */
                               1102         [ +  + ]:         990570 :                 if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetUpdateXid(targtuple->t_data)))
 2595                          1103                 :           1144 :                     *deadrows += 1;
                               1104                 :                :                 else
                               1105                 :                :                 {
 2675                          1106                 :         989426 :                     sample_it = true;
 2595                          1107                 :         989426 :                     *liverows += 1;
                               1108                 :                :                 }
 2675                          1109                 :         990570 :                 break;
                               1110                 :                : 
 2675 andres@anarazel.de       1111                 :UBC           0 :             default:
                               1112         [ #  # ]:              0 :                 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
                               1113                 :                :                 break;
                               1114                 :                :         }
                               1115                 :                : 
 2675 andres@anarazel.de       1116         [ +  + ]:CBC    10001954 :         if (sample_it)
                               1117                 :                :         {
                               1118                 :        9497042 :             ExecStoreBufferHeapTuple(targtuple, slot, hscan->rs_cbuf);
                               1119                 :        9497042 :             hscan->rs_cindex++;
                               1120                 :                : 
                               1121                 :                :             /* note that we leave the buffer locked here! */
                               1122                 :        9497042 :             return true;
                               1123                 :                :         }
                               1124                 :                :     }
                               1125                 :                : 
                               1126                 :                :     /* Now release the lock and pin on the page */
                               1127                 :         116514 :     UnlockReleaseBuffer(hscan->rs_cbuf);
                               1128                 :         116514 :     hscan->rs_cbuf = InvalidBuffer;
                               1129                 :                : 
                               1130                 :                :     /* also prevent old slot contents from having pin on page */
                               1131                 :         116514 :     ExecClearTuple(slot);
                               1132                 :                : 
                               1133                 :         116514 :     return false;
                               1134                 :                : }
                               1135                 :                : 
                               1136                 :                : static double
 2678                          1137                 :          36372 : heapam_index_build_range_scan(Relation heapRelation,
                               1138                 :                :                               Relation indexRelation,
                               1139                 :                :                               IndexInfo *indexInfo,
                               1140                 :                :                               bool allow_sync,
                               1141                 :                :                               bool anyvisible,
                               1142                 :                :                               bool progress,
                               1143                 :                :                               BlockNumber start_blockno,
                               1144                 :                :                               BlockNumber numblocks,
                               1145                 :                :                               IndexBuildCallback callback,
                               1146                 :                :                               void *callback_state,
                               1147                 :                :                               TableScanDesc scan)
                               1148                 :                : {
                               1149                 :                :     HeapScanDesc hscan;
                               1150                 :                :     bool        is_system_catalog;
                               1151                 :                :     bool        checking_uniqueness;
                               1152                 :                :     HeapTuple   heapTuple;
                               1153                 :                :     Datum       values[INDEX_MAX_KEYS];
                               1154                 :                :     bool        isnull[INDEX_MAX_KEYS];
                               1155                 :                :     double      reltuples;
                               1156                 :                :     ExprState  *predicate;
                               1157                 :                :     TupleTableSlot *slot;
                               1158                 :                :     EState     *estate;
                               1159                 :                :     ExprContext *econtext;
                               1160                 :                :     Snapshot    snapshot;
                               1161                 :          36372 :     bool        need_unregister_snapshot = false;
                               1162                 :                :     TransactionId OldestXmin;
 2622 tgl@sss.pgh.pa.us        1163                 :          36372 :     BlockNumber previous_blkno = InvalidBlockNumber;
 2678 andres@anarazel.de       1164                 :          36372 :     BlockNumber root_blkno = InvalidBlockNumber;
                               1165                 :                :     OffsetNumber root_offsets[MaxHeapTuplesPerPage];
                               1166                 :                : 
                               1167                 :                :     /*
                               1168                 :                :      * sanity checks
                               1169                 :                :      */
                               1170         [ -  + ]:          36372 :     Assert(OidIsValid(indexRelation->rd_rel->relam));
                               1171                 :                : 
                               1172                 :                :     /* Remember if it's a system catalog */
                               1173                 :          36372 :     is_system_catalog = IsSystemRelation(heapRelation);
                               1174                 :                : 
                               1175                 :                :     /* See whether we're verifying uniqueness/exclusion properties */
                               1176         [ +  + ]:          45935 :     checking_uniqueness = (indexInfo->ii_Unique ||
                               1177         [ +  + ]:           9563 :                            indexInfo->ii_ExclusionOps != NULL);
                               1178                 :                : 
                               1179                 :                :     /*
                               1180                 :                :      * "Any visible" mode is not compatible with uniqueness checks; make sure
                               1181                 :                :      * only one of those is requested.
                               1182                 :                :      */
                               1183   [ +  +  -  + ]:          36372 :     Assert(!(anyvisible && checking_uniqueness));
                               1184                 :                : 
                               1185                 :                :     /*
                               1186                 :                :      * Need an EState for evaluation of index expressions and partial-index
                               1187                 :                :      * predicates.  Also a slot to hold the current tuple.
                               1188                 :                :      */
                               1189                 :          36372 :     estate = CreateExecutorState();
                               1190         [ -  + ]:          36372 :     econtext = GetPerTupleExprContext(estate);
                               1191                 :          36372 :     slot = table_slot_create(heapRelation, NULL);
                               1192                 :                : 
                               1193                 :                :     /* Arrange for econtext's scan tuple to be the tuple under test */
                               1194                 :          36372 :     econtext->ecxt_scantuple = slot;
                               1195                 :                : 
                               1196                 :                :     /* Set up execution state for predicate, if any. */
                               1197                 :          36372 :     predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
                               1198                 :                : 
                               1199                 :                :     /*
                               1200                 :                :      * Prepare for scan of the base relation.  In a normal index build, we use
                               1201                 :                :      * SnapshotAny because we must retrieve all tuples and do our own time
                               1202                 :                :      * qual checks (because we have to index RECENTLY_DEAD tuples). In a
                               1203                 :                :      * concurrent build, or during bootstrap, we take a regular MVCC snapshot
                               1204                 :                :      * and index whatever's live according to that.
                               1205                 :                :      */
                               1206                 :          36372 :     OldestXmin = InvalidTransactionId;
                               1207                 :                : 
                               1208                 :                :     /* okay to ignore lazy VACUUMs here */
                               1209   [ +  +  +  + ]:          36372 :     if (!IsBootstrapProcessingMode() && !indexInfo->ii_Concurrent)
 2174                          1210                 :          26216 :         OldestXmin = GetOldestNonRemovableTransactionId(heapRelation);
                               1211                 :                : 
 2678                          1212         [ +  + ]:          36372 :     if (!scan)
                               1213                 :                :     {
                               1214                 :                :         /*
                               1215                 :                :          * Serial index build.
                               1216                 :                :          *
                               1217                 :                :          * Must begin our own heap scan in this case.  We may also need to
                               1218                 :                :          * register a snapshot whose lifetime is under our direct control.
                               1219                 :                :          */
                               1220         [ +  + ]:          36019 :         if (!TransactionIdIsValid(OldestXmin))
                               1221                 :                :         {
                               1222                 :          10074 :             snapshot = RegisterSnapshot(GetTransactionSnapshot());
                               1223                 :          10074 :             need_unregister_snapshot = true;
                               1224                 :                :         }
                               1225                 :                :         else
                               1226                 :          25945 :             snapshot = SnapshotAny;
                               1227                 :                : 
                               1228                 :          36019 :         scan = table_beginscan_strat(heapRelation,  /* relation */
                               1229                 :                :                                      snapshot,  /* snapshot */
                               1230                 :                :                                      0, /* number of keys */
                               1231                 :                :                                      NULL,  /* scan key */
                               1232                 :                :                                      true,  /* buffer access strategy OK */
                               1233                 :                :                                      allow_sync);   /* syncscan OK? */
                               1234                 :                :     }
                               1235                 :                :     else
                               1236                 :                :     {
                               1237                 :                :         /*
                               1238                 :                :          * Parallel index build.
                               1239                 :                :          *
                               1240                 :                :          * Parallel case never registers/unregisters own snapshot.  Snapshot
                               1241                 :                :          * is taken from parallel heap scan, and is SnapshotAny or an MVCC
                               1242                 :                :          * snapshot, based on same criteria as serial case.
                               1243                 :                :          */
                               1244         [ -  + ]:            353 :         Assert(!IsBootstrapProcessingMode());
                               1245         [ -  + ]:            353 :         Assert(allow_sync);
                               1246                 :            353 :         snapshot = scan->rs_snapshot;
                               1247                 :                :     }
                               1248                 :                : 
                               1249                 :          36372 :     hscan = (HeapScanDesc) scan;
                               1250                 :                : 
                               1251                 :                :     /*
                               1252                 :                :      * Must have called GetOldestNonRemovableTransactionId() if using
                               1253                 :                :      * SnapshotAny.  Shouldn't have for an MVCC snapshot. (It's especially
                               1254                 :                :      * worth checking this for parallel builds, since ambuild routines that
                               1255                 :                :      * support parallel builds must work these details out for themselves.)
                               1256                 :                :      */
 2174                          1257   [ +  +  -  + ]:          36372 :     Assert(snapshot == SnapshotAny || IsMVCCSnapshot(snapshot));
                               1258   [ +  +  -  + ]:          36372 :     Assert(snapshot == SnapshotAny ? TransactionIdIsValid(OldestXmin) :
                               1259                 :                :            !TransactionIdIsValid(OldestXmin));
                               1260   [ +  +  -  + ]:          36372 :     Assert(snapshot == SnapshotAny || !anyvisible);
                               1261                 :                : 
                               1262                 :                :     /* Publish number of blocks to scan */
 2672 alvherre@alvh.no-ip.     1263         [ +  + ]:          36372 :     if (progress)
                               1264                 :                :     {
                               1265                 :                :         BlockNumber nblocks;
                               1266                 :                : 
                               1267         [ +  + ]:          34658 :         if (hscan->rs_base.rs_parallel != NULL)
                               1268                 :                :         {
                               1269                 :                :             ParallelBlockTableScanDesc pbscan;
                               1270                 :                : 
                               1271                 :            137 :             pbscan = (ParallelBlockTableScanDesc) hscan->rs_base.rs_parallel;
                               1272                 :            137 :             nblocks = pbscan->phs_nblocks;
                               1273                 :                :         }
                               1274                 :                :         else
                               1275                 :          34521 :             nblocks = hscan->rs_nblocks;
                               1276                 :                : 
                               1277                 :          34658 :         pgstat_progress_update_param(PROGRESS_SCAN_BLOCKS_TOTAL,
                               1278                 :                :                                      nblocks);
                               1279                 :                :     }
                               1280                 :                : 
                               1281                 :                :     /* set our scan endpoints */
 2678 andres@anarazel.de       1282         [ +  + ]:          36372 :     if (!allow_sync)
                               1283                 :           1914 :         heap_setscanlimits(scan, start_blockno, numblocks);
                               1284                 :                :     else
                               1285                 :                :     {
                               1286                 :                :         /* syncscan can only be requested on whole relation */
                               1287         [ -  + ]:          34458 :         Assert(start_blockno == 0);
                               1288         [ -  + ]:          34458 :         Assert(numblocks == InvalidBlockNumber);
                               1289                 :                :     }
                               1290                 :                : 
                               1291                 :          36372 :     reltuples = 0;
                               1292                 :                : 
                               1293                 :                :     /*
                               1294                 :                :      * Scan all tuples in the base relation.
                               1295                 :                :      */
                               1296         [ +  + ]:       11393834 :     while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
                               1297                 :                :     {
                               1298                 :                :         bool        tupleIsAlive;
                               1299                 :                : 
                               1300         [ +  + ]:       11357482 :         CHECK_FOR_INTERRUPTS();
                               1301                 :                : 
                               1302                 :                :         /* Report scan progress, if asked to. */
 2672 alvherre@alvh.no-ip.     1303         [ +  + ]:       11357482 :         if (progress)
                               1304                 :                :         {
 2622 tgl@sss.pgh.pa.us        1305                 :        9237968 :             BlockNumber blocks_done = heapam_scan_get_blocks_done(hscan);
                               1306                 :                : 
 2672 alvherre@alvh.no-ip.     1307         [ +  + ]:        9237968 :             if (blocks_done != previous_blkno)
                               1308                 :                :             {
                               1309                 :         117444 :                 pgstat_progress_update_param(PROGRESS_SCAN_BLOCKS_DONE,
                               1310                 :                :                                              blocks_done);
                               1311                 :         117444 :                 previous_blkno = blocks_done;
                               1312                 :                :             }
                               1313                 :                :         }
                               1314                 :                : 
                               1315                 :                :         /*
                               1316                 :                :          * When dealing with a HOT-chain of updated tuples, we want to index
                               1317                 :                :          * the values of the live tuple (if any), but index it under the TID
                               1318                 :                :          * of the chain's root tuple.  This approach is necessary to preserve
                               1319                 :                :          * the HOT-chain structure in the heap. So we need to be able to find
                               1320                 :                :          * the root item offset for every tuple that's in a HOT-chain.  When
                               1321                 :                :          * first reaching a new page of the relation, call
                               1322                 :                :          * heap_get_root_tuples() to build a map of root item offsets on the
                               1323                 :                :          * page.
                               1324                 :                :          *
                               1325                 :                :          * It might look unsafe to use this information across buffer
                               1326                 :                :          * lock/unlock.  However, we hold ShareLock on the table so no
                               1327                 :                :          * ordinary insert/update/delete should occur; and we hold pin on the
                               1328                 :                :          * buffer continuously while visiting the page, so no pruning
                               1329                 :                :          * operation can occur either.
                               1330                 :                :          *
                               1331                 :                :          * In cases with only ShareUpdateExclusiveLock on the table, it's
                               1332                 :                :          * possible for some HOT tuples to appear that we didn't know about
                               1333                 :                :          * when we first read the page.  To handle that case, we re-obtain the
                               1334                 :                :          * list of root offsets when a HOT tuple points to a root item that we
                               1335                 :                :          * don't know about.
                               1336                 :                :          *
                               1337                 :                :          * Also, although our opinions about tuple liveness could change while
                               1338                 :                :          * we scan the page (due to concurrent transaction commits/aborts),
                               1339                 :                :          * the chain root locations won't, so this info doesn't need to be
                               1340                 :                :          * rebuilt after waiting for another transaction.
                               1341                 :                :          *
                               1342                 :                :          * Note the implied assumption that there is no more than one live
                               1343                 :                :          * tuple per HOT-chain --- else we could create more than one index
                               1344                 :                :          * entry pointing to the same root tuple.
                               1345                 :                :          */
 2678 andres@anarazel.de       1346         [ +  + ]:       11357482 :         if (hscan->rs_cblock != root_blkno)
                               1347                 :                :         {
                               1348                 :         136649 :             Page        page = BufferGetPage(hscan->rs_cbuf);
                               1349                 :                : 
                               1350                 :         136649 :             LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_SHARE);
                               1351                 :         136649 :             heap_get_root_tuples(page, root_offsets);
                               1352                 :         136649 :             LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                               1353                 :                : 
                               1354                 :         136649 :             root_blkno = hscan->rs_cblock;
                               1355                 :                :         }
                               1356                 :                : 
                               1357         [ +  + ]:       11357482 :         if (snapshot == SnapshotAny)
                               1358                 :                :         {
                               1359                 :                :             /* do our own time qual check */
                               1360                 :                :             bool        indexIt;
                               1361                 :                :             TransactionId xwait;
                               1362                 :                : 
                               1363                 :        8828035 :     recheck:
                               1364                 :                : 
                               1365                 :                :             /*
                               1366                 :                :              * We could possibly get away with not locking the buffer here,
                               1367                 :                :              * since caller should hold ShareLock on the relation, but let's
                               1368                 :                :              * be conservative about it.  (This remark is still correct even
                               1369                 :                :              * with HOT-pruning: our pin on the buffer prevents pruning.)
                               1370                 :                :              */
                               1371                 :        8828035 :             LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_SHARE);
                               1372                 :                : 
                               1373                 :                :             /*
                               1374                 :                :              * The criteria for counting a tuple as live in this block need to
                               1375                 :                :              * match what analyze.c's heapam_scan_analyze_next_tuple() does,
                               1376                 :                :              * otherwise CREATE INDEX and ANALYZE may produce wildly different
                               1377                 :                :              * reltuples values, e.g. when there are many recently-dead
                               1378                 :                :              * tuples.
                               1379                 :                :              */
                               1380   [ +  +  +  +  :        8828035 :             switch (HeapTupleSatisfiesVacuum(heapTuple, OldestXmin,
                                              +  - ]
                               1381                 :                :                                              hscan->rs_cbuf))
                               1382                 :                :             {
                               1383                 :           1481 :                 case HEAPTUPLE_DEAD:
                               1384                 :                :                     /* Definitely dead, we can ignore it */
                               1385                 :           1481 :                     indexIt = false;
                               1386                 :           1481 :                     tupleIsAlive = false;
                               1387                 :           1481 :                     break;
                               1388                 :        6785745 :                 case HEAPTUPLE_LIVE:
                               1389                 :                :                     /* Normal case, index and unique-check it */
                               1390                 :        6785745 :                     indexIt = true;
                               1391                 :        6785745 :                     tupleIsAlive = true;
                               1392                 :                :                     /* Count it as live, too */
                               1393                 :        6785745 :                     reltuples += 1;
                               1394                 :        6785745 :                     break;
                               1395                 :         154360 :                 case HEAPTUPLE_RECENTLY_DEAD:
                               1396                 :                : 
                               1397                 :                :                     /*
                               1398                 :                :                      * If tuple is recently deleted then we must index it
                               1399                 :                :                      * anyway to preserve MVCC semantics.  (Pre-existing
                               1400                 :                :                      * transactions could try to use the index after we finish
                               1401                 :                :                      * building it, and may need to see such tuples.)
                               1402                 :                :                      *
                               1403                 :                :                      * However, if it was HOT-updated then we must only index
                               1404                 :                :                      * the live tuple at the end of the HOT-chain.  Since this
                               1405                 :                :                      * breaks semantics for pre-existing snapshots, mark the
                               1406                 :                :                      * index as unusable for them.
                               1407                 :                :                      *
                               1408                 :                :                      * We don't count recently-dead tuples in reltuples, even
                               1409                 :                :                      * if we index them; see heapam_scan_analyze_next_tuple().
                               1410                 :                :                      */
                               1411         [ +  + ]:         154360 :                     if (HeapTupleIsHotUpdated(heapTuple))
                               1412                 :                :                     {
                               1413                 :            142 :                         indexIt = false;
                               1414                 :                :                         /* mark the index as unsafe for old snapshots */
                               1415                 :            142 :                         indexInfo->ii_BrokenHotChain = true;
                               1416                 :                :                     }
                               1417                 :                :                     else
                               1418                 :         154218 :                         indexIt = true;
                               1419                 :                :                     /* In any case, exclude the tuple from unique-checking */
                               1420                 :         154360 :                     tupleIsAlive = false;
                               1421                 :         154360 :                     break;
                               1422                 :        1886396 :                 case HEAPTUPLE_INSERT_IN_PROGRESS:
                               1423                 :                : 
                               1424                 :                :                     /*
                               1425                 :                :                      * In "anyvisible" mode, this tuple is visible and we
                               1426                 :                :                      * don't need any further checks.
                               1427                 :                :                      */
                               1428         [ +  + ]:        1886396 :                     if (anyvisible)
                               1429                 :                :                     {
                               1430                 :          30736 :                         indexIt = true;
                               1431                 :          30736 :                         tupleIsAlive = true;
                               1432                 :          30736 :                         reltuples += 1;
                               1433                 :          30736 :                         break;
                               1434                 :                :                     }
                               1435                 :                : 
                               1436                 :                :                     /*
                               1437                 :                :                      * Since caller should hold ShareLock or better, normally
                               1438                 :                :                      * the only way to see this is if it was inserted earlier
                               1439                 :                :                      * in our own transaction.  However, it can happen in
                               1440                 :                :                      * system catalogs, since we tend to release write lock
                               1441                 :                :                      * before commit there.  Give a warning if neither case
                               1442                 :                :                      * applies.
                               1443                 :                :                      */
                               1444                 :        1855660 :                     xwait = HeapTupleHeaderGetXmin(heapTuple->t_data);
                               1445         [ +  + ]:        1855660 :                     if (!TransactionIdIsCurrentTransactionId(xwait))
                               1446                 :                :                     {
                               1447         [ -  + ]:            102 :                         if (!is_system_catalog)
 2678 andres@anarazel.de       1448         [ #  # ]:UBC           0 :                             elog(WARNING, "concurrent insert in progress within table \"%s\"",
                               1449                 :                :                                  RelationGetRelationName(heapRelation));
                               1450                 :                : 
                               1451                 :                :                         /*
                               1452                 :                :                          * If we are performing uniqueness checks, indexing
                               1453                 :                :                          * such a tuple could lead to a bogus uniqueness
                               1454                 :                :                          * failure.  In that case we wait for the inserting
                               1455                 :                :                          * transaction to finish and check again.
                               1456                 :                :                          */
 2678 andres@anarazel.de       1457         [ -  + ]:CBC         102 :                         if (checking_uniqueness)
                               1458                 :                :                         {
                               1459                 :                :                             /*
                               1460                 :                :                              * Must drop the lock on the buffer before we wait
                               1461                 :                :                              */
 2678 andres@anarazel.de       1462                 :UBC           0 :                             LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                               1463                 :              0 :                             XactLockTableWait(xwait, heapRelation,
                               1464                 :              0 :                                               &heapTuple->t_self,
                               1465                 :                :                                               XLTW_InsertIndexUnique);
                               1466         [ #  # ]:              0 :                             CHECK_FOR_INTERRUPTS();
                               1467                 :              0 :                             goto recheck;
                               1468                 :                :                         }
                               1469                 :                :                     }
                               1470                 :                :                     else
                               1471                 :                :                     {
                               1472                 :                :                         /*
                               1473                 :                :                          * For consistency with
                               1474                 :                :                          * heapam_scan_analyze_next_tuple(), count
                               1475                 :                :                          * HEAPTUPLE_INSERT_IN_PROGRESS tuples as live only
                               1476                 :                :                          * when inserted by our own transaction.
                               1477                 :                :                          */
 2678 andres@anarazel.de       1478                 :CBC     1855558 :                         reltuples += 1;
                               1479                 :                :                     }
                               1480                 :                : 
                               1481                 :                :                     /*
                               1482                 :                :                      * We must index such tuples, since if the index build
                               1483                 :                :                      * commits then they're good.
                               1484                 :                :                      */
                               1485                 :        1855660 :                     indexIt = true;
                               1486                 :        1855660 :                     tupleIsAlive = true;
                               1487                 :        1855660 :                     break;
                               1488                 :             53 :                 case HEAPTUPLE_DELETE_IN_PROGRESS:
                               1489                 :                : 
                               1490                 :                :                     /*
                               1491                 :                :                      * As with INSERT_IN_PROGRESS case, this is unexpected
                               1492                 :                :                      * unless it's our own deletion or a system catalog; but
                               1493                 :                :                      * in anyvisible mode, this tuple is visible.
                               1494                 :                :                      */
                               1495         [ -  + ]:             53 :                     if (anyvisible)
                               1496                 :                :                     {
 2678 andres@anarazel.de       1497                 :UBC           0 :                         indexIt = true;
                               1498                 :              0 :                         tupleIsAlive = false;
                               1499                 :              0 :                         reltuples += 1;
                               1500                 :              0 :                         break;
                               1501                 :                :                     }
                               1502                 :                : 
 2678 andres@anarazel.de       1503                 :CBC          53 :                     xwait = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
                               1504         [ +  + ]:             53 :                     if (!TransactionIdIsCurrentTransactionId(xwait))
                               1505                 :                :                     {
                               1506         [ -  + ]:              9 :                         if (!is_system_catalog)
 2678 andres@anarazel.de       1507         [ #  # ]:UBC           0 :                             elog(WARNING, "concurrent delete in progress within table \"%s\"",
                               1508                 :                :                                  RelationGetRelationName(heapRelation));
                               1509                 :                : 
                               1510                 :                :                         /*
                               1511                 :                :                          * If we are performing uniqueness checks, assuming
                               1512                 :                :                          * the tuple is dead could lead to missing a
                               1513                 :                :                          * uniqueness violation.  In that case we wait for the
                               1514                 :                :                          * deleting transaction to finish and check again.
                               1515                 :                :                          *
                               1516                 :                :                          * Also, if it's a HOT-updated tuple, we should not
                               1517                 :                :                          * index it but rather the live tuple at the end of
                               1518                 :                :                          * the HOT-chain.  However, the deleting transaction
                               1519                 :                :                          * could abort, possibly leaving this tuple as live
                               1520                 :                :                          * after all, in which case it has to be indexed. The
                               1521                 :                :                          * only way to know what to do is to wait for the
                               1522                 :                :                          * deleting transaction to finish and check again.
                               1523                 :                :                          */
 2678 andres@anarazel.de       1524   [ +  -  -  + ]:CBC          18 :                         if (checking_uniqueness ||
                               1525                 :              9 :                             HeapTupleIsHotUpdated(heapTuple))
                               1526                 :                :                         {
                               1527                 :                :                             /*
                               1528                 :                :                              * Must drop the lock on the buffer before we wait
                               1529                 :                :                              */
 2678 andres@anarazel.de       1530                 :UBC           0 :                             LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                               1531                 :              0 :                             XactLockTableWait(xwait, heapRelation,
                               1532                 :              0 :                                               &heapTuple->t_self,
                               1533                 :                :                                               XLTW_InsertIndexUnique);
                               1534         [ #  # ]:              0 :                             CHECK_FOR_INTERRUPTS();
                               1535                 :              0 :                             goto recheck;
                               1536                 :                :                         }
                               1537                 :                : 
                               1538                 :                :                         /*
                               1539                 :                :                          * Otherwise index it but don't check for uniqueness,
                               1540                 :                :                          * the same as a RECENTLY_DEAD tuple.
                               1541                 :                :                          */
 2678 andres@anarazel.de       1542                 :CBC           9 :                         indexIt = true;
                               1543                 :                : 
                               1544                 :                :                         /*
                               1545                 :                :                          * Count HEAPTUPLE_DELETE_IN_PROGRESS tuples as live,
                               1546                 :                :                          * if they were not deleted by the current
                               1547                 :                :                          * transaction.  That's what
                               1548                 :                :                          * heapam_scan_analyze_next_tuple() does, and we want
                               1549                 :                :                          * the behavior to be consistent.
                               1550                 :                :                          */
                               1551                 :              9 :                         reltuples += 1;
                               1552                 :                :                     }
                               1553         [ -  + ]:             44 :                     else if (HeapTupleIsHotUpdated(heapTuple))
                               1554                 :                :                     {
                               1555                 :                :                         /*
                               1556                 :                :                          * It's a HOT-updated tuple deleted by our own xact.
                               1557                 :                :                          * We can assume the deletion will commit (else the
                               1558                 :                :                          * index contents don't matter), so treat the same as
                               1559                 :                :                          * RECENTLY_DEAD HOT-updated tuples.
                               1560                 :                :                          */
 2678 andres@anarazel.de       1561                 :UBC           0 :                         indexIt = false;
                               1562                 :                :                         /* mark the index as unsafe for old snapshots */
                               1563                 :              0 :                         indexInfo->ii_BrokenHotChain = true;
                               1564                 :                :                     }
                               1565                 :                :                     else
                               1566                 :                :                     {
                               1567                 :                :                         /*
                               1568                 :                :                          * It's a regular tuple deleted by our own xact. Index
                               1569                 :                :                          * it, but don't check for uniqueness nor count in
                               1570                 :                :                          * reltuples, the same as a RECENTLY_DEAD tuple.
                               1571                 :                :                          */
 2678 andres@anarazel.de       1572                 :CBC          44 :                         indexIt = true;
                               1573                 :                :                     }
                               1574                 :                :                     /* In any case, exclude the tuple from unique-checking */
                               1575                 :             53 :                     tupleIsAlive = false;
                               1576                 :             53 :                     break;
 2678 andres@anarazel.de       1577                 :UBC           0 :                 default:
                               1578         [ #  # ]:              0 :                     elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
                               1579                 :                :                     indexIt = tupleIsAlive = false; /* keep compiler quiet */
                               1580                 :                :                     break;
                               1581                 :                :             }
                               1582                 :                : 
 2678 andres@anarazel.de       1583                 :CBC     8828035 :             LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                               1584                 :                : 
                               1585         [ +  + ]:        8828035 :             if (!indexIt)
                               1586                 :           1623 :                 continue;
                               1587                 :                :         }
                               1588                 :                :         else
                               1589                 :                :         {
                               1590                 :                :             /* heap_getnext did the time qual check */
                               1591                 :        2529447 :             tupleIsAlive = true;
                               1592                 :        2529447 :             reltuples += 1;
                               1593                 :                :         }
                               1594                 :                : 
                               1595                 :       11355859 :         MemoryContextReset(econtext->ecxt_per_tuple_memory);
                               1596                 :                : 
                               1597                 :                :         /* Set up for predicate or expression evaluation */
                               1598                 :       11355859 :         ExecStoreBufferHeapTuple(heapTuple, slot, hscan->rs_cbuf);
                               1599                 :                : 
                               1600                 :                :         /*
                               1601                 :                :          * In a partial index, discard tuples that don't satisfy the
                               1602                 :                :          * predicate.
                               1603                 :                :          */
                               1604         [ +  + ]:       11355859 :         if (predicate != NULL)
                               1605                 :                :         {
                               1606         [ +  + ]:         131216 :             if (!ExecQual(predicate, econtext))
                               1607                 :          72189 :                 continue;
                               1608                 :                :         }
                               1609                 :                : 
                               1610                 :                :         /*
                               1611                 :                :          * For the current heap tuple, extract all the attributes we use in
                               1612                 :                :          * this index, and note which are null.  This also performs evaluation
                               1613                 :                :          * of any expressions needed.
                               1614                 :                :          */
                               1615                 :       11283670 :         FormIndexDatum(indexInfo,
                               1616                 :                :                        slot,
                               1617                 :                :                        estate,
                               1618                 :                :                        values,
                               1619                 :                :                        isnull);
                               1620                 :                : 
                               1621                 :                :         /*
                               1622                 :                :          * You'd think we should go ahead and build the index tuple here, but
                               1623                 :                :          * some index AMs want to do further processing on the data first.  So
                               1624                 :                :          * pass the values[] and isnull[] arrays, instead.
                               1625                 :                :          */
                               1626                 :                : 
                               1627         [ +  + ]:       11283650 :         if (HeapTupleIsHeapOnly(heapTuple))
                               1628                 :                :         {
                               1629                 :                :             /*
                               1630                 :                :              * For a heap-only tuple, pretend its TID is that of the root. See
                               1631                 :                :              * src/backend/access/heap/README.HOT for discussion.
                               1632                 :                :              */
                               1633                 :                :             ItemPointerData tid;
                               1634                 :                :             OffsetNumber offnum;
                               1635                 :                : 
                               1636                 :           4084 :             offnum = ItemPointerGetOffsetNumber(&heapTuple->t_self);
                               1637                 :                : 
                               1638                 :                :             /*
                               1639                 :                :              * If a HOT tuple points to a root that we don't know about,
                               1640                 :                :              * obtain root items afresh.  If that still fails, report it as
                               1641                 :                :              * corruption.
                               1642                 :                :              */
 2173 alvherre@alvh.no-ip.     1643         [ -  + ]:           4084 :             if (root_offsets[offnum - 1] == InvalidOffsetNumber)
                               1644                 :                :             {
 1901 tgl@sss.pgh.pa.us        1645                 :UBC           0 :                 Page        page = BufferGetPage(hscan->rs_cbuf);
                               1646                 :                : 
 2173 alvherre@alvh.no-ip.     1647                 :              0 :                 LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_SHARE);
                               1648                 :              0 :                 heap_get_root_tuples(page, root_offsets);
                               1649                 :              0 :                 LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                               1650                 :                :             }
                               1651                 :                : 
 2678 andres@anarazel.de       1652   [ +  -  +  -  :CBC        4084 :             if (!OffsetNumberIsValid(root_offsets[offnum - 1]))
                                              -  + ]
 2678 andres@anarazel.de       1653         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               1654                 :                :                         (errcode(ERRCODE_DATA_CORRUPTED),
                               1655                 :                :                          errmsg_internal("failed to find parent tuple for heap-only tuple at (%u,%u) in table \"%s\"",
                               1656                 :                :                                          ItemPointerGetBlockNumber(&heapTuple->t_self),
                               1657                 :                :                                          offnum,
                               1658                 :                :                                          RelationGetRelationName(heapRelation))));
                               1659                 :                : 
 2452 andres@anarazel.de       1660                 :CBC        4084 :             ItemPointerSet(&tid, ItemPointerGetBlockNumber(&heapTuple->t_self),
                               1661                 :           4084 :                            root_offsets[offnum - 1]);
                               1662                 :                : 
                               1663                 :                :             /* Call the AM's callback routine to process the tuple */
                               1664                 :           4084 :             callback(indexRelation, &tid, values, isnull, tupleIsAlive,
                               1665                 :                :                      callback_state);
                               1666                 :                :         }
                               1667                 :                :         else
                               1668                 :                :         {
                               1669                 :                :             /* Call the AM's callback routine to process the tuple */
                               1670                 :       11279566 :             callback(indexRelation, &heapTuple->t_self, values, isnull,
                               1671                 :                :                      tupleIsAlive, callback_state);
                               1672                 :                :         }
                               1673                 :                :     }
                               1674                 :                : 
                               1675                 :                :     /* Report scan progress one last time. */
 2672 alvherre@alvh.no-ip.     1676         [ +  + ]:          36352 :     if (progress)
                               1677                 :                :     {
                               1678                 :                :         BlockNumber blks_done;
                               1679                 :                : 
                               1680         [ +  + ]:          34638 :         if (hscan->rs_base.rs_parallel != NULL)
                               1681                 :                :         {
                               1682                 :                :             ParallelBlockTableScanDesc pbscan;
                               1683                 :                : 
                               1684                 :            137 :             pbscan = (ParallelBlockTableScanDesc) hscan->rs_base.rs_parallel;
                               1685                 :            137 :             blks_done = pbscan->phs_nblocks;
                               1686                 :                :         }
                               1687                 :                :         else
                               1688                 :          34501 :             blks_done = hscan->rs_nblocks;
                               1689                 :                : 
                               1690                 :          34638 :         pgstat_progress_update_param(PROGRESS_SCAN_BLOCKS_DONE,
                               1691                 :                :                                      blks_done);
                               1692                 :                :     }
                               1693                 :                : 
 2678 andres@anarazel.de       1694                 :          36352 :     table_endscan(scan);
                               1695                 :                : 
                               1696                 :                :     /* we can now forget our snapshot, if set and registered by us */
                               1697         [ +  + ]:          36352 :     if (need_unregister_snapshot)
                               1698                 :          10058 :         UnregisterSnapshot(snapshot);
                               1699                 :                : 
                               1700                 :          36352 :     ExecDropSingleTupleTableSlot(slot);
                               1701                 :                : 
                               1702                 :          36352 :     FreeExecutorState(estate);
                               1703                 :                : 
                               1704                 :                :     /* These may have been pointing to the now-gone estate */
                               1705                 :          36352 :     indexInfo->ii_ExpressionsState = NIL;
                               1706                 :          36352 :     indexInfo->ii_PredicateState = NULL;
                               1707                 :                : 
                               1708                 :          36352 :     return reltuples;
                               1709                 :                : }
                               1710                 :                : 
                               1711                 :                : static void
                               1712                 :            418 : heapam_index_validate_scan(Relation heapRelation,
                               1713                 :                :                            Relation indexRelation,
                               1714                 :                :                            IndexInfo *indexInfo,
                               1715                 :                :                            Snapshot snapshot,
                               1716                 :                :                            ValidateIndexState *state)
                               1717                 :                : {
                               1718                 :                :     TableScanDesc scan;
                               1719                 :                :     HeapScanDesc hscan;
                               1720                 :                :     HeapTuple   heapTuple;
                               1721                 :                :     Datum       values[INDEX_MAX_KEYS];
                               1722                 :                :     bool        isnull[INDEX_MAX_KEYS];
                               1723                 :                :     ExprState  *predicate;
                               1724                 :                :     TupleTableSlot *slot;
                               1725                 :                :     EState     *estate;
                               1726                 :                :     ExprContext *econtext;
                               1727                 :            418 :     BlockNumber root_blkno = InvalidBlockNumber;
                               1728                 :                :     OffsetNumber root_offsets[MaxHeapTuplesPerPage];
                               1729                 :                :     bool        in_index[MaxHeapTuplesPerPage];
 2622 tgl@sss.pgh.pa.us        1730                 :            418 :     BlockNumber previous_blkno = InvalidBlockNumber;
                               1731                 :                : 
                               1732                 :                :     /* state variables for the merge */
 2678 andres@anarazel.de       1733                 :            418 :     ItemPointer indexcursor = NULL;
                               1734                 :                :     ItemPointerData decoded;
                               1735                 :            418 :     bool        tuplesort_empty = false;
                               1736                 :                : 
                               1737                 :                :     /*
                               1738                 :                :      * sanity checks
                               1739                 :                :      */
                               1740         [ -  + ]:            418 :     Assert(OidIsValid(indexRelation->rd_rel->relam));
                               1741                 :                : 
                               1742                 :                :     /*
                               1743                 :                :      * Need an EState for evaluation of index expressions and partial-index
                               1744                 :                :      * predicates.  Also a slot to hold the current tuple.
                               1745                 :                :      */
                               1746                 :            418 :     estate = CreateExecutorState();
                               1747         [ -  + ]:            418 :     econtext = GetPerTupleExprContext(estate);
                               1748                 :            418 :     slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRelation),
                               1749                 :                :                                     &TTSOpsHeapTuple);
                               1750                 :                : 
                               1751                 :                :     /* Arrange for econtext's scan tuple to be the tuple under test */
                               1752                 :            418 :     econtext->ecxt_scantuple = slot;
                               1753                 :                : 
                               1754                 :                :     /* Set up execution state for predicate, if any. */
                               1755                 :            418 :     predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
                               1756                 :                : 
                               1757                 :                :     /*
                               1758                 :                :      * Prepare for scan of the base relation.  We need just those tuples
                               1759                 :                :      * satisfying the passed-in reference snapshot.  We must disable syncscan
                               1760                 :                :      * here, because it's critical that we read from block zero forward to
                               1761                 :                :      * match the sorted TIDs.
                               1762                 :                :      */
                               1763                 :            418 :     scan = table_beginscan_strat(heapRelation,  /* relation */
                               1764                 :                :                                  snapshot,  /* snapshot */
                               1765                 :                :                                  0, /* number of keys */
                               1766                 :                :                                  NULL,  /* scan key */
                               1767                 :                :                                  true,  /* buffer access strategy OK */
                               1768                 :                :                                  false);    /* syncscan not OK */
                               1769                 :            418 :     hscan = (HeapScanDesc) scan;
                               1770                 :                : 
 2672 alvherre@alvh.no-ip.     1771                 :            418 :     pgstat_progress_update_param(PROGRESS_SCAN_BLOCKS_TOTAL,
                               1772                 :            418 :                                  hscan->rs_nblocks);
                               1773                 :                : 
                               1774                 :                :     /*
                               1775                 :                :      * Scan all tuples matching the snapshot.
                               1776                 :                :      */
 2678 andres@anarazel.de       1777         [ +  + ]:         126367 :     while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
                               1778                 :                :     {
                               1779                 :         125949 :         ItemPointer heapcursor = &heapTuple->t_self;
                               1780                 :                :         ItemPointerData rootTuple;
                               1781                 :                :         OffsetNumber root_offnum;
                               1782                 :                : 
                               1783         [ -  + ]:         125949 :         CHECK_FOR_INTERRUPTS();
                               1784                 :                : 
                               1785                 :         125949 :         state->htups += 1;
                               1786                 :                : 
 2672 alvherre@alvh.no-ip.     1787         [ +  + ]:         125949 :         if ((previous_blkno == InvalidBlockNumber) ||
                               1788         [ +  + ]:         125719 :             (hscan->rs_cblock != previous_blkno))
                               1789                 :                :         {
                               1790                 :           2350 :             pgstat_progress_update_param(PROGRESS_SCAN_BLOCKS_DONE,
                               1791                 :           2350 :                                          hscan->rs_cblock);
                               1792                 :           2350 :             previous_blkno = hscan->rs_cblock;
                               1793                 :                :         }
                               1794                 :                : 
                               1795                 :                :         /*
                               1796                 :                :          * As commented in table_index_build_scan, we should index heap-only
                               1797                 :                :          * tuples under the TIDs of their root tuples; so when we advance onto
                               1798                 :                :          * a new heap page, build a map of root item offsets on the page.
                               1799                 :                :          *
                               1800                 :                :          * This complicates merging against the tuplesort output: we will
                               1801                 :                :          * visit the live tuples in order by their offsets, but the root
                               1802                 :                :          * offsets that we need to compare against the index contents might be
                               1803                 :                :          * ordered differently.  So we might have to "look back" within the
                               1804                 :                :          * tuplesort output, but only within the current page.  We handle that
                               1805                 :                :          * by keeping a bool array in_index[] showing all the
                               1806                 :                :          * already-passed-over tuplesort output TIDs of the current page. We
                               1807                 :                :          * clear that array here, when advancing onto a new heap page.
                               1808                 :                :          */
 2678 andres@anarazel.de       1809         [ +  + ]:         125949 :         if (hscan->rs_cblock != root_blkno)
                               1810                 :                :         {
                               1811                 :           2350 :             Page        page = BufferGetPage(hscan->rs_cbuf);
                               1812                 :                : 
                               1813                 :           2350 :             LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_SHARE);
                               1814                 :           2350 :             heap_get_root_tuples(page, root_offsets);
                               1815                 :           2350 :             LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                               1816                 :                : 
                               1817                 :           2350 :             memset(in_index, 0, sizeof(in_index));
                               1818                 :                : 
                               1819                 :           2350 :             root_blkno = hscan->rs_cblock;
                               1820                 :                :         }
                               1821                 :                : 
                               1822                 :                :         /* Convert actual tuple TID to root TID */
                               1823                 :         125949 :         rootTuple = *heapcursor;
                               1824                 :         125949 :         root_offnum = ItemPointerGetOffsetNumber(heapcursor);
                               1825                 :                : 
                               1826         [ +  + ]:         125949 :         if (HeapTupleIsHeapOnly(heapTuple))
                               1827                 :                :         {
                               1828                 :             10 :             root_offnum = root_offsets[root_offnum - 1];
                               1829   [ +  -  +  -  :             10 :             if (!OffsetNumberIsValid(root_offnum))
                                              -  + ]
 2678 andres@anarazel.de       1830         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               1831                 :                :                         (errcode(ERRCODE_DATA_CORRUPTED),
                               1832                 :                :                          errmsg_internal("failed to find parent tuple for heap-only tuple at (%u,%u) in table \"%s\"",
                               1833                 :                :                                          ItemPointerGetBlockNumber(heapcursor),
                               1834                 :                :                                          ItemPointerGetOffsetNumber(heapcursor),
                               1835                 :                :                                          RelationGetRelationName(heapRelation))));
 2678 andres@anarazel.de       1836                 :CBC          10 :             ItemPointerSetOffsetNumber(&rootTuple, root_offnum);
                               1837                 :                :         }
                               1838                 :                : 
                               1839                 :                :         /*
                               1840                 :                :          * "merge" by skipping through the index tuples until we find or pass
                               1841                 :                :          * the current root tuple.
                               1842                 :                :          */
                               1843   [ +  +  +  + ]:         287249 :         while (!tuplesort_empty &&
                               1844         [ +  + ]:         286965 :                (!indexcursor ||
                               1845                 :         286965 :                 ItemPointerCompare(indexcursor, &rootTuple) < 0))
                               1846                 :                :         {
                               1847                 :                :             Datum       ts_val;
                               1848                 :                :             bool        ts_isnull;
                               1849                 :                : 
                               1850         [ +  + ]:         161300 :             if (indexcursor)
                               1851                 :                :             {
                               1852                 :                :                 /*
                               1853                 :                :                  * Remember index items seen earlier on the current heap page
                               1854                 :                :                  */
                               1855         [ +  + ]:         161070 :                 if (ItemPointerGetBlockNumber(indexcursor) == root_blkno)
                               1856                 :         158192 :                     in_index[ItemPointerGetOffsetNumber(indexcursor) - 1] = true;
                               1857                 :                :             }
                               1858                 :                : 
                               1859                 :         161300 :             tuplesort_empty = !tuplesort_getdatum(state->tuplesort, true,
                               1860                 :                :                                                   false, &ts_val, &ts_isnull,
 1367 drowley@postgresql.o     1861                 :         161300 :                                                   NULL);
 2678 andres@anarazel.de       1862   [ +  +  -  + ]:         161300 :             Assert(tuplesort_empty || !ts_isnull);
                               1863         [ +  + ]:         161300 :             if (!tuplesort_empty)
                               1864                 :                :             {
                               1865                 :         161277 :                 itemptr_decode(&decoded, DatumGetInt64(ts_val));
                               1866                 :         161277 :                 indexcursor = &decoded;
                               1867                 :                :             }
                               1868                 :                :             else
                               1869                 :                :             {
                               1870                 :                :                 /* Be tidy */
                               1871                 :             23 :                 indexcursor = NULL;
                               1872                 :                :             }
                               1873                 :                :         }
                               1874                 :                : 
                               1875                 :                :         /*
                               1876                 :                :          * If the tuplesort has overshot *and* we didn't see a match earlier,
                               1877                 :                :          * then this tuple is missing from the index, so insert it.
                               1878                 :                :          */
                               1879   [ +  +  +  + ]:         251844 :         if ((tuplesort_empty ||
                               1880                 :         125895 :              ItemPointerCompare(indexcursor, &rootTuple) > 0) &&
                               1881         [ +  + ]:            112 :             !in_index[root_offnum - 1])
                               1882                 :                :         {
                               1883                 :            106 :             MemoryContextReset(econtext->ecxt_per_tuple_memory);
                               1884                 :                : 
                               1885                 :                :             /* Set up for predicate or expression evaluation */
                               1886                 :            106 :             ExecStoreHeapTuple(heapTuple, slot, false);
                               1887                 :                : 
                               1888                 :                :             /*
                               1889                 :                :              * In a partial index, discard tuples that don't satisfy the
                               1890                 :                :              * predicate.
                               1891                 :                :              */
                               1892         [ +  + ]:            106 :             if (predicate != NULL)
                               1893                 :                :             {
                               1894         [ +  - ]:             32 :                 if (!ExecQual(predicate, econtext))
                               1895                 :             32 :                     continue;
                               1896                 :                :             }
                               1897                 :                : 
                               1898                 :                :             /*
                               1899                 :                :              * For the current heap tuple, extract all the attributes we use
                               1900                 :                :              * in this index, and note which are null.  This also performs
                               1901                 :                :              * evaluation of any expressions needed.
                               1902                 :                :              */
                               1903                 :             74 :             FormIndexDatum(indexInfo,
                               1904                 :                :                            slot,
                               1905                 :                :                            estate,
                               1906                 :                :                            values,
                               1907                 :                :                            isnull);
                               1908                 :                : 
                               1909                 :                :             /*
                               1910                 :                :              * You'd think we should go ahead and build the index tuple here,
                               1911                 :                :              * but some index AMs want to do further processing on the data
                               1912                 :                :              * first. So pass the values[] and isnull[] arrays, instead.
                               1913                 :                :              */
                               1914                 :                : 
                               1915                 :                :             /*
                               1916                 :                :              * If the tuple is already committed dead, you might think we
                               1917                 :                :              * could suppress uniqueness checking, but this is no longer true
                               1918                 :                :              * in the presence of HOT, because the insert is actually a proxy
                               1919                 :                :              * for a uniqueness check on the whole HOT-chain.  That is, the
                               1920                 :                :              * tuple we have here could be dead because it was already
                               1921                 :                :              * HOT-updated, and if so the updating transaction will not have
                               1922                 :                :              * thought it should insert index entries.  The index AM will
                               1923                 :                :              * check the whole HOT-chain and correctly detect a conflict if
                               1924                 :                :              * there is one.
                               1925                 :                :              */
                               1926                 :                : 
                               1927                 :             74 :             index_insert(indexRelation,
                               1928                 :                :                          values,
                               1929                 :                :                          isnull,
                               1930                 :                :                          &rootTuple,
                               1931                 :                :                          heapRelation,
                               1932                 :             74 :                          indexInfo->ii_Unique ?
                               1933                 :                :                          UNIQUE_CHECK_YES : UNIQUE_CHECK_NO,
                               1934                 :                :                          false,
                               1935                 :                :                          indexInfo);
                               1936                 :                : 
                               1937                 :             74 :             state->tups_inserted += 1;
                               1938                 :                :         }
                               1939                 :                :     }
                               1940                 :                : 
                               1941                 :            418 :     table_endscan(scan);
                               1942                 :                : 
                               1943                 :            418 :     ExecDropSingleTupleTableSlot(slot);
                               1944                 :                : 
                               1945                 :            418 :     FreeExecutorState(estate);
                               1946                 :                : 
                               1947                 :                :     /* These may have been pointing to the now-gone estate */
                               1948                 :            418 :     indexInfo->ii_ExpressionsState = NIL;
                               1949                 :            418 :     indexInfo->ii_PredicateState = NULL;
                               1950                 :            418 : }
                               1951                 :                : 
                               1952                 :                : /*
                               1953                 :                :  * Return the number of blocks that have been read by this scan since
                               1954                 :                :  * starting.  This is meant for progress reporting rather than be fully
                               1955                 :                :  * accurate: in a parallel scan, workers can be concurrently reading blocks
                               1956                 :                :  * further ahead than what we report.
                               1957                 :                :  */
                               1958                 :                : static BlockNumber
 2672 alvherre@alvh.no-ip.     1959                 :        9237968 : heapam_scan_get_blocks_done(HeapScanDesc hscan)
                               1960                 :                : {
                               1961                 :        9237968 :     ParallelBlockTableScanDesc bpscan = NULL;
                               1962                 :                :     BlockNumber startblock;
                               1963                 :                :     BlockNumber blocks_done;
                               1964                 :                : 
                               1965         [ +  + ]:        9237968 :     if (hscan->rs_base.rs_parallel != NULL)
                               1966                 :                :     {
                               1967                 :        1128435 :         bpscan = (ParallelBlockTableScanDesc) hscan->rs_base.rs_parallel;
                               1968                 :        1128435 :         startblock = bpscan->phs_startblock;
                               1969                 :                :     }
                               1970                 :                :     else
                               1971                 :        8109533 :         startblock = hscan->rs_startblock;
                               1972                 :                : 
                               1973                 :                :     /*
                               1974                 :                :      * Might have wrapped around the end of the relation, if startblock was
                               1975                 :                :      * not zero.
                               1976                 :                :      */
                               1977         [ +  + ]:        9237968 :     if (hscan->rs_cblock > startblock)
                               1978                 :        8903780 :         blocks_done = hscan->rs_cblock - startblock;
                               1979                 :                :     else
                               1980                 :                :     {
                               1981                 :                :         BlockNumber nblocks;
                               1982                 :                : 
                               1983         [ +  + ]:         334188 :         nblocks = bpscan != NULL ? bpscan->phs_nblocks : hscan->rs_nblocks;
                               1984                 :         334188 :         blocks_done = nblocks - startblock +
                               1985                 :         334188 :             hscan->rs_cblock;
                               1986                 :                :     }
                               1987                 :                : 
                               1988                 :        9237968 :     return blocks_done;
                               1989                 :                : }
                               1990                 :                : 
                               1991                 :                : 
                               1992                 :                : /* ------------------------------------------------------------------------
                               1993                 :                :  * Miscellaneous callbacks for the heap AM
                               1994                 :                :  * ------------------------------------------------------------------------
                               1995                 :                :  */
                               1996                 :                : 
                               1997                 :                : /*
                               1998                 :                :  * Check to see whether the table needs a TOAST table.  It does only if
                               1999                 :                :  * (1) there are any toastable attributes, and (2) the maximum length
                               2000                 :                :  * of a tuple could exceed TOAST_TUPLE_THRESHOLD.  (We don't want to
                               2001                 :                :  * create a toast table for something like "f1 varchar(20)".)
                               2002                 :                :  */
                               2003                 :                : static bool
 2623 rhaas@postgresql.org     2004                 :          31297 : heapam_relation_needs_toast_table(Relation rel)
                               2005                 :                : {
                               2006                 :          31297 :     int32       data_length = 0;
                               2007                 :          31297 :     bool        maxlength_unknown = false;
                               2008                 :          31297 :     bool        has_toastable_attrs = false;
                               2009                 :          31297 :     TupleDesc   tupdesc = rel->rd_att;
                               2010                 :                :     int32       tuple_length;
                               2011                 :                :     int         i;
                               2012                 :                : 
                               2013         [ +  + ]:         122219 :     for (i = 0; i < tupdesc->natts; i++)
                               2014                 :                :     {
                               2015                 :          90922 :         Form_pg_attribute att = TupleDescAttr(tupdesc, i);
                               2016                 :                : 
                               2017         [ +  + ]:          90922 :         if (att->attisdropped)
                               2018                 :            789 :             continue;
  534 peter@eisentraut.org     2019         [ +  + ]:          90133 :         if (att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
                               2020                 :            704 :             continue;
 2623 rhaas@postgresql.org     2021                 :          89429 :         data_length = att_align_nominal(data_length, att->attalign);
                               2022         [ +  + ]:          89429 :         if (att->attlen > 0)
                               2023                 :                :         {
                               2024                 :                :             /* Fixed-length types are never toastable */
                               2025                 :          66819 :             data_length += att->attlen;
                               2026                 :                :         }
                               2027                 :                :         else
                               2028                 :                :         {
                               2029                 :          22610 :             int32       maxlen = type_maximum_size(att->atttypid,
                               2030                 :                :                                                    att->atttypmod);
                               2031                 :                : 
                               2032         [ +  + ]:          22610 :             if (maxlen < 0)
                               2033                 :          20369 :                 maxlength_unknown = true;
                               2034                 :                :             else
                               2035                 :           2241 :                 data_length += maxlen;
 2335 tgl@sss.pgh.pa.us        2036         [ +  + ]:          22610 :             if (att->attstorage != TYPSTORAGE_PLAIN)
 2623 rhaas@postgresql.org     2037                 :          21925 :                 has_toastable_attrs = true;
                               2038                 :                :         }
                               2039                 :                :     }
                               2040         [ +  + ]:          31297 :     if (!has_toastable_attrs)
                               2041                 :          18439 :         return false;           /* nothing to toast? */
                               2042         [ +  + ]:          12858 :     if (maxlength_unknown)
                               2043                 :          11167 :         return true;            /* any unlimited-length attrs? */
                               2044                 :           1691 :     tuple_length = MAXALIGN(SizeofHeapTupleHeader +
                               2045                 :           1691 :                             BITMAPLEN(tupdesc->natts)) +
                               2046                 :           1691 :         MAXALIGN(data_length);
                               2047                 :           1691 :     return (tuple_length > TOAST_TUPLE_THRESHOLD);
                               2048                 :                : }
                               2049                 :                : 
                               2050                 :                : /*
                               2051                 :                :  * TOAST tables for heap relations are just heap relations.
                               2052                 :                :  */
                               2053                 :                : static Oid
 2392                          2054                 :          11469 : heapam_relation_toast_am(Relation rel)
                               2055                 :                : {
                               2056                 :          11469 :     return rel->rd_rel->relam;
                               2057                 :                : }
                               2058                 :                : 
                               2059                 :                : 
                               2060                 :                : /* ------------------------------------------------------------------------
                               2061                 :                :  * Planner related callbacks for the heap AM
                               2062                 :                :  * ------------------------------------------------------------------------
                               2063                 :                :  */
                               2064                 :                : 
                               2065                 :                : #define HEAP_OVERHEAD_BYTES_PER_TUPLE \
                               2066                 :                :     (MAXALIGN(SizeofHeapTupleHeader) + sizeof(ItemIdData))
                               2067                 :                : #define HEAP_USABLE_BYTES_PER_PAGE \
                               2068                 :                :     (BLCKSZ - SizeOfPageHeaderData)
                               2069                 :                : 
                               2070                 :                : static void
 2675 andres@anarazel.de       2071                 :         347894 : heapam_estimate_rel_size(Relation rel, int32 *attr_widths,
                               2072                 :                :                          BlockNumber *pages, double *tuples,
                               2073                 :                :                          double *allvisfrac)
                               2074                 :                : {
 2575 rhaas@postgresql.org     2075                 :         347894 :     table_block_relation_estimate_size(rel, attr_widths, pages,
                               2076                 :                :                                        tuples, allvisfrac,
                               2077                 :                :                                        HEAP_OVERHEAD_BYTES_PER_TUPLE,
                               2078                 :                :                                        HEAP_USABLE_BYTES_PER_PAGE);
 2675 andres@anarazel.de       2079                 :         347894 : }
                               2080                 :                : 
                               2081                 :                : 
                               2082                 :                : /* ------------------------------------------------------------------------
                               2083                 :                :  * Executor related callbacks for the heap AM
                               2084                 :                :  * ------------------------------------------------------------------------
                               2085                 :                :  */
                               2086                 :                : 
                               2087                 :                : static bool
  498 melanieplageman@gmai     2088                 :        4049588 : heapam_scan_bitmap_next_tuple(TableScanDesc scan,
                               2089                 :                :                               TupleTableSlot *slot,
                               2090                 :                :                               bool *recheck,
                               2091                 :                :                               uint64 *lossy_pages,
                               2092                 :                :                               uint64 *exact_pages)
                               2093                 :                : {
  556                          2094                 :        4049588 :     BitmapHeapScanDesc bscan = (BitmapHeapScanDesc) scan;
                               2095                 :        4049588 :     HeapScanDesc hscan = (HeapScanDesc) bscan;
                               2096                 :                :     OffsetNumber targoffset;
                               2097                 :                :     Page        page;
                               2098                 :                :     ItemId      lp;
                               2099                 :                : 
                               2100                 :                :     /*
                               2101                 :                :      * Out of range?  If so, nothing more to look at on this page
                               2102                 :                :      */
  498                          2103         [ +  + ]:        4292982 :     while (hscan->rs_cindex >= hscan->rs_ntuples)
                               2104                 :                :     {
                               2105                 :                :         /*
                               2106                 :                :          * Returns false if the bitmap is exhausted and there are no further
                               2107                 :                :          * blocks we need to scan.
                               2108                 :                :          */
                               2109         [ +  + ]:         257943 :         if (!BitmapHeapScanNextBlock(scan, recheck, lossy_pages, exact_pages))
                               2110                 :          14546 :             return false;
                               2111                 :                :     }
                               2112                 :                : 
 2674 andres@anarazel.de       2113                 :        4035039 :     targoffset = hscan->rs_vistuples[hscan->rs_cindex];
 1348 peter@eisentraut.org     2114                 :        4035039 :     page = BufferGetPage(hscan->rs_cbuf);
                               2115                 :        4035039 :     lp = PageGetItemId(page, targoffset);
 2674 andres@anarazel.de       2116         [ -  + ]:        4035039 :     Assert(ItemIdIsNormal(lp));
                               2117                 :                : 
 1348 peter@eisentraut.org     2118                 :        4035039 :     hscan->rs_ctup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
 2674 andres@anarazel.de       2119                 :        4035039 :     hscan->rs_ctup.t_len = ItemIdGetLength(lp);
                               2120                 :        4035039 :     hscan->rs_ctup.t_tableOid = scan->rs_rd->rd_id;
                               2121                 :        4035039 :     ItemPointerSet(&hscan->rs_ctup.t_self, hscan->rs_cblock, targoffset);
                               2122                 :                : 
                               2123   [ -  +  -  -  :        4035039 :     pgstat_count_heap_fetch(scan->rs_rd);
                                              +  - ]
                               2124                 :                : 
                               2125                 :                :     /*
                               2126                 :                :      * Set up the result slot to point to this tuple.  Note that the slot
                               2127                 :                :      * acquires a pin on the buffer.
                               2128                 :                :      */
                               2129                 :        4035039 :     ExecStoreBufferHeapTuple(&hscan->rs_ctup,
                               2130                 :                :                              slot,
                               2131                 :                :                              hscan->rs_cbuf);
                               2132                 :                : 
                               2133                 :        4035039 :     hscan->rs_cindex++;
                               2134                 :                : 
                               2135                 :        4035039 :     return true;
                               2136                 :                : }
                               2137                 :                : 
                               2138                 :                : static bool
 2675                          2139                 :           8588 : heapam_scan_sample_next_block(TableScanDesc scan, SampleScanState *scanstate)
                               2140                 :                : {
                               2141                 :           8588 :     HeapScanDesc hscan = (HeapScanDesc) scan;
                               2142                 :           8588 :     TsmRoutine *tsm = scanstate->tsmroutine;
                               2143                 :                :     BlockNumber blockno;
                               2144                 :                : 
                               2145                 :                :     /* return false immediately if relation is empty */
                               2146         [ -  + ]:           8588 :     if (hscan->rs_nblocks == 0)
 2675 andres@anarazel.de       2147                 :UBC           0 :         return false;
                               2148                 :                : 
                               2149                 :                :     /* release previous scan buffer, if any */
  843 drowley@postgresql.o     2150         [ +  + ]:CBC        8588 :     if (BufferIsValid(hscan->rs_cbuf))
                               2151                 :                :     {
                               2152                 :           8475 :         ReleaseBuffer(hscan->rs_cbuf);
                               2153                 :           8475 :         hscan->rs_cbuf = InvalidBuffer;
                               2154                 :                :     }
                               2155                 :                : 
                               2156         [ +  + ]:           8588 :     if (tsm->NextSampleBlock)
                               2157                 :           2944 :         blockno = tsm->NextSampleBlock(scanstate, hscan->rs_nblocks);
                               2158                 :                :     else
                               2159                 :                :     {
                               2160                 :                :         /* scanning table sequentially */
                               2161                 :                : 
 2675 andres@anarazel.de       2162         [ +  + ]:           5644 :         if (hscan->rs_cblock == InvalidBlockNumber)
                               2163                 :                :         {
                               2164         [ -  + ]:             52 :             Assert(!hscan->rs_inited);
                               2165                 :             52 :             blockno = hscan->rs_startblock;
                               2166                 :                :         }
                               2167                 :                :         else
                               2168                 :                :         {
                               2169         [ -  + ]:           5592 :             Assert(hscan->rs_inited);
                               2170                 :                : 
                               2171                 :           5592 :             blockno = hscan->rs_cblock + 1;
                               2172                 :                : 
                               2173         [ +  + ]:           5592 :             if (blockno >= hscan->rs_nblocks)
                               2174                 :                :             {
                               2175                 :                :                 /* wrap to beginning of rel, might not have started at 0 */
                               2176                 :             52 :                 blockno = 0;
                               2177                 :                :             }
                               2178                 :                : 
                               2179                 :                :             /*
                               2180                 :                :              * Report our new scan position for synchronization purposes.
                               2181                 :                :              *
                               2182                 :                :              * Note: we do this before checking for end of scan so that the
                               2183                 :                :              * final state of the position hint is back at the start of the
                               2184                 :                :              * rel.  That's not strictly necessary, but otherwise when you run
                               2185                 :                :              * the same query multiple times the starting position would shift
                               2186                 :                :              * a little bit backwards on every invocation, which is confusing.
                               2187                 :                :              * We don't guarantee any specific ordering in general, though.
                               2188                 :                :              */
 2625                          2189         [ -  + ]:           5592 :             if (scan->rs_flags & SO_ALLOW_SYNC)
 2675 andres@anarazel.de       2190                 :UBC           0 :                 ss_report_location(scan->rs_rd, blockno);
                               2191                 :                : 
 2675 andres@anarazel.de       2192         [ +  + ]:CBC        5592 :             if (blockno == hscan->rs_startblock)
                               2193                 :                :             {
                               2194                 :             52 :                 blockno = InvalidBlockNumber;
                               2195                 :                :             }
                               2196                 :                :         }
                               2197                 :                :     }
                               2198                 :                : 
  843 drowley@postgresql.o     2199                 :           8588 :     hscan->rs_cblock = blockno;
                               2200                 :                : 
 2675 andres@anarazel.de       2201         [ +  + ]:           8588 :     if (!BlockNumberIsValid(blockno))
                               2202                 :                :     {
                               2203                 :            109 :         hscan->rs_inited = false;
                               2204                 :            109 :         return false;
                               2205                 :                :     }
                               2206                 :                : 
  843 drowley@postgresql.o     2207         [ -  + ]:           8479 :     Assert(hscan->rs_cblock < hscan->rs_nblocks);
                               2208                 :                : 
                               2209                 :                :     /*
                               2210                 :                :      * Be sure to check for interrupts at least once per page.  Checks at
                               2211                 :                :      * higher code levels won't be able to stop a sample scan that encounters
                               2212                 :                :      * many pages' worth of consecutive dead tuples.
                               2213                 :                :      */
                               2214         [ -  + ]:           8479 :     CHECK_FOR_INTERRUPTS();
                               2215                 :                : 
                               2216                 :                :     /* Read page using selected strategy */
                               2217                 :           8479 :     hscan->rs_cbuf = ReadBufferExtended(hscan->rs_base.rs_rd, MAIN_FORKNUM,
                               2218                 :                :                                         blockno, RBM_NORMAL, hscan->rs_strategy);
                               2219                 :                : 
                               2220                 :                :     /* in pagemode, prune the page and determine visible tuple offsets */
                               2221         [ +  + ]:           8479 :     if (hscan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
                               2222                 :           5687 :         heap_prepare_pagescan(scan);
                               2223                 :                : 
                               2224                 :           8479 :     hscan->rs_inited = true;
 2675 andres@anarazel.de       2225                 :           8479 :     return true;
                               2226                 :                : }
                               2227                 :                : 
                               2228                 :                : static bool
                               2229                 :         169183 : heapam_scan_sample_next_tuple(TableScanDesc scan, SampleScanState *scanstate,
                               2230                 :                :                               TupleTableSlot *slot)
                               2231                 :                : {
                               2232                 :         169183 :     HeapScanDesc hscan = (HeapScanDesc) scan;
                               2233                 :         169183 :     TsmRoutine *tsm = scanstate->tsmroutine;
                               2234                 :         169183 :     BlockNumber blockno = hscan->rs_cblock;
 2625                          2235                 :         169183 :     bool        pagemode = (scan->rs_flags & SO_ALLOW_PAGEMODE) != 0;
                               2236                 :                : 
                               2237                 :                :     Page        page;
                               2238                 :                :     bool        all_visible;
                               2239                 :                :     OffsetNumber maxoffset;
                               2240                 :                : 
                               2241                 :                :     /*
                               2242                 :                :      * When not using pagemode, we must lock the buffer during tuple
                               2243                 :                :      * visibility checks.
                               2244                 :                :      */
 2675                          2245         [ +  + ]:         169183 :     if (!pagemode)
                               2246                 :           2796 :         LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_SHARE);
                               2247                 :                : 
  331 peter@eisentraut.org     2248                 :         169183 :     page = BufferGetPage(hscan->rs_cbuf);
 2675 andres@anarazel.de       2249         [ +  + ]:         337844 :     all_visible = PageIsAllVisible(page) &&
                               2250         [ +  - ]:         168661 :         !scan->rs_snapshot->takenDuringRecovery;
                               2251                 :         169183 :     maxoffset = PageGetMaxOffsetNumber(page);
                               2252                 :                : 
                               2253                 :                :     for (;;)
 2675 andres@anarazel.de       2254                 :UBC           0 :     {
                               2255                 :                :         OffsetNumber tupoffset;
                               2256                 :                : 
 2675 andres@anarazel.de       2257         [ -  + ]:CBC      169183 :         CHECK_FOR_INTERRUPTS();
                               2258                 :                : 
                               2259                 :                :         /* Ask the tablesample method which tuples to check on this page. */
                               2260                 :         169183 :         tupoffset = tsm->NextSampleTuple(scanstate,
                               2261                 :                :                                          blockno,
                               2262                 :                :                                          maxoffset);
                               2263                 :                : 
                               2264   [ +  +  +  -  :         169183 :         if (OffsetNumberIsValid(tupoffset))
                                              +  + ]
                               2265                 :                :         {
                               2266                 :                :             ItemId      itemid;
                               2267                 :                :             bool        visible;
                               2268                 :         160708 :             HeapTuple   tuple = &(hscan->rs_ctup);
                               2269                 :                : 
                               2270                 :                :             /* Skip invalid tuple pointers. */
                               2271                 :         160708 :             itemid = PageGetItemId(page, tupoffset);
                               2272         [ -  + ]:         160708 :             if (!ItemIdIsNormal(itemid))
 2675 andres@anarazel.de       2273                 :UBC           0 :                 continue;
                               2274                 :                : 
 2675 andres@anarazel.de       2275                 :CBC      160708 :             tuple->t_data = (HeapTupleHeader) PageGetItem(page, itemid);
                               2276                 :         160708 :             tuple->t_len = ItemIdGetLength(itemid);
                               2277                 :         160708 :             ItemPointerSet(&(tuple->t_self), blockno, tupoffset);
                               2278                 :                : 
                               2279                 :                : 
                               2280         [ +  + ]:         160708 :             if (all_visible)
                               2281                 :         160337 :                 visible = true;
                               2282                 :                :             else
                               2283                 :            371 :                 visible = SampleHeapTupleVisible(scan, hscan->rs_cbuf,
                               2284                 :                :                                                  tuple, tupoffset);
                               2285                 :                : 
                               2286                 :                :             /* in pagemode, heap_prepare_pagescan did this for us */
                               2287         [ +  + ]:         160708 :             if (!pagemode)
 2371 tmunro@postgresql.or     2288                 :              4 :                 HeapCheckForSerializableConflictOut(visible, scan->rs_rd, tuple,
                               2289                 :                :                                                     hscan->rs_cbuf, scan->rs_snapshot);
                               2290                 :                : 
                               2291                 :                :             /* Try next tuple from same page. */
 2675 andres@anarazel.de       2292         [ -  + ]:         160708 :             if (!visible)
 2675 andres@anarazel.de       2293                 :UBC           0 :                 continue;
                               2294                 :                : 
                               2295                 :                :             /* Found visible tuple, return it. */
 2675 andres@anarazel.de       2296         [ +  + ]:CBC      160708 :             if (!pagemode)
                               2297                 :              4 :                 LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                               2298                 :                : 
                               2299                 :         160708 :             ExecStoreBufferHeapTuple(tuple, slot, hscan->rs_cbuf);
                               2300                 :                : 
                               2301                 :                :             /* Count successfully-fetched tuples as heap fetches */
                               2302   [ -  +  -  -  :         160708 :             pgstat_count_heap_getnext(scan->rs_rd);
                                              +  - ]
                               2303                 :                : 
                               2304                 :         160708 :             return true;
                               2305                 :                :         }
                               2306                 :                :         else
                               2307                 :                :         {
                               2308                 :                :             /*
                               2309                 :                :              * If we get here, it means we've exhausted the items on this page
                               2310                 :                :              * and it's time to move to the next.
                               2311                 :                :              */
                               2312         [ +  + ]:           8475 :             if (!pagemode)
                               2313                 :           2792 :                 LockBuffer(hscan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                               2314                 :                : 
                               2315                 :           8475 :             ExecClearTuple(slot);
                               2316                 :           8475 :             return false;
                               2317                 :                :         }
                               2318                 :                :     }
                               2319                 :                : 
                               2320                 :                :     Assert(0);
                               2321                 :                : }
                               2322                 :                : 
                               2323                 :                : 
                               2324                 :                : /* ----------------------------------------------------------------------------
                               2325                 :                :  *  Helper functions for the above.
                               2326                 :                :  * ----------------------------------------------------------------------------
                               2327                 :                :  */
                               2328                 :                : 
                               2329                 :                : /*
                               2330                 :                :  * Reconstruct and rewrite the given tuple
                               2331                 :                :  *
                               2332                 :                :  * We cannot simply copy the tuple as-is, for several reasons:
                               2333                 :                :  *
                               2334                 :                :  * 1. We'd like to squeeze out the values of any dropped columns, both
                               2335                 :                :  * to save space and to ensure we have no corner-case failures. (It's
                               2336                 :                :  * possible for example that the new table hasn't got a TOAST table
                               2337                 :                :  * and so is unable to store any large values of dropped cols.)
                               2338                 :                :  *
                               2339                 :                :  * 2. The tuple might not even be legal for the new table; this is
                               2340                 :                :  * currently only known to happen as an after-effect of ALTER TABLE
                               2341                 :                :  * SET WITHOUT OIDS.
                               2342                 :                :  *
                               2343                 :                :  * So, we must reconstruct the tuple from component Datums.
                               2344                 :                :  */
                               2345                 :                : static void
                               2346                 :         474721 : reform_and_rewrite_tuple(HeapTuple tuple,
                               2347                 :                :                          Relation OldHeap, Relation NewHeap,
                               2348                 :                :                          Datum *values, bool *isnull, RewriteState rwstate)
                               2349                 :                : {
                               2350                 :                :     HeapTuple   newtuple;
                               2351                 :                : 
  111 alvherre@kurilemu.de     2352                 :         474721 :     newtuple = reform_tuple(tuple, OldHeap, NewHeap, values, isnull);
                               2353                 :                : 
                               2354                 :                :     /* The heap rewrite module does the rest */
                               2355                 :         474721 :     rewrite_heap_tuple(rwstate, tuple, newtuple);
                               2356                 :                : 
                               2357                 :         474721 :     heap_freetuple(newtuple);
                               2358                 :         474721 : }
                               2359                 :                : 
                               2360                 :                : /*
                               2361                 :                :  * Insert tuple when processing REPACK CONCURRENTLY.
                               2362                 :                :  *
                               2363                 :                :  * rewriteheap.c is not used in the CONCURRENTLY case because it'd be
                               2364                 :                :  * difficult to do the same in the catch-up phase (as the logical
                               2365                 :                :  * decoding does not provide us with sufficient visibility
                               2366                 :                :  * information). Thus we must use heap_insert() both during the
                               2367                 :                :  * catch-up and here.
                               2368                 :                :  *
                               2369                 :                :  * We pass the NO_LOGICAL flag to heap_insert() in order to skip logical
                               2370                 :                :  * decoding: as soon as REPACK CONCURRENTLY swaps the relation files, it drops
                               2371                 :                :  * this relation, so no logical replication subscription should need the data.
                               2372                 :                :  *
                               2373                 :                :  * BulkInsertState is used because many tuples are inserted in the typical
                               2374                 :                :  * case.
                               2375                 :                :  */
                               2376                 :                : static void
                               2377                 :             31 : heap_insert_for_repack(HeapTuple tuple, Relation OldHeap, Relation NewHeap,
                               2378                 :                :                        Datum *values, bool *isnull, BulkInsertState bistate)
                               2379                 :                : {
                               2380                 :                :     HeapTuple   newtuple;
                               2381                 :                : 
                               2382                 :             31 :     newtuple = reform_tuple(tuple, OldHeap, NewHeap, values, isnull);
                               2383                 :                : 
                               2384                 :             31 :     heap_insert(NewHeap, newtuple, GetCurrentCommandId(true),
                               2385                 :                :                 HEAP_INSERT_NO_LOGICAL, bistate);
                               2386                 :                : 
                               2387                 :             31 :     heap_freetuple(newtuple);
                               2388                 :             31 : }
                               2389                 :                : 
                               2390                 :                : /*
                               2391                 :                :  * Subroutine for reform_and_rewrite_tuple and heap_insert_for_repack.
                               2392                 :                :  *
                               2393                 :                :  * Deform the given tuple, set values of dropped columns to NULL, and fill in
                               2394                 :                :  * any values from attmissingval; then form a new tuple and return it.  If no
                               2395                 :                :  * attributes need to be changed, a copy of the original tuple is returned.
                               2396                 :                :  * Caller is responsible for freeing the returned tuple.
                               2397                 :                :  *
                               2398                 :                :  * XXX this coding assumes that both relations have the same tupledesc.
                               2399                 :                :  */
                               2400                 :                : static HeapTuple
                               2401                 :         474752 : reform_tuple(HeapTuple tuple, Relation OldHeap, Relation NewHeap,
                               2402                 :                :              Datum *values, bool *isnull)
                               2403                 :                : {
 2675 andres@anarazel.de       2404                 :         474752 :     TupleDesc   oldTupDesc = RelationGetDescr(OldHeap);
                               2405                 :         474752 :     TupleDesc   newTupDesc = RelationGetDescr(NewHeap);
  111 alvherre@kurilemu.de     2406                 :         474752 :     bool        needs_reform = false;
                               2407                 :                : 
                               2408                 :                :     /*
                               2409                 :                :      * A short tuple might require values from attmissing val, so activate the
                               2410                 :                :      * coding unconditionally in that case.  The value might legitimally be
                               2411                 :                :      * NULL otherwise, so this is slightly wasteful, but it probably beats
                               2412                 :                :      * having to test each attribute for presence of attmissingval each time.
                               2413                 :                :      */
   82                          2414         [ +  + ]:         474752 :     if (HeapTupleHeaderGetNatts(tuple->t_data) < newTupDesc->natts)
                               2415                 :             41 :         needs_reform = true;
                               2416                 :                : 
                               2417                 :                :     /*
                               2418                 :                :      * If the column has been dropped but a value is still present, we can
                               2419                 :                :      * optimize storage now by getting rid of it.
                               2420                 :                :      */
                               2421         [ +  + ]:         474752 :     if (!needs_reform)
                               2422                 :                :     {
                               2423         [ +  + ]:        3957807 :         for (int i = 0; i < newTupDesc->natts; i++)
                               2424                 :                :         {
                               2425         [ +  + ]:        3483106 :             if (TupleDescCompactAttr(newTupDesc, i)->attisdropped &&
                               2426         [ +  + ]:             30 :                 !heap_attisnull(tuple, i + 1, newTupDesc))
                               2427                 :                :             {
                               2428                 :             10 :                 needs_reform = true;
                               2429                 :             10 :                 break;
                               2430                 :                :             }
                               2431                 :                :         }
                               2432                 :                :     }
                               2433                 :                : 
                               2434                 :                :     /* Skip work if no changes are needed */
  111                          2435         [ +  + ]:         474752 :     if (!needs_reform)
                               2436                 :         474701 :         return heap_copytuple(tuple);
                               2437                 :                : 
 2675 andres@anarazel.de       2438                 :             51 :     heap_deform_tuple(tuple, oldTupDesc, values, isnull);
                               2439                 :                : 
  111 alvherre@kurilemu.de     2440         [ +  + ]:            255 :     for (int i = 0; i < newTupDesc->natts; i++)
                               2441                 :                :     {
  583 drowley@postgresql.o     2442         [ +  + ]:            204 :         if (TupleDescCompactAttr(newTupDesc, i)->attisdropped)
 2675 andres@anarazel.de       2443                 :             20 :             isnull[i] = true;
                               2444                 :                :     }
                               2445                 :                : 
  111 alvherre@kurilemu.de     2446                 :             51 :     return heap_form_tuple(newTupDesc, values, isnull);
                               2447                 :                : }
                               2448                 :                : 
                               2449                 :                : /*
                               2450                 :                :  * Check visibility of the tuple.
                               2451                 :                :  */
                               2452                 :                : static bool
 2675 andres@anarazel.de       2453                 :            371 : SampleHeapTupleVisible(TableScanDesc scan, Buffer buffer,
                               2454                 :                :                        HeapTuple tuple,
                               2455                 :                :                        OffsetNumber tupoffset)
                               2456                 :                : {
                               2457                 :            371 :     HeapScanDesc hscan = (HeapScanDesc) scan;
                               2458                 :                : 
 2625                          2459         [ +  + ]:            371 :     if (scan->rs_flags & SO_ALLOW_PAGEMODE)
                               2460                 :                :     {
  583 melanieplageman@gmai     2461                 :            367 :         uint32      start = 0,
                               2462                 :            367 :                     end = hscan->rs_ntuples;
                               2463                 :                : 
                               2464                 :                :         /*
                               2465                 :                :          * In pageatatime mode, heap_prepare_pagescan() already did visibility
                               2466                 :                :          * checks, so just look at the info it left in rs_vistuples[].
                               2467                 :                :          *
                               2468                 :                :          * We use a binary search over the known-sorted array.  Note: we could
                               2469                 :                :          * save some effort if we insisted that NextSampleTuple select tuples
                               2470                 :                :          * in increasing order, but it's not clear that there would be enough
                               2471                 :                :          * gain to justify the restriction.
                               2472                 :                :          */
                               2473         [ +  - ]:            685 :         while (start < end)
                               2474                 :                :         {
                               2475                 :            685 :             uint32      mid = start + (end - start) / 2;
 2675 andres@anarazel.de       2476                 :            685 :             OffsetNumber curoffset = hscan->rs_vistuples[mid];
                               2477                 :                : 
                               2478         [ +  + ]:            685 :             if (tupoffset == curoffset)
                               2479                 :            367 :                 return true;
                               2480         [ +  + ]:            318 :             else if (tupoffset < curoffset)
  583 melanieplageman@gmai     2481                 :            164 :                 end = mid;
                               2482                 :                :             else
 2675 andres@anarazel.de       2483                 :            154 :                 start = mid + 1;
                               2484                 :                :         }
                               2485                 :                : 
 2675 andres@anarazel.de       2486                 :UBC           0 :         return false;
                               2487                 :                :     }
                               2488                 :                :     else
                               2489                 :                :     {
                               2490                 :                :         /* Otherwise, we have to check the tuple individually. */
 2675 andres@anarazel.de       2491                 :CBC           4 :         return HeapTupleSatisfiesVisibility(tuple, scan->rs_snapshot,
                               2492                 :                :                                             buffer);
                               2493                 :                :     }
                               2494                 :                : }
                               2495                 :                : 
                               2496                 :                : /*
                               2497                 :                :  * Helper function get the next block of a bitmap heap scan. Returns true when
                               2498                 :                :  * it got the next block and saved it in the scan descriptor and false when
                               2499                 :                :  * the bitmap and or relation are exhausted.
                               2500                 :                :  */
                               2501                 :                : static bool
  498 melanieplageman@gmai     2502                 :         257943 : BitmapHeapScanNextBlock(TableScanDesc scan,
                               2503                 :                :                         bool *recheck,
                               2504                 :                :                         uint64 *lossy_pages, uint64 *exact_pages)
                               2505                 :                : {
                               2506                 :         257943 :     BitmapHeapScanDesc bscan = (BitmapHeapScanDesc) scan;
                               2507                 :         257943 :     HeapScanDesc hscan = (HeapScanDesc) bscan;
                               2508                 :                :     BlockNumber block;
                               2509                 :                :     void       *per_buffer_data;
                               2510                 :                :     Buffer      buffer;
                               2511                 :                :     Snapshot    snapshot;
                               2512                 :                :     int         ntup;
                               2513                 :                :     TBMIterateResult *tbmres;
                               2514                 :                :     OffsetNumber offsets[TBM_MAX_TUPLES_PER_PAGE];
                               2515                 :         257943 :     int         noffsets = -1;
                               2516                 :                : 
                               2517         [ -  + ]:         257943 :     Assert(scan->rs_flags & SO_TYPE_BITMAPSCAN);
                               2518         [ -  + ]:         257943 :     Assert(hscan->rs_read_stream);
                               2519                 :                : 
                               2520                 :         257943 :     hscan->rs_cindex = 0;
                               2521                 :         257943 :     hscan->rs_ntuples = 0;
                               2522                 :                : 
                               2523                 :                :     /* Release buffer containing previous block. */
                               2524         [ +  + ]:         257943 :     if (BufferIsValid(hscan->rs_cbuf))
                               2525                 :                :     {
                               2526                 :         243131 :         ReleaseBuffer(hscan->rs_cbuf);
                               2527                 :         243131 :         hscan->rs_cbuf = InvalidBuffer;
                               2528                 :                :     }
                               2529                 :                : 
                               2530                 :         257943 :     hscan->rs_cbuf = read_stream_next_buffer(hscan->rs_read_stream,
                               2531                 :                :                                              &per_buffer_data);
                               2532                 :                : 
                               2533         [ +  + ]:         257943 :     if (BufferIsInvalid(hscan->rs_cbuf))
                               2534                 :                :     {
                               2535                 :                :         /* the bitmap is exhausted */
  480 andres@anarazel.de       2536                 :          14546 :         return false;
                               2537                 :                :     }
                               2538                 :                : 
  498 melanieplageman@gmai     2539         [ -  + ]:         243397 :     Assert(per_buffer_data);
                               2540                 :                : 
                               2541                 :         243397 :     tbmres = per_buffer_data;
                               2542                 :                : 
                               2543         [ -  + ]:         243397 :     Assert(BlockNumberIsValid(tbmres->blockno));
                               2544         [ -  + ]:         243397 :     Assert(BufferGetBlockNumber(hscan->rs_cbuf) == tbmres->blockno);
                               2545                 :                : 
                               2546                 :                :     /* Exact pages need their tuple offsets extracted. */
                               2547         [ +  + ]:         243397 :     if (!tbmres->lossy)
                               2548                 :         136462 :         noffsets = tbm_extract_page_tuple(tbmres, offsets,
                               2549                 :                :                                           TBM_MAX_TUPLES_PER_PAGE);
                               2550                 :                : 
                               2551                 :         243397 :     *recheck = tbmres->recheck;
                               2552                 :                : 
                               2553                 :         243397 :     block = hscan->rs_cblock = tbmres->blockno;
                               2554                 :         243397 :     buffer = hscan->rs_cbuf;
                               2555                 :         243397 :     snapshot = scan->rs_snapshot;
                               2556                 :                : 
                               2557                 :         243397 :     ntup = 0;
                               2558                 :                : 
                               2559                 :                :     /*
                               2560                 :                :      * Prune and repair fragmentation for the whole page, if possible.
                               2561                 :                :      */
  118                          2562                 :         243397 :     heap_page_prune_opt(scan->rs_rd, buffer, &hscan->rs_vmbuffer,
                               2563                 :         243397 :                         scan->rs_flags & SO_HINT_REL_READ_ONLY);
                               2564                 :                : 
                               2565                 :                :     /*
                               2566                 :                :      * We must hold share lock on the buffer content while examining tuple
                               2567                 :                :      * visibility.  Afterwards, however, the tuples we have found to be
                               2568                 :                :      * visible are guaranteed good as long as we hold the buffer pin.
                               2569                 :                :      */
  498                          2570                 :         243397 :     LockBuffer(buffer, BUFFER_LOCK_SHARE);
                               2571                 :                : 
                               2572                 :                :     /*
                               2573                 :                :      * We need two separate strategies for lossy and non-lossy cases.
                               2574                 :                :      */
                               2575         [ +  + ]:         243397 :     if (!tbmres->lossy)
                               2576                 :                :     {
                               2577                 :                :         /*
                               2578                 :                :          * Bitmap is non-lossy, so we just look through the offsets listed in
                               2579                 :                :          * tbmres; but we have to follow any HOT chain starting at each such
                               2580                 :                :          * offset.
                               2581                 :                :          */
                               2582                 :                :         int         curslot;
                               2583                 :                : 
                               2584                 :                :         /* We must have extracted the tuple offsets by now */
                               2585         [ -  + ]:         136462 :         Assert(noffsets > -1);
                               2586                 :                : 
                               2587         [ +  + ]:        3506533 :         for (curslot = 0; curslot < noffsets; curslot++)
                               2588                 :                :         {
                               2589                 :        3370074 :             OffsetNumber offnum = offsets[curslot];
                               2590                 :                :             ItemPointerData tid;
                               2591                 :                :             HeapTupleData heapTuple;
                               2592                 :                : 
                               2593                 :        3370074 :             ItemPointerSet(&tid, block, offnum);
                               2594         [ +  + ]:        3370074 :             if (heap_hot_search_buffer(&tid, scan->rs_rd, buffer, snapshot,
                               2595                 :                :                                        &heapTuple, NULL, true))
                               2596                 :        3220585 :                 hscan->rs_vistuples[ntup++] = ItemPointerGetOffsetNumber(&tid);
                               2597                 :                :         }
                               2598                 :                :     }
                               2599                 :                :     else
                               2600                 :                :     {
                               2601                 :                :         /*
                               2602                 :                :          * Bitmap is lossy, so we must examine each line pointer on the page.
                               2603                 :                :          * But we can ignore HOT chains, since we'll check each tuple anyway.
                               2604                 :                :          */
                               2605                 :         106935 :         Page        page = BufferGetPage(buffer);
                               2606                 :         106935 :         OffsetNumber maxoff = PageGetMaxOffsetNumber(page);
                               2607                 :                :         OffsetNumber offnum;
                               2608                 :                : 
                               2609         [ +  + ]:         923265 :         for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum))
                               2610                 :                :         {
                               2611                 :                :             ItemId      lp;
                               2612                 :                :             HeapTupleData loctup;
                               2613                 :                :             bool        valid;
                               2614                 :                : 
                               2615                 :         816330 :             lp = PageGetItemId(page, offnum);
                               2616         [ -  + ]:         816330 :             if (!ItemIdIsNormal(lp))
  498 melanieplageman@gmai     2617                 :UBC           0 :                 continue;
  498 melanieplageman@gmai     2618                 :CBC      816330 :             loctup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
                               2619                 :         816330 :             loctup.t_len = ItemIdGetLength(lp);
                               2620                 :         816330 :             loctup.t_tableOid = scan->rs_rd->rd_id;
                               2621                 :         816330 :             ItemPointerSet(&loctup.t_self, block, offnum);
                               2622                 :         816330 :             valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
                               2623         [ +  + ]:         816330 :             if (valid)
                               2624                 :                :             {
                               2625                 :         816246 :                 hscan->rs_vistuples[ntup++] = offnum;
                               2626                 :         816246 :                 PredicateLockTID(scan->rs_rd, &loctup.t_self, snapshot,
                               2627                 :         816246 :                                  HeapTupleHeaderGetXmin(loctup.t_data));
                               2628                 :                :             }
                               2629                 :         816330 :             HeapCheckForSerializableConflictOut(valid, scan->rs_rd, &loctup,
                               2630                 :                :                                                 buffer, snapshot);
                               2631                 :                :         }
                               2632                 :                :     }
                               2633                 :                : 
                               2634                 :         243394 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               2635                 :                : 
                               2636         [ -  + ]:         243394 :     Assert(ntup <= MaxHeapTuplesPerPage);
                               2637                 :         243394 :     hscan->rs_ntuples = ntup;
                               2638                 :                : 
                               2639         [ +  + ]:         243394 :     if (tbmres->lossy)
                               2640                 :         106935 :         (*lossy_pages)++;
                               2641                 :                :     else
                               2642                 :         136459 :         (*exact_pages)++;
                               2643                 :                : 
                               2644                 :                :     /*
                               2645                 :                :      * Return true to indicate that a valid block was found and the bitmap is
                               2646                 :                :      * not exhausted. If there are no visible tuples on this page,
                               2647                 :                :      * hscan->rs_ntuples will be 0 and heapam_scan_bitmap_next_tuple() will
                               2648                 :                :      * return false returning control to this function to advance to the next
                               2649                 :                :      * block in the bitmap.
                               2650                 :                :      */
                               2651                 :         243394 :     return true;
                               2652                 :                : }
                               2653                 :                : 
                               2654                 :                : /* ------------------------------------------------------------------------
                               2655                 :                :  * Definition of the heap table access method.
                               2656                 :                :  * ------------------------------------------------------------------------
                               2657                 :                :  */
                               2658                 :                : 
                               2659                 :                : static const TableAmRoutine heapam_methods = {
                               2660                 :                :     .type = T_TableAmRoutine,
                               2661                 :                : 
                               2662                 :                :     .slot_callbacks = heapam_slot_callbacks,
                               2663                 :                : 
                               2664                 :                :     .scan_begin = heap_beginscan,
                               2665                 :                :     .scan_end = heap_endscan,
                               2666                 :                :     .scan_rescan = heap_rescan,
                               2667                 :                :     .scan_getnextslot = heap_getnextslot,
                               2668                 :                : 
                               2669                 :                :     .scan_set_tidrange = heap_set_tidrange,
                               2670                 :                :     .scan_getnextslot_tidrange = heap_getnextslot_tidrange,
                               2671                 :                : 
                               2672                 :                :     .parallelscan_estimate = table_block_parallelscan_estimate,
                               2673                 :                :     .parallelscan_initialize = table_block_parallelscan_initialize,
                               2674                 :                :     .parallelscan_reinitialize = table_block_parallelscan_reinitialize,
                               2675                 :                : 
                               2676                 :                :     .index_fetch_begin = heapam_index_fetch_begin,
                               2677                 :                :     .index_fetch_reset = heapam_index_fetch_reset,
                               2678                 :                :     .index_fetch_end = heapam_index_fetch_end,
                               2679                 :                :     .index_fetch_tuple = heapam_index_fetch_tuple,
                               2680                 :                : 
                               2681                 :                :     .tuple_insert = heapam_tuple_insert,
                               2682                 :                :     .tuple_insert_speculative = heapam_tuple_insert_speculative,
                               2683                 :                :     .tuple_complete_speculative = heapam_tuple_complete_speculative,
                               2684                 :                :     .multi_insert = heap_multi_insert,
                               2685                 :                :     .tuple_delete = heapam_tuple_delete,
                               2686                 :                :     .tuple_update = heapam_tuple_update,
                               2687                 :                :     .tuple_lock = heapam_tuple_lock,
                               2688                 :                : 
                               2689                 :                :     .tuple_fetch_row_version = heapam_fetch_row_version,
                               2690                 :                :     .tuple_get_latest_tid = heap_get_latest_tid,
                               2691                 :                :     .tuple_tid_valid = heapam_tuple_tid_valid,
                               2692                 :                :     .tuple_satisfies_snapshot = heapam_tuple_satisfies_snapshot,
                               2693                 :                :     .index_delete_tuples = heap_index_delete_tuples,
                               2694                 :                : 
                               2695                 :                :     .relation_set_new_filelocator = heapam_relation_set_new_filelocator,
                               2696                 :                :     .relation_nontransactional_truncate = heapam_relation_nontransactional_truncate,
                               2697                 :                :     .relation_copy_data = heapam_relation_copy_data,
                               2698                 :                :     .relation_copy_for_cluster = heapam_relation_copy_for_cluster,
                               2699                 :                :     .relation_vacuum = heap_vacuum_rel,
                               2700                 :                :     .scan_analyze_next_block = heapam_scan_analyze_next_block,
                               2701                 :                :     .scan_analyze_next_tuple = heapam_scan_analyze_next_tuple,
                               2702                 :                :     .index_build_range_scan = heapam_index_build_range_scan,
                               2703                 :                :     .index_validate_scan = heapam_index_validate_scan,
                               2704                 :                : 
                               2705                 :                :     .relation_size = table_block_relation_size,
                               2706                 :                :     .relation_needs_toast_table = heapam_relation_needs_toast_table,
                               2707                 :                :     .relation_toast_am = heapam_relation_toast_am,
                               2708                 :                :     .relation_fetch_toast_slice = heap_fetch_toast_slice,
                               2709                 :                : 
                               2710                 :                :     .relation_estimate_size = heapam_estimate_rel_size,
                               2711                 :                : 
                               2712                 :                :     .scan_bitmap_next_tuple = heapam_scan_bitmap_next_tuple,
                               2713                 :                :     .scan_sample_next_block = heapam_scan_sample_next_block,
                               2714                 :                :     .scan_sample_next_tuple = heapam_scan_sample_next_tuple
                               2715                 :                : };
                               2716                 :                : 
                               2717                 :                : 
                               2718                 :                : const TableAmRoutine *
 2699 andres@anarazel.de       2719                 :       11845875 : GetHeapamTableAmRoutine(void)
                               2720                 :                : {
                               2721                 :       11845875 :     return &heapam_methods;
                               2722                 :                : }
                               2723                 :                : 
                               2724                 :                : Datum
                               2725                 :        1365283 : heap_tableam_handler(PG_FUNCTION_ARGS)
                               2726                 :                : {
                               2727                 :        1365283 :     PG_RETURN_POINTER(&heapam_methods);
                               2728                 :                : }
        

Generated by: LCOV version 2.0-1