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