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