1 /*-------------------------------------------------------------------------
4 * heap access method code
6 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/access/heap/heapam.c
15 * relation_open - open any relation by relation OID
16 * relation_openrv - open any relation specified by a RangeVar
17 * relation_close - close any relation
18 * heap_open - open a heap relation by relation OID
19 * heap_openrv - open a heap relation specified by a RangeVar
20 * heap_close - (now just a macro for relation_close)
21 * heap_beginscan - begin relation scan
22 * heap_rescan - restart a relation scan
23 * heap_endscan - end relation scan
24 * heap_getnext - retrieve next tuple in scan
25 * heap_fetch - retrieve tuple with given tid
26 * heap_insert - insert tuple into a relation
27 * heap_multi_insert - insert multiple tuples into a relation
28 * heap_delete - delete a tuple from a relation
29 * heap_update - replace a tuple in a relation with another tuple
30 * heap_sync - sync heap, for when no WAL has been written
33 * This file contains the heap_ routines which implement
34 * the POSTGRES heap access method used for all POSTGRES
37 *-------------------------------------------------------------------------
41 #include "access/heapam.h"
42 #include "access/heapam_xlog.h"
43 #include "access/hio.h"
44 #include "access/multixact.h"
45 #include "access/relscan.h"
46 #include "access/sysattr.h"
47 #include "access/transam.h"
48 #include "access/tuptoaster.h"
49 #include "access/valid.h"
50 #include "access/visibilitymap.h"
51 #include "access/xact.h"
52 #include "access/xlog.h"
53 #include "access/xloginsert.h"
54 #include "access/xlogutils.h"
55 #include "catalog/catalog.h"
56 #include "catalog/namespace.h"
57 #include "miscadmin.h"
59 #include "storage/bufmgr.h"
60 #include "storage/freespace.h"
61 #include "storage/lmgr.h"
62 #include "storage/predicate.h"
63 #include "storage/procarray.h"
64 #include "storage/smgr.h"
65 #include "storage/standby.h"
66 #include "utils/datum.h"
67 #include "utils/inval.h"
68 #include "utils/lsyscache.h"
69 #include "utils/relcache.h"
70 #include "utils/snapmgr.h"
71 #include "utils/syscache.h"
72 #include "utils/tqual.h"
76 bool synchronize_seqscans = true;
79 static HeapScanDesc heap_beginscan_internal(Relation relation,
81 int nkeys, ScanKey key,
82 bool allow_strat, bool allow_sync,
83 bool is_bitmapscan, bool temp_snap);
84 static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup,
85 TransactionId xid, CommandId cid, int options);
86 static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
87 Buffer newbuf, HeapTuple oldtup,
88 HeapTuple newtup, HeapTuple old_key_tup,
89 bool all_visible_cleared, bool new_all_visible_cleared);
90 static void HeapSatisfiesHOTandKeyUpdate(Relation relation,
92 Bitmapset *key_attrs, Bitmapset *id_attrs,
93 bool *satisfies_hot, bool *satisfies_key,
95 HeapTuple oldtup, HeapTuple newtup);
96 static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
97 uint16 old_infomask2, TransactionId add_to_xmax,
98 LockTupleMode mode, bool is_update,
99 TransactionId *result_xmax, uint16 *result_infomask,
100 uint16 *result_infomask2);
101 static HTSU_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple,
102 ItemPointer ctid, TransactionId xid,
104 static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
105 uint16 *new_infomask2);
106 static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax,
108 static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
109 Relation rel, ItemPointer ctid, XLTW_Oper oper,
111 static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
112 uint16 infomask, Relation rel, int *remaining);
113 static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup);
114 static HeapTuple ExtractReplicaIdentity(Relation rel, HeapTuple tup, bool key_modified,
119 * Each tuple lock mode has a corresponding heavyweight lock, and one or two
120 * corresponding MultiXactStatuses (one to merely lock tuples, another one to
121 * update them). This table (and the macros below) helps us determine the
122 * heavyweight lock mode and MultiXactStatus values to use for any particular
123 * tuple lock strength.
125 * Don't look at lockstatus/updstatus directly! Use get_mxact_status_for_lock
135 tupleLockExtraInfo[MaxLockTupleMode + 1] =
137 { /* LockTupleKeyShare */
139 MultiXactStatusForKeyShare,
140 -1 /* KeyShare does not allow updating tuples */
142 { /* LockTupleShare */
144 MultiXactStatusForShare,
145 -1 /* Share does not allow updating tuples */
147 { /* LockTupleNoKeyExclusive */
149 MultiXactStatusForNoKeyUpdate,
150 MultiXactStatusNoKeyUpdate
152 { /* LockTupleExclusive */
154 MultiXactStatusForUpdate,
155 MultiXactStatusUpdate
159 /* Get the LOCKMODE for a given MultiXactStatus */
160 #define LOCKMODE_from_mxstatus(status) \
161 (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
164 * Acquire heavyweight locks on tuples, using a LockTupleMode strength value.
165 * This is more readable than having every caller translate it to lock.h's
168 #define LockTupleTuplock(rel, tup, mode) \
169 LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
170 #define UnlockTupleTuplock(rel, tup, mode) \
171 UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
172 #define ConditionalLockTupleTuplock(rel, tup, mode) \
173 ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
176 * This table maps tuple lock strength values for each particular
177 * MultiXactStatus value.
179 static const int MultiXactStatusLock[MaxMultiXactStatus + 1] =
181 LockTupleKeyShare, /* ForKeyShare */
182 LockTupleShare, /* ForShare */
183 LockTupleNoKeyExclusive, /* ForNoKeyUpdate */
184 LockTupleExclusive, /* ForUpdate */
185 LockTupleNoKeyExclusive, /* NoKeyUpdate */
186 LockTupleExclusive /* Update */
189 /* Get the LockTupleMode for a given MultiXactStatus */
190 #define TUPLOCK_from_mxstatus(status) \
191 (MultiXactStatusLock[(status)])
193 /* ----------------------------------------------------------------
194 * heap support routines
195 * ----------------------------------------------------------------
199 * initscan - scan code common to heap_beginscan and heap_rescan
203 initscan(HeapScanDesc scan, ScanKey key, bool is_rescan)
209 * Determine the number of blocks we have to scan.
211 * It is sufficient to do this once at scan start, since any tuples added
212 * while the scan is in progress will be invisible to my snapshot anyway.
213 * (That is not true when using a non-MVCC snapshot. However, we couldn't
214 * guarantee to return tuples added after scan start anyway, since they
215 * might go into pages we already scanned. To guarantee consistent
216 * results for a non-MVCC snapshot, the caller must hold some higher-level
217 * lock that ensures the interesting tuple(s) won't change.)
219 scan->rs_nblocks = RelationGetNumberOfBlocks(scan->rs_rd);
222 * If the table is large relative to NBuffers, use a bulk-read access
223 * strategy and enable synchronized scanning (see syncscan.c). Although
224 * the thresholds for these features could be different, we make them the
225 * same so that there are only two behaviors to tune rather than four.
226 * (However, some callers need to be able to disable one or both of these
227 * behaviors, independently of the size of the table; also there is a GUC
228 * variable that can disable synchronized scanning.)
230 * During a rescan, don't make a new strategy object if we don't have to.
232 if (!RelationUsesLocalBuffers(scan->rs_rd) &&
233 scan->rs_nblocks > NBuffers / 4)
235 allow_strat = scan->rs_allow_strat;
236 allow_sync = scan->rs_allow_sync;
239 allow_strat = allow_sync = false;
243 if (scan->rs_strategy == NULL)
244 scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
248 if (scan->rs_strategy != NULL)
249 FreeAccessStrategy(scan->rs_strategy);
250 scan->rs_strategy = NULL;
256 * If rescan, keep the previous startblock setting so that rewinding a
257 * cursor doesn't generate surprising results. Reset the syncscan
260 scan->rs_syncscan = (allow_sync && synchronize_seqscans);
262 else if (allow_sync && synchronize_seqscans)
264 scan->rs_syncscan = true;
265 scan->rs_startblock = ss_get_location(scan->rs_rd, scan->rs_nblocks);
269 scan->rs_syncscan = false;
270 scan->rs_startblock = 0;
273 scan->rs_initblock = 0;
274 scan->rs_numblocks = InvalidBlockNumber;
275 scan->rs_inited = false;
276 scan->rs_ctup.t_data = NULL;
277 ItemPointerSetInvalid(&scan->rs_ctup.t_self);
278 scan->rs_cbuf = InvalidBuffer;
279 scan->rs_cblock = InvalidBlockNumber;
281 /* page-at-a-time fields are always invalid when not rs_inited */
284 * copy the scan key, if appropriate
287 memcpy(scan->rs_key, key, scan->rs_nkeys * sizeof(ScanKeyData));
290 * Currently, we don't have a stats counter for bitmap heap scans (but the
291 * underlying bitmap index scans will be counted).
293 if (!scan->rs_bitmapscan)
294 pgstat_count_heap_scan(scan->rs_rd);
298 heap_setscanlimits(HeapScanDesc scan, BlockNumber startBlk, BlockNumber numBlks)
300 scan->rs_startblock = startBlk;
301 scan->rs_initblock = startBlk;
302 scan->rs_numblocks = numBlks;
306 * heapgetpage - subroutine for heapgettup()
308 * This routine reads and pins the specified page of the relation.
309 * In page-at-a-time mode it performs additional work, namely determining
310 * which tuples on the page are visible.
313 heapgetpage(HeapScanDesc scan, BlockNumber page)
320 OffsetNumber lineoff;
324 Assert(page < scan->rs_nblocks);
326 /* release previous scan buffer, if any */
327 if (BufferIsValid(scan->rs_cbuf))
329 ReleaseBuffer(scan->rs_cbuf);
330 scan->rs_cbuf = InvalidBuffer;
334 * Be sure to check for interrupts at least once per page. Checks at
335 * higher code levels won't be able to stop a seqscan that encounters many
336 * pages' worth of consecutive dead tuples.
338 CHECK_FOR_INTERRUPTS();
340 /* read page using selected strategy */
341 scan->rs_cbuf = ReadBufferExtended(scan->rs_rd, MAIN_FORKNUM, page,
342 RBM_NORMAL, scan->rs_strategy);
343 scan->rs_cblock = page;
345 if (!scan->rs_pageatatime)
348 buffer = scan->rs_cbuf;
349 snapshot = scan->rs_snapshot;
352 * Prune and repair fragmentation for the whole page, if possible.
354 heap_page_prune_opt(scan->rs_rd, buffer);
357 * We must hold share lock on the buffer content while examining tuple
358 * visibility. Afterwards, however, the tuples we have found to be
359 * visible are guaranteed good as long as we hold the buffer pin.
361 LockBuffer(buffer, BUFFER_LOCK_SHARE);
363 dp = (Page) BufferGetPage(buffer);
364 lines = PageGetMaxOffsetNumber(dp);
368 * If the all-visible flag indicates that all tuples on the page are
369 * visible to everyone, we can skip the per-tuple visibility tests.
371 * Note: In hot standby, a tuple that's already visible to all
372 * transactions in the master might still be invisible to a read-only
373 * transaction in the standby. We partly handle this problem by tracking
374 * the minimum xmin of visible tuples as the cut-off XID while marking a
375 * page all-visible on master and WAL log that along with the visibility
376 * map SET operation. In hot standby, we wait for (or abort) all
377 * transactions that can potentially may not see one or more tuples on the
378 * page. That's how index-only scans work fine in hot standby. A crucial
379 * difference between index-only scans and heap scans is that the
380 * index-only scan completely relies on the visibility map where as heap
381 * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
382 * the page-level flag can be trusted in the same way, because it might
383 * get propagated somehow without being explicitly WAL-logged, e.g. via a
384 * full page write. Until we can prove that beyond doubt, let's check each
385 * tuple for visibility the hard way.
387 all_visible = PageIsAllVisible(dp) && !snapshot->takenDuringRecovery;
389 for (lineoff = FirstOffsetNumber, lpp = PageGetItemId(dp, lineoff);
393 if (ItemIdIsNormal(lpp))
395 HeapTupleData loctup;
398 loctup.t_tableOid = RelationGetRelid(scan->rs_rd);
399 loctup.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
400 loctup.t_len = ItemIdGetLength(lpp);
401 ItemPointerSet(&(loctup.t_self), page, lineoff);
406 valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
408 CheckForSerializableConflictOut(valid, scan->rs_rd, &loctup,
412 scan->rs_vistuples[ntup++] = lineoff;
416 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
418 Assert(ntup <= MaxHeapTuplesPerPage);
419 scan->rs_ntuples = ntup;
423 * heapgettup - fetch next heap tuple
425 * Initialize the scan if not already done; then advance to the next
426 * tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
427 * or set scan->rs_ctup.t_data = NULL if no more tuples.
429 * dir == NoMovementScanDirection means "re-fetch the tuple indicated
432 * Note: the reason nkeys/key are passed separately, even though they are
433 * kept in the scan descriptor, is that the caller may not want us to check
436 * Note: when we fall off the end of the scan in either direction, we
437 * reset rs_inited. This means that a further request with the same
438 * scan direction will restart the scan, which is a bit odd, but a
439 * request with the opposite scan direction will start a fresh scan
440 * in the proper direction. The latter is required behavior for cursors,
441 * while the former case is generally undefined behavior in Postgres
442 * so we don't care too much.
446 heapgettup(HeapScanDesc scan,
451 HeapTuple tuple = &(scan->rs_ctup);
452 Snapshot snapshot = scan->rs_snapshot;
453 bool backward = ScanDirectionIsBackward(dir);
458 OffsetNumber lineoff;
463 * calculate next starting lineoff, given scan direction
465 if (ScanDirectionIsForward(dir))
467 if (!scan->rs_inited)
470 * return null immediately if relation is empty
472 if (scan->rs_nblocks == 0)
474 Assert(!BufferIsValid(scan->rs_cbuf));
475 tuple->t_data = NULL;
478 page = scan->rs_startblock; /* first page */
479 heapgetpage(scan, page);
480 lineoff = FirstOffsetNumber; /* first offnum */
481 scan->rs_inited = true;
485 /* continue from previously returned page/tuple */
486 page = scan->rs_cblock; /* current page */
487 lineoff = /* next offnum */
488 OffsetNumberNext(ItemPointerGetOffsetNumber(&(tuple->t_self)));
491 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
493 dp = (Page) BufferGetPage(scan->rs_cbuf);
494 lines = PageGetMaxOffsetNumber(dp);
495 /* page and lineoff now reference the physically next tid */
497 linesleft = lines - lineoff + 1;
501 if (!scan->rs_inited)
504 * return null immediately if relation is empty
506 if (scan->rs_nblocks == 0)
508 Assert(!BufferIsValid(scan->rs_cbuf));
509 tuple->t_data = NULL;
514 * Disable reporting to syncscan logic in a backwards scan; it's
515 * not very likely anyone else is doing the same thing at the same
516 * time, and much more likely that we'll just bollix things for
519 scan->rs_syncscan = false;
520 /* start from last page of the scan */
521 if (scan->rs_startblock > 0)
522 page = scan->rs_startblock - 1;
524 page = scan->rs_nblocks - 1;
525 heapgetpage(scan, page);
529 /* continue from previously returned page/tuple */
530 page = scan->rs_cblock; /* current page */
533 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
535 dp = (Page) BufferGetPage(scan->rs_cbuf);
536 lines = PageGetMaxOffsetNumber(dp);
538 if (!scan->rs_inited)
540 lineoff = lines; /* final offnum */
541 scan->rs_inited = true;
545 lineoff = /* previous offnum */
546 OffsetNumberPrev(ItemPointerGetOffsetNumber(&(tuple->t_self)));
548 /* page and lineoff now reference the physically previous tid */
555 * ``no movement'' scan direction: refetch prior tuple
557 if (!scan->rs_inited)
559 Assert(!BufferIsValid(scan->rs_cbuf));
560 tuple->t_data = NULL;
564 page = ItemPointerGetBlockNumber(&(tuple->t_self));
565 if (page != scan->rs_cblock)
566 heapgetpage(scan, page);
568 /* Since the tuple was previously fetched, needn't lock page here */
569 dp = (Page) BufferGetPage(scan->rs_cbuf);
570 lineoff = ItemPointerGetOffsetNumber(&(tuple->t_self));
571 lpp = PageGetItemId(dp, lineoff);
572 Assert(ItemIdIsNormal(lpp));
574 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
575 tuple->t_len = ItemIdGetLength(lpp);
581 * advance the scan until we find a qualifying tuple or run out of stuff
584 lpp = PageGetItemId(dp, lineoff);
587 while (linesleft > 0)
589 if (ItemIdIsNormal(lpp))
593 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
594 tuple->t_len = ItemIdGetLength(lpp);
595 ItemPointerSet(&(tuple->t_self), page, lineoff);
598 * if current tuple qualifies, return it.
600 valid = HeapTupleSatisfiesVisibility(tuple,
604 CheckForSerializableConflictOut(valid, scan->rs_rd, tuple,
605 scan->rs_cbuf, snapshot);
607 if (valid && key != NULL)
608 HeapKeyTest(tuple, RelationGetDescr(scan->rs_rd),
613 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
619 * otherwise move to the next item on the page
624 --lpp; /* move back in this page's ItemId array */
629 ++lpp; /* move forward in this page's ItemId array */
635 * if we get here, it means we've exhausted the items on this page and
636 * it's time to move to the next.
638 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
641 * advance to next/prior page and detect end of scan
645 finished = (page == scan->rs_startblock) ||
646 (scan->rs_numblocks != InvalidBlockNumber ? --scan->rs_numblocks <= 0 : false);
648 page = scan->rs_nblocks;
654 if (page >= scan->rs_nblocks)
656 finished = (page == scan->rs_startblock) ||
657 (scan->rs_numblocks != InvalidBlockNumber ? --scan->rs_numblocks <= 0 : false);
660 * Report our new scan position for synchronization purposes. We
661 * don't do that when moving backwards, however. That would just
662 * mess up any other forward-moving scanners.
664 * Note: we do this before checking for end of scan so that the
665 * final state of the position hint is back at the start of the
666 * rel. That's not strictly necessary, but otherwise when you run
667 * the same query multiple times the starting position would shift
668 * a little bit backwards on every invocation, which is confusing.
669 * We don't guarantee any specific ordering in general, though.
671 if (scan->rs_syncscan)
672 ss_report_location(scan->rs_rd, page);
676 * return NULL if we've exhausted all the pages
680 if (BufferIsValid(scan->rs_cbuf))
681 ReleaseBuffer(scan->rs_cbuf);
682 scan->rs_cbuf = InvalidBuffer;
683 scan->rs_cblock = InvalidBlockNumber;
684 tuple->t_data = NULL;
685 scan->rs_inited = false;
689 heapgetpage(scan, page);
691 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
693 dp = (Page) BufferGetPage(scan->rs_cbuf);
694 lines = PageGetMaxOffsetNumber((Page) dp);
699 lpp = PageGetItemId(dp, lines);
703 lineoff = FirstOffsetNumber;
704 lpp = PageGetItemId(dp, FirstOffsetNumber);
710 * heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
712 * Same API as heapgettup, but used in page-at-a-time mode
714 * The internal logic is much the same as heapgettup's too, but there are some
715 * differences: we do not take the buffer content lock (that only needs to
716 * happen inside heapgetpage), and we iterate through just the tuples listed
717 * in rs_vistuples[] rather than all tuples on the page. Notice that
718 * lineindex is 0-based, where the corresponding loop variable lineoff in
719 * heapgettup is 1-based.
723 heapgettup_pagemode(HeapScanDesc scan,
728 HeapTuple tuple = &(scan->rs_ctup);
729 bool backward = ScanDirectionIsBackward(dir);
735 OffsetNumber lineoff;
740 * calculate next starting lineindex, given scan direction
742 if (ScanDirectionIsForward(dir))
744 if (!scan->rs_inited)
747 * return null immediately if relation is empty
749 if (scan->rs_nblocks == 0)
751 Assert(!BufferIsValid(scan->rs_cbuf));
752 tuple->t_data = NULL;
755 page = scan->rs_startblock; /* first page */
756 heapgetpage(scan, page);
758 scan->rs_inited = true;
762 /* continue from previously returned page/tuple */
763 page = scan->rs_cblock; /* current page */
764 lineindex = scan->rs_cindex + 1;
767 dp = (Page) BufferGetPage(scan->rs_cbuf);
768 lines = scan->rs_ntuples;
769 /* page and lineindex now reference the next visible tid */
771 linesleft = lines - lineindex;
775 if (!scan->rs_inited)
778 * return null immediately if relation is empty
780 if (scan->rs_nblocks == 0)
782 Assert(!BufferIsValid(scan->rs_cbuf));
783 tuple->t_data = NULL;
788 * Disable reporting to syncscan logic in a backwards scan; it's
789 * not very likely anyone else is doing the same thing at the same
790 * time, and much more likely that we'll just bollix things for
793 scan->rs_syncscan = false;
794 /* start from last page of the scan */
795 if (scan->rs_startblock > 0)
796 page = scan->rs_startblock - 1;
798 page = scan->rs_nblocks - 1;
799 heapgetpage(scan, page);
803 /* continue from previously returned page/tuple */
804 page = scan->rs_cblock; /* current page */
807 dp = (Page) BufferGetPage(scan->rs_cbuf);
808 lines = scan->rs_ntuples;
810 if (!scan->rs_inited)
812 lineindex = lines - 1;
813 scan->rs_inited = true;
817 lineindex = scan->rs_cindex - 1;
819 /* page and lineindex now reference the previous visible tid */
821 linesleft = lineindex + 1;
826 * ``no movement'' scan direction: refetch prior tuple
828 if (!scan->rs_inited)
830 Assert(!BufferIsValid(scan->rs_cbuf));
831 tuple->t_data = NULL;
835 page = ItemPointerGetBlockNumber(&(tuple->t_self));
836 if (page != scan->rs_cblock)
837 heapgetpage(scan, page);
839 /* Since the tuple was previously fetched, needn't lock page here */
840 dp = (Page) BufferGetPage(scan->rs_cbuf);
841 lineoff = ItemPointerGetOffsetNumber(&(tuple->t_self));
842 lpp = PageGetItemId(dp, lineoff);
843 Assert(ItemIdIsNormal(lpp));
845 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
846 tuple->t_len = ItemIdGetLength(lpp);
848 /* check that rs_cindex is in sync */
849 Assert(scan->rs_cindex < scan->rs_ntuples);
850 Assert(lineoff == scan->rs_vistuples[scan->rs_cindex]);
856 * advance the scan until we find a qualifying tuple or run out of stuff
861 while (linesleft > 0)
863 lineoff = scan->rs_vistuples[lineindex];
864 lpp = PageGetItemId(dp, lineoff);
865 Assert(ItemIdIsNormal(lpp));
867 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
868 tuple->t_len = ItemIdGetLength(lpp);
869 ItemPointerSet(&(tuple->t_self), page, lineoff);
872 * if current tuple qualifies, return it.
878 HeapKeyTest(tuple, RelationGetDescr(scan->rs_rd),
882 scan->rs_cindex = lineindex;
888 scan->rs_cindex = lineindex;
893 * otherwise move to the next item on the page
903 * if we get here, it means we've exhausted the items on this page and
904 * it's time to move to the next.
908 finished = (page == scan->rs_startblock) ||
909 (scan->rs_numblocks != InvalidBlockNumber ? --scan->rs_numblocks <= 0 : false);
911 page = scan->rs_nblocks;
917 if (page >= scan->rs_nblocks)
919 finished = (page == scan->rs_startblock) ||
920 (scan->rs_numblocks != InvalidBlockNumber ? --scan->rs_numblocks <= 0 : false);
923 * Report our new scan position for synchronization purposes. We
924 * don't do that when moving backwards, however. That would just
925 * mess up any other forward-moving scanners.
927 * Note: we do this before checking for end of scan so that the
928 * final state of the position hint is back at the start of the
929 * rel. That's not strictly necessary, but otherwise when you run
930 * the same query multiple times the starting position would shift
931 * a little bit backwards on every invocation, which is confusing.
932 * We don't guarantee any specific ordering in general, though.
934 if (scan->rs_syncscan)
935 ss_report_location(scan->rs_rd, page);
939 * return NULL if we've exhausted all the pages
943 if (BufferIsValid(scan->rs_cbuf))
944 ReleaseBuffer(scan->rs_cbuf);
945 scan->rs_cbuf = InvalidBuffer;
946 scan->rs_cblock = InvalidBlockNumber;
947 tuple->t_data = NULL;
948 scan->rs_inited = false;
952 heapgetpage(scan, page);
954 dp = (Page) BufferGetPage(scan->rs_cbuf);
955 lines = scan->rs_ntuples;
958 lineindex = lines - 1;
965 #if defined(DISABLE_COMPLEX_MACRO)
967 * This is formatted so oddly so that the correspondence to the macro
968 * definition in access/htup_details.h is maintained.
971 fastgetattr(HeapTuple tup, int attnum, TupleDesc tupleDesc,
978 HeapTupleNoNulls(tup) ?
980 (tupleDesc)->attrs[(attnum) - 1]->attcacheoff >= 0 ?
982 fetchatt((tupleDesc)->attrs[(attnum) - 1],
983 (char *) (tup)->t_data + (tup)->t_data->t_hoff +
984 (tupleDesc)->attrs[(attnum) - 1]->attcacheoff)
987 nocachegetattr((tup), (attnum), (tupleDesc))
991 att_isnull((attnum) - 1, (tup)->t_data->t_bits) ?
998 nocachegetattr((tup), (attnum), (tupleDesc))
1008 #endif /* defined(DISABLE_COMPLEX_MACRO) */
1011 /* ----------------------------------------------------------------
1012 * heap access method interface
1013 * ----------------------------------------------------------------
1017 * relation_open - open any relation by relation OID
1019 * If lockmode is not "NoLock", the specified kind of lock is
1020 * obtained on the relation. (Generally, NoLock should only be
1021 * used if the caller knows it has some appropriate lock on the
1022 * relation already.)
1024 * An error is raised if the relation does not exist.
1026 * NB: a "relation" is anything with a pg_class entry. The caller is
1027 * expected to check whether the relkind is something it can handle.
1031 relation_open(Oid relationId, LOCKMODE lockmode)
1035 Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
1037 /* Get the lock before trying to open the relcache entry */
1038 if (lockmode != NoLock)
1039 LockRelationOid(relationId, lockmode);
1041 /* The relcache does all the real work... */
1042 r = RelationIdGetRelation(relationId);
1044 if (!RelationIsValid(r))
1045 elog(ERROR, "could not open relation with OID %u", relationId);
1047 /* Make note that we've accessed a temporary relation */
1048 if (RelationUsesLocalBuffers(r))
1049 MyXactAccessedTempRel = true;
1051 pgstat_initstats(r);
1057 * try_relation_open - open any relation by relation OID
1059 * Same as relation_open, except return NULL instead of failing
1060 * if the relation does not exist.
1064 try_relation_open(Oid relationId, LOCKMODE lockmode)
1068 Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
1070 /* Get the lock first */
1071 if (lockmode != NoLock)
1072 LockRelationOid(relationId, lockmode);
1075 * Now that we have the lock, probe to see if the relation really exists
1078 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relationId)))
1080 /* Release useless lock */
1081 if (lockmode != NoLock)
1082 UnlockRelationOid(relationId, lockmode);
1087 /* Should be safe to do a relcache load */
1088 r = RelationIdGetRelation(relationId);
1090 if (!RelationIsValid(r))
1091 elog(ERROR, "could not open relation with OID %u", relationId);
1093 /* Make note that we've accessed a temporary relation */
1094 if (RelationUsesLocalBuffers(r))
1095 MyXactAccessedTempRel = true;
1097 pgstat_initstats(r);
1103 * relation_openrv - open any relation specified by a RangeVar
1105 * Same as relation_open, but the relation is specified by a RangeVar.
1109 relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
1114 * Check for shared-cache-inval messages before trying to open the
1115 * relation. This is needed even if we already hold a lock on the
1116 * relation, because GRANT/REVOKE are executed without taking any lock on
1117 * the target relation, and we want to be sure we see current ACL
1118 * information. We can skip this if asked for NoLock, on the assumption
1119 * that such a call is not the first one in the current command, and so we
1120 * should be reasonably up-to-date already. (XXX this all could stand to
1121 * be redesigned, but for the moment we'll keep doing this like it's been
1122 * done historically.)
1124 if (lockmode != NoLock)
1125 AcceptInvalidationMessages();
1127 /* Look up and lock the appropriate relation using namespace search */
1128 relOid = RangeVarGetRelid(relation, lockmode, false);
1130 /* Let relation_open do the rest */
1131 return relation_open(relOid, NoLock);
1135 * relation_openrv_extended - open any relation specified by a RangeVar
1137 * Same as relation_openrv, but with an additional missing_ok argument
1138 * allowing a NULL return rather than an error if the relation is not
1139 * found. (Note that some other causes, such as permissions problems,
1140 * will still result in an ereport.)
1144 relation_openrv_extended(const RangeVar *relation, LOCKMODE lockmode,
1150 * Check for shared-cache-inval messages before trying to open the
1151 * relation. See comments in relation_openrv().
1153 if (lockmode != NoLock)
1154 AcceptInvalidationMessages();
1156 /* Look up and lock the appropriate relation using namespace search */
1157 relOid = RangeVarGetRelid(relation, lockmode, missing_ok);
1159 /* Return NULL on not-found */
1160 if (!OidIsValid(relOid))
1163 /* Let relation_open do the rest */
1164 return relation_open(relOid, NoLock);
1168 * relation_close - close any relation
1170 * If lockmode is not "NoLock", we then release the specified lock.
1172 * Note that it is often sensible to hold a lock beyond relation_close;
1173 * in that case, the lock is released automatically at xact end.
1177 relation_close(Relation relation, LOCKMODE lockmode)
1179 LockRelId relid = relation->rd_lockInfo.lockRelId;
1181 Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
1183 /* The relcache does the real work... */
1184 RelationClose(relation);
1186 if (lockmode != NoLock)
1187 UnlockRelationId(&relid, lockmode);
1192 * heap_open - open a heap relation by relation OID
1194 * This is essentially relation_open plus check that the relation
1195 * is not an index nor a composite type. (The caller should also
1196 * check that it's not a view or foreign table before assuming it has
1201 heap_open(Oid relationId, LOCKMODE lockmode)
1205 r = relation_open(relationId, lockmode);
1207 if (r->rd_rel->relkind == RELKIND_INDEX)
1209 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1210 errmsg("\"%s\" is an index",
1211 RelationGetRelationName(r))));
1212 else if (r->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1214 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1215 errmsg("\"%s\" is a composite type",
1216 RelationGetRelationName(r))));
1222 * heap_openrv - open a heap relation specified
1223 * by a RangeVar node
1225 * As above, but relation is specified by a RangeVar.
1229 heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
1233 r = relation_openrv(relation, lockmode);
1235 if (r->rd_rel->relkind == RELKIND_INDEX)
1237 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1238 errmsg("\"%s\" is an index",
1239 RelationGetRelationName(r))));
1240 else if (r->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1242 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1243 errmsg("\"%s\" is a composite type",
1244 RelationGetRelationName(r))));
1250 * heap_openrv_extended - open a heap relation specified
1251 * by a RangeVar node
1253 * As above, but optionally return NULL instead of failing for
1254 * relation-not-found.
1258 heap_openrv_extended(const RangeVar *relation, LOCKMODE lockmode,
1263 r = relation_openrv_extended(relation, lockmode, missing_ok);
1267 if (r->rd_rel->relkind == RELKIND_INDEX)
1269 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1270 errmsg("\"%s\" is an index",
1271 RelationGetRelationName(r))));
1272 else if (r->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1274 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1275 errmsg("\"%s\" is a composite type",
1276 RelationGetRelationName(r))));
1284 * heap_beginscan - begin relation scan
1286 * heap_beginscan_strat offers an extended API that lets the caller control
1287 * whether a nondefault buffer access strategy can be used, and whether
1288 * syncscan can be chosen (possibly resulting in the scan not starting from
1289 * block zero). Both of these default to TRUE with plain heap_beginscan.
1291 * heap_beginscan_bm is an alternative entry point for setting up a
1292 * HeapScanDesc for a bitmap heap scan. Although that scan technology is
1293 * really quite unlike a standard seqscan, there is just enough commonality
1294 * to make it worth using the same data structure.
1298 heap_beginscan(Relation relation, Snapshot snapshot,
1299 int nkeys, ScanKey key)
1301 return heap_beginscan_internal(relation, snapshot, nkeys, key,
1302 true, true, false, false);
1306 heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
1308 Oid relid = RelationGetRelid(relation);
1309 Snapshot snapshot = RegisterSnapshot(GetCatalogSnapshot(relid));
1311 return heap_beginscan_internal(relation, snapshot, nkeys, key,
1312 true, true, false, true);
1316 heap_beginscan_strat(Relation relation, Snapshot snapshot,
1317 int nkeys, ScanKey key,
1318 bool allow_strat, bool allow_sync)
1320 return heap_beginscan_internal(relation, snapshot, nkeys, key,
1321 allow_strat, allow_sync, false, false);
1325 heap_beginscan_bm(Relation relation, Snapshot snapshot,
1326 int nkeys, ScanKey key)
1328 return heap_beginscan_internal(relation, snapshot, nkeys, key,
1329 false, false, true, false);
1333 heap_beginscan_internal(Relation relation, Snapshot snapshot,
1334 int nkeys, ScanKey key,
1335 bool allow_strat, bool allow_sync,
1336 bool is_bitmapscan, bool temp_snap)
1341 * increment relation ref count while scanning relation
1343 * This is just to make really sure the relcache entry won't go away while
1344 * the scan has a pointer to it. Caller should be holding the rel open
1345 * anyway, so this is redundant in all normal scenarios...
1347 RelationIncrementReferenceCount(relation);
1350 * allocate and initialize scan descriptor
1352 scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
1354 scan->rs_rd = relation;
1355 scan->rs_snapshot = snapshot;
1356 scan->rs_nkeys = nkeys;
1357 scan->rs_bitmapscan = is_bitmapscan;
1358 scan->rs_strategy = NULL; /* set in initscan */
1359 scan->rs_allow_strat = allow_strat;
1360 scan->rs_allow_sync = allow_sync;
1361 scan->rs_temp_snap = temp_snap;
1364 * we can use page-at-a-time mode if it's an MVCC-safe snapshot
1366 scan->rs_pageatatime = IsMVCCSnapshot(snapshot);
1369 * For a seqscan in a serializable transaction, acquire a predicate lock
1370 * on the entire relation. This is required not only to lock all the
1371 * matching tuples, but also to conflict with new insertions into the
1372 * table. In an indexscan, we take page locks on the index pages covering
1373 * the range specified in the scan qual, but in a heap scan there is
1374 * nothing more fine-grained to lock. A bitmap scan is a different story,
1375 * there we have already scanned the index and locked the index pages
1376 * covering the predicate. But in that case we still have to lock any
1377 * matching heap tuples.
1380 PredicateLockRelation(relation, snapshot);
1382 /* we only need to set this up once */
1383 scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1386 * we do this here instead of in initscan() because heap_rescan also calls
1387 * initscan() and we don't want to allocate memory again
1390 scan->rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
1392 scan->rs_key = NULL;
1394 initscan(scan, key, false);
1400 * heap_rescan - restart a relation scan
1404 heap_rescan(HeapScanDesc scan,
1408 * unpin scan buffers
1410 if (BufferIsValid(scan->rs_cbuf))
1411 ReleaseBuffer(scan->rs_cbuf);
1414 * reinitialize scan descriptor
1416 initscan(scan, key, true);
1420 * heap_endscan - end relation scan
1422 * See how to integrate with index scans.
1423 * Check handling if reldesc caching.
1427 heap_endscan(HeapScanDesc scan)
1429 /* Note: no locking manipulations needed */
1432 * unpin scan buffers
1434 if (BufferIsValid(scan->rs_cbuf))
1435 ReleaseBuffer(scan->rs_cbuf);
1438 * decrement relation reference count and free scan descriptor storage
1440 RelationDecrementReferenceCount(scan->rs_rd);
1443 pfree(scan->rs_key);
1445 if (scan->rs_strategy != NULL)
1446 FreeAccessStrategy(scan->rs_strategy);
1448 if (scan->rs_temp_snap)
1449 UnregisterSnapshot(scan->rs_snapshot);
1455 * heap_getnext - retrieve next tuple in scan
1457 * Fix to work with index relations.
1458 * We don't return the buffer anymore, but you can get it from the
1459 * returned HeapTuple.
1464 #define HEAPDEBUG_1 \
1465 elog(DEBUG2, "heap_getnext([%s,nkeys=%d],dir=%d) called", \
1466 RelationGetRelationName(scan->rs_rd), scan->rs_nkeys, (int) direction)
1467 #define HEAPDEBUG_2 \
1468 elog(DEBUG2, "heap_getnext returning EOS")
1469 #define HEAPDEBUG_3 \
1470 elog(DEBUG2, "heap_getnext returning tuple")
1475 #endif /* !defined(HEAPDEBUGALL) */
1479 heap_getnext(HeapScanDesc scan, ScanDirection direction)
1481 /* Note: no locking manipulations needed */
1483 HEAPDEBUG_1; /* heap_getnext( info ) */
1485 if (scan->rs_pageatatime)
1486 heapgettup_pagemode(scan, direction,
1487 scan->rs_nkeys, scan->rs_key);
1489 heapgettup(scan, direction, scan->rs_nkeys, scan->rs_key);
1491 if (scan->rs_ctup.t_data == NULL)
1493 HEAPDEBUG_2; /* heap_getnext returning EOS */
1498 * if we get here it means we have a new current scan tuple, so point to
1499 * the proper return buffer and return the tuple.
1501 HEAPDEBUG_3; /* heap_getnext returning tuple */
1503 pgstat_count_heap_getnext(scan->rs_rd);
1505 return &(scan->rs_ctup);
1509 * heap_fetch - retrieve tuple with given tid
1511 * On entry, tuple->t_self is the TID to fetch. We pin the buffer holding
1512 * the tuple, fill in the remaining fields of *tuple, and check the tuple
1513 * against the specified snapshot.
1515 * If successful (tuple found and passes snapshot time qual), then *userbuf
1516 * is set to the buffer holding the tuple and TRUE is returned. The caller
1517 * must unpin the buffer when done with the tuple.
1519 * If the tuple is not found (ie, item number references a deleted slot),
1520 * then tuple->t_data is set to NULL and FALSE is returned.
1522 * If the tuple is found but fails the time qual check, then FALSE is returned
1523 * but tuple->t_data is left pointing to the tuple.
1525 * keep_buf determines what is done with the buffer in the FALSE-result cases.
1526 * When the caller specifies keep_buf = true, we retain the pin on the buffer
1527 * and return it in *userbuf (so the caller must eventually unpin it); when
1528 * keep_buf = false, the pin is released and *userbuf is set to InvalidBuffer.
1530 * stats_relation is the relation to charge the heap_fetch operation against
1531 * for statistical purposes. (This could be the heap rel itself, an
1532 * associated index, or NULL to not count the fetch at all.)
1534 * heap_fetch does not follow HOT chains: only the exact TID requested will
1537 * It is somewhat inconsistent that we ereport() on invalid block number but
1538 * return false on invalid item number. There are a couple of reasons though.
1539 * One is that the caller can relatively easily check the block number for
1540 * validity, but cannot check the item number without reading the page
1541 * himself. Another is that when we are following a t_ctid link, we can be
1542 * reasonably confident that the page number is valid (since VACUUM shouldn't
1543 * truncate off the destination page without having killed the referencing
1544 * tuple first), but the item number might well not be good.
1547 heap_fetch(Relation relation,
1552 Relation stats_relation)
1554 ItemPointer tid = &(tuple->t_self);
1558 OffsetNumber offnum;
1562 * Fetch and pin the appropriate page of the relation.
1564 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1567 * Need share lock on buffer to examine tuple commit status.
1569 LockBuffer(buffer, BUFFER_LOCK_SHARE);
1570 page = BufferGetPage(buffer);
1573 * We'd better check for out-of-range offnum in case of VACUUM since the
1576 offnum = ItemPointerGetOffsetNumber(tid);
1577 if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1579 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1584 ReleaseBuffer(buffer);
1585 *userbuf = InvalidBuffer;
1587 tuple->t_data = NULL;
1592 * get the item line pointer corresponding to the requested tid
1594 lp = PageGetItemId(page, offnum);
1597 * Must check for deleted tuple.
1599 if (!ItemIdIsNormal(lp))
1601 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1606 ReleaseBuffer(buffer);
1607 *userbuf = InvalidBuffer;
1609 tuple->t_data = NULL;
1614 * fill in *tuple fields
1616 tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1617 tuple->t_len = ItemIdGetLength(lp);
1618 tuple->t_tableOid = RelationGetRelid(relation);
1621 * check time qualification of tuple, then release lock
1623 valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1626 PredicateLockTuple(relation, tuple, snapshot);
1628 CheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1630 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1635 * All checks passed, so return the tuple as valid. Caller is now
1636 * responsible for releasing the buffer.
1640 /* Count the successful fetch against appropriate rel, if any */
1641 if (stats_relation != NULL)
1642 pgstat_count_heap_fetch(stats_relation);
1647 /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1652 ReleaseBuffer(buffer);
1653 *userbuf = InvalidBuffer;
1660 * heap_hot_search_buffer - search HOT chain for tuple satisfying snapshot
1662 * On entry, *tid is the TID of a tuple (either a simple tuple, or the root
1663 * of a HOT chain), and buffer is the buffer holding this tuple. We search
1664 * for the first chain member satisfying the given snapshot. If one is
1665 * found, we update *tid to reference that tuple's offset number, and
1666 * return TRUE. If no match, return FALSE without modifying *tid.
1668 * heapTuple is a caller-supplied buffer. When a match is found, we return
1669 * the tuple here, in addition to updating *tid. If no match is found, the
1670 * contents of this buffer on return are undefined.
1672 * If all_dead is not NULL, we check non-visible tuples to see if they are
1673 * globally dead; *all_dead is set TRUE if all members of the HOT chain
1674 * are vacuumable, FALSE if not.
1676 * Unlike heap_fetch, the caller must already have pin and (at least) share
1677 * lock on the buffer; it is still pinned/locked at exit. Also unlike
1678 * heap_fetch, we do not report any pgstats count; caller may do so if wanted.
1681 heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer,
1682 Snapshot snapshot, HeapTuple heapTuple,
1683 bool *all_dead, bool first_call)
1685 Page dp = (Page) BufferGetPage(buffer);
1686 TransactionId prev_xmax = InvalidTransactionId;
1687 OffsetNumber offnum;
1688 bool at_chain_start;
1692 /* If this is not the first call, previous call returned a (live!) tuple */
1694 *all_dead = first_call;
1696 Assert(TransactionIdIsValid(RecentGlobalXmin));
1698 Assert(ItemPointerGetBlockNumber(tid) == BufferGetBlockNumber(buffer));
1699 offnum = ItemPointerGetOffsetNumber(tid);
1700 at_chain_start = first_call;
1703 heapTuple->t_self = *tid;
1705 /* Scan through possible multiple members of HOT-chain */
1710 /* check for bogus TID */
1711 if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(dp))
1714 lp = PageGetItemId(dp, offnum);
1716 /* check for unused, dead, or redirected items */
1717 if (!ItemIdIsNormal(lp))
1719 /* We should only see a redirect at start of chain */
1720 if (ItemIdIsRedirected(lp) && at_chain_start)
1722 /* Follow the redirect */
1723 offnum = ItemIdGetRedirect(lp);
1724 at_chain_start = false;
1727 /* else must be end of chain */
1731 heapTuple->t_data = (HeapTupleHeader) PageGetItem(dp, lp);
1732 heapTuple->t_len = ItemIdGetLength(lp);
1733 heapTuple->t_tableOid = RelationGetRelid(relation);
1734 ItemPointerSetOffsetNumber(&heapTuple->t_self, offnum);
1737 * Shouldn't see a HEAP_ONLY tuple at chain start.
1739 if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
1743 * The xmin should match the previous xmax value, else chain is
1746 if (TransactionIdIsValid(prev_xmax) &&
1747 !TransactionIdEquals(prev_xmax,
1748 HeapTupleHeaderGetXmin(heapTuple->t_data)))
1752 * When first_call is true (and thus, skip is initially false) we'll
1753 * return the first tuple we find. But on later passes, heapTuple
1754 * will initially be pointing to the tuple we returned last time.
1755 * Returning it again would be incorrect (and would loop forever), so
1756 * we skip it and return the next match we find.
1761 * For the benefit of logical decoding, have t_self point at the
1762 * element of the HOT chain we're currently investigating instead
1763 * of the root tuple of the HOT chain. This is important because
1764 * the *Satisfies routine for historical mvcc snapshots needs the
1765 * correct tid to decide about the visibility in some cases.
1767 ItemPointerSet(&(heapTuple->t_self), BufferGetBlockNumber(buffer), offnum);
1769 /* If it's visible per the snapshot, we must return it */
1770 valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
1771 CheckForSerializableConflictOut(valid, relation, heapTuple,
1773 /* reset to original, non-redirected, tid */
1774 heapTuple->t_self = *tid;
1778 ItemPointerSetOffsetNumber(tid, offnum);
1779 PredicateLockTuple(relation, heapTuple, snapshot);
1788 * If we can't see it, maybe no one else can either. At caller
1789 * request, check whether all chain members are dead to all
1792 if (all_dead && *all_dead &&
1793 !HeapTupleIsSurelyDead(heapTuple, RecentGlobalXmin))
1797 * Check to see if HOT chain continues past this tuple; if so fetch
1798 * the next offnum and loop around.
1800 if (HeapTupleIsHotUpdated(heapTuple))
1802 Assert(ItemPointerGetBlockNumber(&heapTuple->t_data->t_ctid) ==
1803 ItemPointerGetBlockNumber(tid));
1804 offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
1805 at_chain_start = false;
1806 prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
1809 break; /* end of chain */
1816 * heap_hot_search - search HOT chain for tuple satisfying snapshot
1818 * This has the same API as heap_hot_search_buffer, except that the caller
1819 * does not provide the buffer containing the page, rather we access it
1823 heap_hot_search(ItemPointer tid, Relation relation, Snapshot snapshot,
1828 HeapTupleData heapTuple;
1830 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1831 LockBuffer(buffer, BUFFER_LOCK_SHARE);
1832 result = heap_hot_search_buffer(tid, relation, buffer, snapshot,
1833 &heapTuple, all_dead, true);
1834 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1835 ReleaseBuffer(buffer);
1840 * heap_get_latest_tid - get the latest tid of a specified tuple
1842 * Actually, this gets the latest version that is visible according to
1843 * the passed snapshot. You can pass SnapshotDirty to get the very latest,
1844 * possibly uncommitted version.
1846 * *tid is both an input and an output parameter: it is updated to
1847 * show the latest version of the row. Note that it will not be changed
1848 * if no version of the row passes the snapshot test.
1851 heap_get_latest_tid(Relation relation,
1856 ItemPointerData ctid;
1857 TransactionId priorXmax;
1859 /* this is to avoid Assert failures on bad input */
1860 if (!ItemPointerIsValid(tid))
1864 * Since this can be called with user-supplied TID, don't trust the input
1865 * too much. (RelationGetNumberOfBlocks is an expensive check, so we
1866 * don't check t_ctid links again this way. Note that it would not do to
1867 * call it just once and save the result, either.)
1869 blk = ItemPointerGetBlockNumber(tid);
1870 if (blk >= RelationGetNumberOfBlocks(relation))
1871 elog(ERROR, "block number %u is out of range for relation \"%s\"",
1872 blk, RelationGetRelationName(relation));
1875 * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1876 * need to examine, and *tid is the TID we will return if ctid turns out
1879 * Note that we will loop until we reach the end of the t_ctid chain.
1880 * Depending on the snapshot passed, there might be at most one visible
1881 * version of the row, but we don't try to optimize for that.
1884 priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1889 OffsetNumber offnum;
1895 * Read, pin, and lock the page.
1897 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1898 LockBuffer(buffer, BUFFER_LOCK_SHARE);
1899 page = BufferGetPage(buffer);
1902 * Check for bogus item number. This is not treated as an error
1903 * condition because it can happen while following a t_ctid link. We
1904 * just assume that the prior tid is OK and return it unchanged.
1906 offnum = ItemPointerGetOffsetNumber(&ctid);
1907 if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1909 UnlockReleaseBuffer(buffer);
1912 lp = PageGetItemId(page, offnum);
1913 if (!ItemIdIsNormal(lp))
1915 UnlockReleaseBuffer(buffer);
1919 /* OK to access the tuple */
1921 tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
1922 tp.t_len = ItemIdGetLength(lp);
1923 tp.t_tableOid = RelationGetRelid(relation);
1926 * After following a t_ctid link, we might arrive at an unrelated
1927 * tuple. Check for XMIN match.
1929 if (TransactionIdIsValid(priorXmax) &&
1930 !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
1932 UnlockReleaseBuffer(buffer);
1937 * Check time qualification of tuple; if visible, set it as the new
1940 valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
1941 CheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
1946 * If there's a valid t_ctid link, follow it, else we're done.
1948 if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1949 HeapTupleHeaderIsOnlyLocked(tp.t_data) ||
1950 ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
1952 UnlockReleaseBuffer(buffer);
1956 ctid = tp.t_data->t_ctid;
1957 priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
1958 UnlockReleaseBuffer(buffer);
1964 * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
1966 * This is called after we have waited for the XMAX transaction to terminate.
1967 * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
1968 * be set on exit. If the transaction committed, we set the XMAX_COMMITTED
1969 * hint bit if possible --- but beware that that may not yet be possible,
1970 * if the transaction committed asynchronously.
1972 * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
1973 * even if it commits.
1975 * Hence callers should look only at XMAX_INVALID.
1977 * Note this is not allowed for tuples whose xmax is a multixact.
1980 UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
1982 Assert(TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple), xid));
1983 Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
1985 if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
1987 if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
1988 TransactionIdDidCommit(xid))
1989 HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
1992 HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
1993 InvalidTransactionId);
1999 * GetBulkInsertState - prepare status object for a bulk insert
2002 GetBulkInsertState(void)
2004 BulkInsertState bistate;
2006 bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
2007 bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
2008 bistate->current_buf = InvalidBuffer;
2013 * FreeBulkInsertState - clean up after finishing a bulk insert
2016 FreeBulkInsertState(BulkInsertState bistate)
2018 if (bistate->current_buf != InvalidBuffer)
2019 ReleaseBuffer(bistate->current_buf);
2020 FreeAccessStrategy(bistate->strategy);
2026 * heap_insert - insert tuple into a heap
2028 * The new tuple is stamped with current transaction ID and the specified
2031 * If the HEAP_INSERT_SKIP_WAL option is specified, the new tuple is not
2032 * logged in WAL, even for a non-temp relation. Safe usage of this behavior
2033 * requires that we arrange that all new tuples go into new pages not
2034 * containing any tuples from other transactions, and that the relation gets
2035 * fsync'd before commit. (See also heap_sync() comments)
2037 * The HEAP_INSERT_SKIP_FSM option is passed directly to
2038 * RelationGetBufferForTuple, which see for more info.
2040 * HEAP_INSERT_FROZEN should only be specified for inserts into
2041 * relfilenodes created during the current subtransaction and when
2042 * there are no prior snapshots or pre-existing portals open.
2043 * This causes rows to be frozen, which is an MVCC violation and
2044 * requires explicit options chosen by user.
2046 * Note that these options will be applied when inserting into the heap's
2047 * TOAST table, too, if the tuple requires any out-of-line data.
2049 * The BulkInsertState object (if any; bistate can be NULL for default
2050 * behavior) is also just passed through to RelationGetBufferForTuple.
2052 * The return value is the OID assigned to the tuple (either here or by the
2053 * caller), or InvalidOid if no OID. The header fields of *tup are updated
2054 * to match the stored tuple; in particular tup->t_self receives the actual
2055 * TID where the tuple was stored. But note that any toasting of fields
2056 * within the tuple data is NOT reflected into *tup.
2059 heap_insert(Relation relation, HeapTuple tup, CommandId cid,
2060 int options, BulkInsertState bistate)
2062 TransactionId xid = GetCurrentTransactionId();
2065 Buffer vmbuffer = InvalidBuffer;
2066 bool all_visible_cleared = false;
2069 * Fill in tuple header fields, assign an OID, and toast the tuple if
2072 * Note: below this point, heaptup is the data we actually intend to store
2073 * into the relation; tup is the caller's original untoasted data.
2075 heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2078 * We're about to do the actual insert -- but check for conflict first, to
2079 * avoid possibly having to roll back work we've just done.
2081 * For a heap insert, we only need to check for table-level SSI locks. Our
2082 * new tuple can't possibly conflict with existing tuple locks, and heap
2083 * page locks are only consolidated versions of tuple locks; they do not
2084 * lock "gaps" as index page locks do. So we don't need to identify a
2085 * buffer before making the call.
2087 CheckForSerializableConflictIn(relation, NULL, InvalidBuffer);
2090 * Find buffer to insert this tuple into. If the page is all visible,
2091 * this will also pin the requisite visibility map page.
2093 buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2094 InvalidBuffer, options, bistate,
2097 /* NO EREPORT(ERROR) from here till changes are logged */
2098 START_CRIT_SECTION();
2100 RelationPutHeapTuple(relation, buffer, heaptup);
2102 if (PageIsAllVisible(BufferGetPage(buffer)))
2104 all_visible_cleared = true;
2105 PageClearAllVisible(BufferGetPage(buffer));
2106 visibilitymap_clear(relation,
2107 ItemPointerGetBlockNumber(&(heaptup->t_self)),
2112 * XXX Should we set PageSetPrunable on this page ?
2114 * The inserting transaction may eventually abort thus making this tuple
2115 * DEAD and hence available for pruning. Though we don't want to optimize
2116 * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
2117 * aborted tuple will never be pruned until next vacuum is triggered.
2119 * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
2122 MarkBufferDirty(buffer);
2125 if (!(options & HEAP_INSERT_SKIP_WAL) && RelationNeedsWAL(relation))
2127 xl_heap_insert xlrec;
2128 xl_heap_header xlhdr;
2130 Page page = BufferGetPage(buffer);
2131 uint8 info = XLOG_HEAP_INSERT;
2135 * If this is a catalog, we need to transmit combocids to properly
2136 * decode, so log that as well.
2138 if (RelationIsAccessibleInLogicalDecoding(relation))
2139 log_heap_new_cid(relation, heaptup);
2142 * If this is the single and first tuple on page, we can reinit the
2143 * page instead of restoring the whole thing. Set flag, and hide
2144 * buffer references from XLogInsert.
2146 if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2147 PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
2149 info |= XLOG_HEAP_INIT_PAGE;
2150 bufflags |= REGBUF_WILL_INIT;
2153 xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
2154 xlrec.flags = all_visible_cleared ? XLOG_HEAP_ALL_VISIBLE_CLEARED : 0;
2155 Assert(ItemPointerGetBlockNumber(&heaptup->t_self) == BufferGetBlockNumber(buffer));
2158 * For logical decoding, we need the tuple even if we're doing a full
2159 * page write, so make sure it's included even if we take a full-page
2160 * image. (XXX We could alternatively store a pointer into the FPW).
2162 if (RelationIsLogicallyLogged(relation))
2164 xlrec.flags |= XLOG_HEAP_CONTAINS_NEW_TUPLE;
2165 bufflags |= REGBUF_KEEP_DATA;
2169 XLogRegisterData((char *) &xlrec, SizeOfHeapInsert);
2171 xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2172 xlhdr.t_infomask = heaptup->t_data->t_infomask;
2173 xlhdr.t_hoff = heaptup->t_data->t_hoff;
2176 * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2177 * write the whole page to the xlog, we don't need to store
2178 * xl_heap_header in the xlog.
2180 XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2181 XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
2182 /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2183 XLogRegisterBufData(0,
2184 (char *) heaptup->t_data + offsetof(HeapTupleHeaderData, t_bits),
2185 heaptup->t_len - offsetof(HeapTupleHeaderData, t_bits));
2187 recptr = XLogInsert(RM_HEAP_ID, info);
2189 PageSetLSN(page, recptr);
2194 UnlockReleaseBuffer(buffer);
2195 if (vmbuffer != InvalidBuffer)
2196 ReleaseBuffer(vmbuffer);
2199 * If tuple is cachable, mark it for invalidation from the caches in case
2200 * we abort. Note it is OK to do this after releasing the buffer, because
2201 * the heaptup data structure is all in local memory, not in the shared
2204 CacheInvalidateHeapTuple(relation, heaptup, NULL);
2206 pgstat_count_heap_insert(relation, 1);
2209 * If heaptup is a private copy, release it. Don't forget to copy t_self
2210 * back to the caller's image, too.
2214 tup->t_self = heaptup->t_self;
2215 heap_freetuple(heaptup);
2218 return HeapTupleGetOid(tup);
2222 * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
2223 * tuple header fields, assigns an OID, and toasts the tuple if necessary.
2224 * Returns a toasted version of the tuple if it was toasted, or the original
2225 * tuple if not. Note that in any case, the header fields are also set in
2226 * the original tuple.
2229 heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
2230 CommandId cid, int options)
2232 if (relation->rd_rel->relhasoids)
2235 /* this is redundant with an Assert in HeapTupleSetOid */
2236 Assert(tup->t_data->t_infomask & HEAP_HASOID);
2240 * If the object id of this tuple has already been assigned, trust the
2241 * caller. There are a couple of ways this can happen. At initial db
2242 * creation, the backend program sets oids for tuples. When we define
2243 * an index, we set the oid. Finally, in the future, we may allow
2244 * users to set their own object ids in order to support a persistent
2245 * object store (objects need to contain pointers to one another).
2247 if (!OidIsValid(HeapTupleGetOid(tup)))
2248 HeapTupleSetOid(tup, GetNewOid(relation));
2252 /* check there is not space for an OID */
2253 Assert(!(tup->t_data->t_infomask & HEAP_HASOID));
2256 tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2257 tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2258 tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
2259 HeapTupleHeaderSetXmin(tup->t_data, xid);
2260 if (options & HEAP_INSERT_FROZEN)
2261 HeapTupleHeaderSetXminFrozen(tup->t_data);
2263 HeapTupleHeaderSetCmin(tup->t_data, cid);
2264 HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
2265 tup->t_tableOid = RelationGetRelid(relation);
2268 * If the new tuple is too big for storage or contains already toasted
2269 * out-of-line attributes from some other relation, invoke the toaster.
2271 if (relation->rd_rel->relkind != RELKIND_RELATION &&
2272 relation->rd_rel->relkind != RELKIND_MATVIEW)
2274 /* toast table entries should never be recursively toasted */
2275 Assert(!HeapTupleHasExternal(tup));
2278 else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2279 return toast_insert_or_update(relation, tup, NULL, options);
2285 * heap_multi_insert - insert multiple tuple into a heap
2287 * This is like heap_insert(), but inserts multiple tuples in one operation.
2288 * That's faster than calling heap_insert() in a loop, because when multiple
2289 * tuples can be inserted on a single page, we can write just a single WAL
2290 * record covering all of them, and only need to lock/unlock the page once.
2292 * Note: this leaks memory into the current memory context. You can create a
2293 * temporary context before calling this, if that's a problem.
2296 heap_multi_insert(Relation relation, HeapTuple *tuples, int ntuples,
2297 CommandId cid, int options, BulkInsertState bistate)
2299 TransactionId xid = GetCurrentTransactionId();
2300 HeapTuple *heaptuples;
2303 char *scratch = NULL;
2307 bool need_tuple_data = RelationIsLogicallyLogged(relation);
2308 bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
2310 needwal = !(options & HEAP_INSERT_SKIP_WAL) && RelationNeedsWAL(relation);
2311 saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2312 HEAP_DEFAULT_FILLFACTOR);
2314 /* Toast and set header data in all the tuples */
2315 heaptuples = palloc(ntuples * sizeof(HeapTuple));
2316 for (i = 0; i < ntuples; i++)
2317 heaptuples[i] = heap_prepare_insert(relation, tuples[i],
2321 * Allocate some memory to use for constructing the WAL record. Using
2322 * palloc() within a critical section is not safe, so we allocate this
2326 scratch = palloc(BLCKSZ);
2329 * We're about to do the actual inserts -- but check for conflict first,
2330 * to avoid possibly having to roll back work we've just done.
2332 * For a heap insert, we only need to check for table-level SSI locks. Our
2333 * new tuple can't possibly conflict with existing tuple locks, and heap
2334 * page locks are only consolidated versions of tuple locks; they do not
2335 * lock "gaps" as index page locks do. So we don't need to identify a
2336 * buffer before making the call.
2338 CheckForSerializableConflictIn(relation, NULL, InvalidBuffer);
2341 while (ndone < ntuples)
2344 Buffer vmbuffer = InvalidBuffer;
2345 bool all_visible_cleared = false;
2348 CHECK_FOR_INTERRUPTS();
2351 * Find buffer where at least the next tuple will fit. If the page is
2352 * all-visible, this will also pin the requisite visibility map page.
2354 buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2355 InvalidBuffer, options, bistate,
2357 page = BufferGetPage(buffer);
2359 /* NO EREPORT(ERROR) from here till changes are logged */
2360 START_CRIT_SECTION();
2363 * RelationGetBufferForTuple has ensured that the first tuple fits.
2364 * Put that on the page, and then as many other tuples as fit.
2366 RelationPutHeapTuple(relation, buffer, heaptuples[ndone]);
2367 for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2369 HeapTuple heaptup = heaptuples[ndone + nthispage];
2371 if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
2374 RelationPutHeapTuple(relation, buffer, heaptup);
2377 * We don't use heap_multi_insert for catalog tuples yet, but
2378 * better be prepared...
2380 if (needwal && need_cids)
2381 log_heap_new_cid(relation, heaptup);
2384 if (PageIsAllVisible(page))
2386 all_visible_cleared = true;
2387 PageClearAllVisible(page);
2388 visibilitymap_clear(relation,
2389 BufferGetBlockNumber(buffer),
2394 * XXX Should we set PageSetPrunable on this page ? See heap_insert()
2397 MarkBufferDirty(buffer);
2403 xl_heap_multi_insert *xlrec;
2404 uint8 info = XLOG_HEAP2_MULTI_INSERT;
2407 char *scratchptr = scratch;
2412 * If the page was previously empty, we can reinit the page
2413 * instead of restoring the whole thing.
2415 init = (ItemPointerGetOffsetNumber(&(heaptuples[ndone]->t_self)) == FirstOffsetNumber &&
2416 PageGetMaxOffsetNumber(page) == FirstOffsetNumber + nthispage - 1);
2418 /* allocate xl_heap_multi_insert struct from the scratch area */
2419 xlrec = (xl_heap_multi_insert *) scratchptr;
2420 scratchptr += SizeOfHeapMultiInsert;
2423 * Allocate offsets array. Unless we're reinitializing the page,
2424 * in that case the tuples are stored in order starting at
2425 * FirstOffsetNumber and we don't need to store the offsets
2429 scratchptr += nthispage * sizeof(OffsetNumber);
2431 /* the rest of the scratch space is used for tuple data */
2432 tupledata = scratchptr;
2434 xlrec->flags = all_visible_cleared ? XLOG_HEAP_ALL_VISIBLE_CLEARED : 0;
2435 xlrec->ntuples = nthispage;
2438 * Write out an xl_multi_insert_tuple and the tuple data itself
2441 for (i = 0; i < nthispage; i++)
2443 HeapTuple heaptup = heaptuples[ndone + i];
2444 xl_multi_insert_tuple *tuphdr;
2448 xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2449 /* xl_multi_insert_tuple needs two-byte alignment. */
2450 tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2451 scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2453 tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2454 tuphdr->t_infomask = heaptup->t_data->t_infomask;
2455 tuphdr->t_hoff = heaptup->t_data->t_hoff;
2457 /* write bitmap [+ padding] [+ oid] + data */
2458 datalen = heaptup->t_len - offsetof(HeapTupleHeaderData, t_bits);
2460 (char *) heaptup->t_data + offsetof(HeapTupleHeaderData, t_bits),
2462 tuphdr->datalen = datalen;
2463 scratchptr += datalen;
2465 totaldatalen = scratchptr - tupledata;
2466 Assert((scratchptr - scratch) < BLCKSZ);
2468 if (need_tuple_data)
2469 xlrec->flags |= XLOG_HEAP_CONTAINS_NEW_TUPLE;
2472 * Signal that this is the last xl_heap_multi_insert record
2473 * emitted by this call to heap_multi_insert(). Needed for logical
2474 * decoding so it knows when to cleanup temporary data.
2476 if (ndone + nthispage == ntuples)
2477 xlrec->flags |= XLOG_HEAP_LAST_MULTI_INSERT;
2481 info |= XLOG_HEAP_INIT_PAGE;
2482 bufflags |= REGBUF_WILL_INIT;
2486 * If we're doing logical decoding, include the new tuple data
2487 * even if we take a full-page image of the page.
2489 if (need_tuple_data)
2490 bufflags |= REGBUF_KEEP_DATA;
2493 XLogRegisterData((char *) xlrec, tupledata - scratch);
2494 XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2496 XLogRegisterBufData(0, tupledata, totaldatalen);
2497 recptr = XLogInsert(RM_HEAP2_ID, info);
2499 PageSetLSN(page, recptr);
2504 UnlockReleaseBuffer(buffer);
2505 if (vmbuffer != InvalidBuffer)
2506 ReleaseBuffer(vmbuffer);
2512 * If tuples are cachable, mark them for invalidation from the caches in
2513 * case we abort. Note it is OK to do this after releasing the buffer,
2514 * because the heaptuples data structure is all in local memory, not in
2515 * the shared buffer.
2517 if (IsCatalogRelation(relation))
2519 for (i = 0; i < ntuples; i++)
2520 CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2524 * Copy t_self fields back to the caller's original tuples. This does
2525 * nothing for untoasted tuples (tuples[i] == heaptuples[i)], but it's
2526 * probably faster to always copy than check.
2528 for (i = 0; i < ntuples; i++)
2529 tuples[i]->t_self = heaptuples[i]->t_self;
2531 pgstat_count_heap_insert(relation, ntuples);
2535 * simple_heap_insert - insert a tuple
2537 * Currently, this routine differs from heap_insert only in supplying
2538 * a default command ID and not allowing access to the speedup options.
2540 * This should be used rather than using heap_insert directly in most places
2541 * where we are modifying system catalogs.
2544 simple_heap_insert(Relation relation, HeapTuple tup)
2546 return heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
2550 * Given infomask/infomask2, compute the bits that must be saved in the
2551 * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
2552 * xl_heap_lock_updated WAL records.
2554 * See fix_infomask_from_infobits.
2557 compute_infobits(uint16 infomask, uint16 infomask2)
2560 ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2561 ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2562 ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2563 /* note we ignore HEAP_XMAX_SHR_LOCK here */
2564 ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2565 ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2566 XLHL_KEYS_UPDATED : 0);
2570 * Given two versions of the same t_infomask for a tuple, compare them and
2571 * return whether the relevant status for a tuple Xmax has changed. This is
2572 * used after a buffer lock has been released and reacquired: we want to ensure
2573 * that the tuple state continues to be the same it was when we previously
2576 * Note the Xmax field itself must be compared separately.
2579 xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
2581 const uint16 interesting =
2582 HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
2584 if ((new_infomask & interesting) != (old_infomask & interesting))
2591 * heap_delete - delete a tuple
2593 * NB: do not call this directly unless you are prepared to deal with
2594 * concurrent-update conditions. Use simple_heap_delete instead.
2596 * relation - table to be modified (caller must hold suitable lock)
2597 * tid - TID of tuple to be deleted
2598 * cid - delete command ID (used for visibility test, and stored into
2599 * cmax if successful)
2600 * crosscheck - if not InvalidSnapshot, also check tuple against this
2601 * wait - true if should wait for any conflicting update to commit/abort
2602 * hufd - output parameter, filled in failure cases (see below)
2604 * Normal, successful return value is HeapTupleMayBeUpdated, which
2605 * actually means we did delete it. Failure return codes are
2606 * HeapTupleSelfUpdated, HeapTupleUpdated, or HeapTupleBeingUpdated
2607 * (the last only possible if wait == false).
2609 * In the failure cases, the routine fills *hufd with the tuple's t_ctid,
2610 * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax
2611 * (the last only for HeapTupleSelfUpdated, since we
2612 * cannot obtain cmax from a combocid generated by another transaction).
2613 * See comments for struct HeapUpdateFailureData for additional info.
2616 heap_delete(Relation relation, ItemPointer tid,
2617 CommandId cid, Snapshot crosscheck, bool wait,
2618 HeapUpdateFailureData *hufd)
2621 TransactionId xid = GetCurrentTransactionId();
2627 Buffer vmbuffer = InvalidBuffer;
2628 TransactionId new_xmax;
2629 uint16 new_infomask,
2631 bool have_tuple_lock = false;
2633 bool all_visible_cleared = false;
2634 HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
2635 bool old_key_copied = false;
2637 Assert(ItemPointerIsValid(tid));
2639 block = ItemPointerGetBlockNumber(tid);
2640 buffer = ReadBuffer(relation, block);
2641 page = BufferGetPage(buffer);
2644 * Before locking the buffer, pin the visibility map page if it appears to
2645 * be necessary. Since we haven't got the lock yet, someone else might be
2646 * in the middle of changing this, so we'll need to recheck after we have
2649 if (PageIsAllVisible(page))
2650 visibilitymap_pin(relation, block, &vmbuffer);
2652 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2655 * If we didn't pin the visibility map page and the page has become all
2656 * visible while we were busy locking the buffer, we'll have to unlock and
2657 * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2658 * unfortunate, but hopefully shouldn't happen often.
2660 if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2662 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2663 visibilitymap_pin(relation, block, &vmbuffer);
2664 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2667 lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2668 Assert(ItemIdIsNormal(lp));
2670 tp.t_tableOid = RelationGetRelid(relation);
2671 tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2672 tp.t_len = ItemIdGetLength(lp);
2676 result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2678 if (result == HeapTupleInvisible)
2680 UnlockReleaseBuffer(buffer);
2681 elog(ERROR, "attempted to delete invisible tuple");
2683 else if (result == HeapTupleBeingUpdated && wait)
2685 TransactionId xwait;
2688 /* must copy state data before unlocking buffer */
2689 xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
2690 infomask = tp.t_data->t_infomask;
2692 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2695 * Acquire tuple lock to establish our priority for the tuple (see
2696 * heap_lock_tuple). LockTuple will release us when we are
2697 * next-in-line for the tuple.
2699 * If we are forced to "start over" below, we keep the tuple lock;
2700 * this arranges that we stay at the head of the line while rechecking
2703 if (!have_tuple_lock)
2705 LockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2706 have_tuple_lock = true;
2710 * Sleep until concurrent transaction ends. Note that we don't care
2711 * which lock mode the locker has, because we need the strongest one.
2714 if (infomask & HEAP_XMAX_IS_MULTI)
2716 /* wait for multixact */
2717 MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
2718 relation, &tp.t_data->t_ctid, XLTW_Delete,
2720 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2723 * If xwait had just locked the tuple then some other xact could
2724 * update this tuple before we get to this point. Check for xmax
2725 * change, and start over if so.
2727 if (xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2728 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2733 * You might think the multixact is necessarily done here, but not
2734 * so: it could have surviving members, namely our own xact or
2735 * other subxacts of this backend. It is legal for us to delete
2736 * the tuple in either case, however (the latter case is
2737 * essentially a situation of upgrading our former shared lock to
2738 * exclusive). We don't bother changing the on-disk hint bits
2739 * since we are about to overwrite the xmax altogether.
2744 /* wait for regular transaction to end */
2745 XactLockTableWait(xwait, relation, &tp.t_data->t_ctid, XLTW_Delete);
2746 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2749 * xwait is done, but if xwait had just locked the tuple then some
2750 * other xact could update this tuple before we get to this point.
2751 * Check for xmax change, and start over if so.
2753 if (xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2754 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2758 /* Otherwise check if it committed or aborted */
2759 UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2763 * We may overwrite if previous xmax aborted, or if it committed but
2764 * only locked the tuple without updating it.
2766 if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2767 HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
2768 HeapTupleHeaderIsOnlyLocked(tp.t_data))
2769 result = HeapTupleMayBeUpdated;
2771 result = HeapTupleUpdated;
2774 if (crosscheck != InvalidSnapshot && result == HeapTupleMayBeUpdated)
2776 /* Perform additional check for transaction-snapshot mode RI updates */
2777 if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2778 result = HeapTupleUpdated;
2781 if (result != HeapTupleMayBeUpdated)
2783 Assert(result == HeapTupleSelfUpdated ||
2784 result == HeapTupleUpdated ||
2785 result == HeapTupleBeingUpdated);
2786 Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
2787 hufd->ctid = tp.t_data->t_ctid;
2788 hufd->xmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
2789 if (result == HeapTupleSelfUpdated)
2790 hufd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
2792 hufd->cmax = InvalidCommandId;
2793 UnlockReleaseBuffer(buffer);
2794 if (have_tuple_lock)
2795 UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2796 if (vmbuffer != InvalidBuffer)
2797 ReleaseBuffer(vmbuffer);
2802 * We're about to do the actual delete -- check for conflict first, to
2803 * avoid possibly having to roll back work we've just done.
2805 CheckForSerializableConflictIn(relation, &tp, buffer);
2807 /* replace cid with a combo cid if necessary */
2808 HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
2811 * Compute replica identity tuple before entering the critical section so
2812 * we don't PANIC upon a memory allocation failure.
2814 old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
2817 * If this is the first possibly-multixact-able operation in the current
2818 * transaction, set my per-backend OldestMemberMXactId setting. We can be
2819 * certain that the transaction will never become a member of any older
2820 * MultiXactIds than that. (We have to do this even if we end up just
2821 * using our own TransactionId below, since some other backend could
2822 * incorporate our XID into a MultiXact immediately afterwards.)
2824 MultiXactIdSetOldestMember();
2826 compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
2827 tp.t_data->t_infomask, tp.t_data->t_infomask2,
2828 xid, LockTupleExclusive, true,
2829 &new_xmax, &new_infomask, &new_infomask2);
2831 START_CRIT_SECTION();
2834 * If this transaction commits, the tuple will become DEAD sooner or
2835 * later. Set flag that this page is a candidate for pruning once our xid
2836 * falls below the OldestXmin horizon. If the transaction finally aborts,
2837 * the subsequent page pruning will be a no-op and the hint will be
2840 PageSetPrunable(page, xid);
2842 if (PageIsAllVisible(page))
2844 all_visible_cleared = true;
2845 PageClearAllVisible(page);
2846 visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
2850 /* store transaction information of xact deleting the tuple */
2851 tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
2852 tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
2853 tp.t_data->t_infomask |= new_infomask;
2854 tp.t_data->t_infomask2 |= new_infomask2;
2855 HeapTupleHeaderClearHotUpdated(tp.t_data);
2856 HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
2857 HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
2858 /* Make sure there is no forward chain link in t_ctid */
2859 tp.t_data->t_ctid = tp.t_self;
2861 MarkBufferDirty(buffer);
2864 if (RelationNeedsWAL(relation))
2866 xl_heap_delete xlrec;
2869 /* For logical decode we need combocids to properly decode the catalog */
2870 if (RelationIsAccessibleInLogicalDecoding(relation))
2871 log_heap_new_cid(relation, &tp);
2873 xlrec.flags = all_visible_cleared ? XLOG_HEAP_ALL_VISIBLE_CLEARED : 0;
2874 xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
2875 tp.t_data->t_infomask2);
2876 xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
2877 xlrec.xmax = new_xmax;
2879 if (old_key_tuple != NULL)
2881 if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
2882 xlrec.flags |= XLOG_HEAP_CONTAINS_OLD_TUPLE;
2884 xlrec.flags |= XLOG_HEAP_CONTAINS_OLD_KEY;
2888 XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
2890 XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
2893 * Log replica identity of the deleted tuple if there is one
2895 if (old_key_tuple != NULL)
2897 xl_heap_header xlhdr;
2899 xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
2900 xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
2901 xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
2903 XLogRegisterData((char *) &xlhdr, SizeOfHeapHeader);
2904 XLogRegisterData((char *) old_key_tuple->t_data
2905 + offsetof(HeapTupleHeaderData, t_bits),
2906 old_key_tuple->t_len
2907 - offsetof(HeapTupleHeaderData, t_bits));
2910 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
2912 PageSetLSN(page, recptr);
2917 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2919 if (vmbuffer != InvalidBuffer)
2920 ReleaseBuffer(vmbuffer);
2923 * If the tuple has toasted out-of-line attributes, we need to delete
2924 * those items too. We have to do this before releasing the buffer
2925 * because we need to look at the contents of the tuple, but it's OK to
2926 * release the content lock on the buffer first.
2928 if (relation->rd_rel->relkind != RELKIND_RELATION &&
2929 relation->rd_rel->relkind != RELKIND_MATVIEW)
2931 /* toast table entries should never be recursively toasted */
2932 Assert(!HeapTupleHasExternal(&tp));
2934 else if (HeapTupleHasExternal(&tp))
2935 toast_delete(relation, &tp);
2938 * Mark tuple for invalidation from system caches at next command
2939 * boundary. We have to do this before releasing the buffer because we
2940 * need to look at the contents of the tuple.
2942 CacheInvalidateHeapTuple(relation, &tp, NULL);
2944 /* Now we can release the buffer */
2945 ReleaseBuffer(buffer);
2948 * Release the lmgr tuple lock, if we had it.
2950 if (have_tuple_lock)
2951 UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2953 pgstat_count_heap_delete(relation);
2955 if (old_key_tuple != NULL && old_key_copied)
2956 heap_freetuple(old_key_tuple);
2958 return HeapTupleMayBeUpdated;
2962 * simple_heap_delete - delete a tuple
2964 * This routine may be used to delete a tuple when concurrent updates of
2965 * the target tuple are not expected (for example, because we have a lock
2966 * on the relation associated with the tuple). Any failure is reported
2970 simple_heap_delete(Relation relation, ItemPointer tid)
2973 HeapUpdateFailureData hufd;
2975 result = heap_delete(relation, tid,
2976 GetCurrentCommandId(true), InvalidSnapshot,
2977 true /* wait for commit */ ,
2981 case HeapTupleSelfUpdated:
2982 /* Tuple was already updated in current command? */
2983 elog(ERROR, "tuple already updated by self");
2986 case HeapTupleMayBeUpdated:
2987 /* done successfully */
2990 case HeapTupleUpdated:
2991 elog(ERROR, "tuple concurrently updated");
2995 elog(ERROR, "unrecognized heap_delete status: %u", result);
3001 * heap_update - replace a tuple
3003 * NB: do not call this directly unless you are prepared to deal with
3004 * concurrent-update conditions. Use simple_heap_update instead.
3006 * relation - table to be modified (caller must hold suitable lock)
3007 * otid - TID of old tuple to be replaced
3008 * newtup - newly constructed tuple data to store
3009 * cid - update command ID (used for visibility test, and stored into
3010 * cmax/cmin if successful)
3011 * crosscheck - if not InvalidSnapshot, also check old tuple against this
3012 * wait - true if should wait for any conflicting update to commit/abort
3013 * hufd - output parameter, filled in failure cases (see below)
3014 * lockmode - output parameter, filled with lock mode acquired on tuple
3016 * Normal, successful return value is HeapTupleMayBeUpdated, which
3017 * actually means we *did* update it. Failure return codes are
3018 * HeapTupleSelfUpdated, HeapTupleUpdated, or HeapTupleBeingUpdated
3019 * (the last only possible if wait == false).
3021 * On success, the header fields of *newtup are updated to match the new
3022 * stored tuple; in particular, newtup->t_self is set to the TID where the
3023 * new tuple was inserted, and its HEAP_ONLY_TUPLE flag is set iff a HOT
3024 * update was done. However, any TOAST changes in the new tuple's
3025 * data are not reflected into *newtup.
3027 * In the failure cases, the routine fills *hufd with the tuple's t_ctid,
3028 * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax
3029 * (the last only for HeapTupleSelfUpdated, since we
3030 * cannot obtain cmax from a combocid generated by another transaction).
3031 * See comments for struct HeapUpdateFailureData for additional info.
3034 heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,
3035 CommandId cid, Snapshot crosscheck, bool wait,
3036 HeapUpdateFailureData *hufd, LockTupleMode *lockmode)
3039 TransactionId xid = GetCurrentTransactionId();
3040 Bitmapset *hot_attrs;
3041 Bitmapset *key_attrs;
3042 Bitmapset *id_attrs;
3044 HeapTupleData oldtup;
3046 HeapTuple old_key_tuple = NULL;
3047 bool old_key_copied = false;
3050 MultiXactStatus mxact_status;
3053 vmbuffer = InvalidBuffer,
3054 vmbuffer_new = InvalidBuffer;
3059 bool have_tuple_lock = false;
3064 bool use_hot_update = false;
3066 bool all_visible_cleared = false;
3067 bool all_visible_cleared_new = false;
3068 bool checked_lockers;
3069 bool locker_remains;
3070 TransactionId xmax_new_tuple,
3072 uint16 infomask_old_tuple,
3073 infomask2_old_tuple,
3075 infomask2_new_tuple;
3077 Assert(ItemPointerIsValid(otid));
3080 * Fetch the list of attributes to be checked for HOT update. This is
3081 * wasted effort if we fail to update or have to put the new tuple on a
3082 * different page. But we must compute the list before obtaining buffer
3083 * lock --- in the worst case, if we are doing an update on one of the
3084 * relevant system catalogs, we could deadlock if we try to fetch the list
3085 * later. In any case, the relcache caches the data so this is usually
3088 * Note that we get a copy here, so we need not worry about relcache flush
3089 * happening midway through.
3091 hot_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_ALL);
3092 key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3093 id_attrs = RelationGetIndexAttrBitmap(relation,
3094 INDEX_ATTR_BITMAP_IDENTITY_KEY);
3096 block = ItemPointerGetBlockNumber(otid);
3097 buffer = ReadBuffer(relation, block);
3098 page = BufferGetPage(buffer);
3101 * Before locking the buffer, pin the visibility map page if it appears to
3102 * be necessary. Since we haven't got the lock yet, someone else might be
3103 * in the middle of changing this, so we'll need to recheck after we have
3106 if (PageIsAllVisible(page))
3107 visibilitymap_pin(relation, block, &vmbuffer);
3109 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3111 lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3112 Assert(ItemIdIsNormal(lp));
3115 * Fill in enough data in oldtup for HeapSatisfiesHOTandKeyUpdate to work
3118 oldtup.t_tableOid = RelationGetRelid(relation);
3119 oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
3120 oldtup.t_len = ItemIdGetLength(lp);
3121 oldtup.t_self = *otid;
3123 /* the new tuple is ready, except for this: */
3124 newtup->t_tableOid = RelationGetRelid(relation);
3126 /* Fill in OID for newtup */
3127 if (relation->rd_rel->relhasoids)
3130 /* this is redundant with an Assert in HeapTupleSetOid */
3131 Assert(newtup->t_data->t_infomask & HEAP_HASOID);
3133 HeapTupleSetOid(newtup, HeapTupleGetOid(&oldtup));
3137 /* check there is not space for an OID */
3138 Assert(!(newtup->t_data->t_infomask & HEAP_HASOID));
3142 * If we're not updating any "key" column, we can grab a weaker lock type.
3143 * This allows for more concurrency when we are running simultaneously
3144 * with foreign key checks.
3146 * Note that if a column gets detoasted while executing the update, but
3147 * the value ends up being the same, this test will fail and we will use
3148 * the stronger lock. This is acceptable; the important case to optimize
3149 * is updates that don't manipulate key columns, not those that
3150 * serendipitiously arrive at the same key values.
3152 HeapSatisfiesHOTandKeyUpdate(relation, hot_attrs, key_attrs, id_attrs,
3153 &satisfies_hot, &satisfies_key,
3154 &satisfies_id, &oldtup, newtup);
3157 *lockmode = LockTupleNoKeyExclusive;
3158 mxact_status = MultiXactStatusNoKeyUpdate;
3162 * If this is the first possibly-multixact-able operation in the
3163 * current transaction, set my per-backend OldestMemberMXactId
3164 * setting. We can be certain that the transaction will never become a
3165 * member of any older MultiXactIds than that. (We have to do this
3166 * even if we end up just using our own TransactionId below, since
3167 * some other backend could incorporate our XID into a MultiXact
3168 * immediately afterwards.)
3170 MultiXactIdSetOldestMember();
3174 *lockmode = LockTupleExclusive;
3175 mxact_status = MultiXactStatusUpdate;
3180 * Note: beyond this point, use oldtup not otid to refer to old tuple.
3181 * otid may very well point at newtup->t_self, which we will overwrite
3182 * with the new tuple's location, so there's great risk of confusion if we
3187 checked_lockers = false;
3188 locker_remains = false;
3189 result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3191 /* see below about the "no wait" case */
3192 Assert(result != HeapTupleBeingUpdated || wait);
3194 if (result == HeapTupleInvisible)
3196 UnlockReleaseBuffer(buffer);
3197 elog(ERROR, "attempted to update invisible tuple");
3199 else if (result == HeapTupleBeingUpdated && wait)
3201 TransactionId xwait;
3203 bool can_continue = false;
3205 checked_lockers = true;
3208 * XXX note that we don't consider the "no wait" case here. This
3209 * isn't a problem currently because no caller uses that case, but it
3210 * should be fixed if such a caller is introduced. It wasn't a
3211 * problem previously because this code would always wait, but now
3212 * that some tuple locks do not conflict with one of the lock modes we
3213 * use, it is possible that this case is interesting to handle
3216 * This may cause failures with third-party code that calls
3217 * heap_update directly.
3220 /* must copy state data before unlocking buffer */
3221 xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3222 infomask = oldtup.t_data->t_infomask;
3224 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3227 * Acquire tuple lock to establish our priority for the tuple (see
3228 * heap_lock_tuple). LockTuple will release us when we are
3229 * next-in-line for the tuple.
3231 * If we are forced to "start over" below, we keep the tuple lock;
3232 * this arranges that we stay at the head of the line while rechecking
3235 if (!have_tuple_lock)
3237 LockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3238 have_tuple_lock = true;
3242 * Now we have to do something about the existing locker. If it's a
3243 * multi, sleep on it; we might be awakened before it is completely
3244 * gone (or even not sleep at all in some cases); we need to preserve
3245 * it as locker, unless it is gone completely.
3247 * If it's not a multi, we need to check for sleeping conditions
3248 * before actually going to sleep. If the update doesn't conflict
3249 * with the locks, we just continue without sleeping (but making sure
3252 if (infomask & HEAP_XMAX_IS_MULTI)
3254 TransactionId update_xact;
3257 /* wait for multixact */
3258 MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3259 relation, &oldtup.t_data->t_ctid, XLTW_Update,
3261 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3264 * If xwait had just locked the tuple then some other xact could
3265 * update this tuple before we get to this point. Check for xmax
3266 * change, and start over if so.
3268 if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3269 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3274 * Note that the multixact may not be done by now. It could have
3275 * surviving members; our own xact or other subxacts of this
3276 * backend, and also any other concurrent transaction that locked
3277 * the tuple with KeyShare if we only got TupleLockUpdate. If
3278 * this is the case, we have to be careful to mark the updated
3279 * tuple with the surviving members in Xmax.
3281 * Note that there could have been another update in the
3282 * MultiXact. In that case, we need to check whether it committed
3283 * or aborted. If it aborted we are safe to update it again;
3284 * otherwise there is an update conflict, and we have to return
3285 * HeapTupleUpdated below.
3287 * In the LockTupleExclusive case, we still need to preserve the
3288 * surviving members: those would include the tuple locks we had
3289 * before this one, which are important to keep in case this
3292 update_xact = InvalidTransactionId;
3293 if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
3294 update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3297 * There was no UPDATE in the MultiXact; or it aborted. No
3298 * TransactionIdIsInProgress() call needed here, since we called
3299 * MultiXactIdWait() above.
3301 if (!TransactionIdIsValid(update_xact) ||
3302 TransactionIdDidAbort(update_xact))
3303 can_continue = true;
3305 locker_remains = remain != 0;
3310 * If it's just a key-share locker, and we're not changing the key
3311 * columns, we don't need to wait for it to end; but we need to
3312 * preserve it as locker.
3314 if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3316 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3319 * recheck the locker; if someone else changed the tuple while
3320 * we weren't looking, start over.
3322 if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3323 !TransactionIdEquals(
3324 HeapTupleHeaderGetRawXmax(oldtup.t_data),
3328 can_continue = true;
3329 locker_remains = true;
3333 /* wait for regular transaction to end */
3334 XactLockTableWait(xwait, relation, &oldtup.t_data->t_ctid,
3336 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3339 * xwait is done, but if xwait had just locked the tuple then
3340 * some other xact could update this tuple before we get to
3341 * this point. Check for xmax change, and start over if so.
3343 if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3344 !TransactionIdEquals(
3345 HeapTupleHeaderGetRawXmax(oldtup.t_data),
3349 /* Otherwise check if it committed or aborted */
3350 UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3351 if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
3352 can_continue = true;
3356 result = can_continue ? HeapTupleMayBeUpdated : HeapTupleUpdated;
3359 if (crosscheck != InvalidSnapshot && result == HeapTupleMayBeUpdated)
3361 /* Perform additional check for transaction-snapshot mode RI updates */
3362 if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3363 result = HeapTupleUpdated;
3366 if (result != HeapTupleMayBeUpdated)
3368 Assert(result == HeapTupleSelfUpdated ||
3369 result == HeapTupleUpdated ||
3370 result == HeapTupleBeingUpdated);
3371 Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
3372 hufd->ctid = oldtup.t_data->t_ctid;
3373 hufd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3374 if (result == HeapTupleSelfUpdated)
3375 hufd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3377 hufd->cmax = InvalidCommandId;
3378 UnlockReleaseBuffer(buffer);
3379 if (have_tuple_lock)
3380 UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3381 if (vmbuffer != InvalidBuffer)
3382 ReleaseBuffer(vmbuffer);
3383 bms_free(hot_attrs);
3384 bms_free(key_attrs);
3389 * If we didn't pin the visibility map page and the page has become all
3390 * visible while we were busy locking the buffer, or during some
3391 * subsequent window during which we had it unlocked, we'll have to unlock
3392 * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3393 * bit unfortunate, especially since we'll now have to recheck whether the
3394 * tuple has been locked or updated under us, but hopefully it won't
3395 * happen very often.
3397 if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3399 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3400 visibilitymap_pin(relation, block, &vmbuffer);
3401 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3406 * We're about to do the actual update -- check for conflict first, to
3407 * avoid possibly having to roll back work we've just done.
3409 CheckForSerializableConflictIn(relation, &oldtup, buffer);
3411 /* Fill in transaction status data */
3414 * If the tuple we're updating is locked, we need to preserve the locking
3415 * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3417 compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3418 oldtup.t_data->t_infomask,
3419 oldtup.t_data->t_infomask2,
3420 xid, *lockmode, true,
3421 &xmax_old_tuple, &infomask_old_tuple,
3422 &infomask2_old_tuple);
3425 * And also prepare an Xmax value for the new copy of the tuple. If there
3426 * was no xmax previously, or there was one but all lockers are now gone,
3427 * then use InvalidXid; otherwise, get the xmax from the old tuple. (In
3428 * rare cases that might also be InvalidXid and yet not have the
3429 * HEAP_XMAX_INVALID bit set; that's fine.)
3431 if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3432 (checked_lockers && !locker_remains))
3433 xmax_new_tuple = InvalidTransactionId;
3435 xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3437 if (!TransactionIdIsValid(xmax_new_tuple))
3439 infomask_new_tuple = HEAP_XMAX_INVALID;
3440 infomask2_new_tuple = 0;
3445 * If we found a valid Xmax for the new tuple, then the infomask bits
3446 * to use on the new tuple depend on what was there on the old one.
3447 * Note that since we're doing an update, the only possibility is that
3448 * the lockers had FOR KEY SHARE lock.
3450 if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3452 GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3453 &infomask2_new_tuple);
3457 infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3458 infomask2_new_tuple = 0;
3463 * Prepare the new tuple with the appropriate initial values of Xmin and
3464 * Xmax, as well as initial infomask bits as computed above.
3466 newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
3467 newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
3468 HeapTupleHeaderSetXmin(newtup->t_data, xid);
3469 HeapTupleHeaderSetCmin(newtup->t_data, cid);
3470 newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3471 newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3472 HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3475 * Replace cid with a combo cid if necessary. Note that we already put
3476 * the plain cid into the new tuple.
3478 HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3481 * If the toaster needs to be activated, OR if the new tuple will not fit
3482 * on the same page as the old, then we need to release the content lock
3483 * (but not the pin!) on the old tuple's buffer while we are off doing
3484 * TOAST and/or table-file-extension work. We must mark the old tuple to
3485 * show that it's already being updated, else other processes may try to
3486 * update it themselves.
3488 * We need to invoke the toaster if there are already any out-of-line
3489 * toasted values present, or if the new tuple is over-threshold.
3491 if (relation->rd_rel->relkind != RELKIND_RELATION &&
3492 relation->rd_rel->relkind != RELKIND_MATVIEW)
3494 /* toast table entries should never be recursively toasted */
3495 Assert(!HeapTupleHasExternal(&oldtup));
3496 Assert(!HeapTupleHasExternal(newtup));
3500 need_toast = (HeapTupleHasExternal(&oldtup) ||
3501 HeapTupleHasExternal(newtup) ||
3502 newtup->t_len > TOAST_TUPLE_THRESHOLD);
3504 pagefree = PageGetHeapFreeSpace(page);
3506 newtupsize = MAXALIGN(newtup->t_len);
3508 if (need_toast || newtupsize > pagefree)
3510 /* Clear obsolete visibility flags ... */
3511 oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3512 oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3513 HeapTupleClearHotUpdated(&oldtup);
3514 /* ... and store info about transaction updating this tuple */
3515 Assert(TransactionIdIsValid(xmax_old_tuple));
3516 HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
3517 oldtup.t_data->t_infomask |= infomask_old_tuple;
3518 oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
3519 HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3520 /* temporarily make it look not-updated */
3521 oldtup.t_data->t_ctid = oldtup.t_self;
3522 already_marked = true;
3523 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3526 * Let the toaster do its thing, if needed.
3528 * Note: below this point, heaptup is the data we actually intend to
3529 * store into the relation; newtup is the caller's original untoasted
3534 /* Note we always use WAL and FSM during updates */
3535 heaptup = toast_insert_or_update(relation, newtup, &oldtup, 0);
3536 newtupsize = MAXALIGN(heaptup->t_len);
3542 * Now, do we need a new page for the tuple, or not? This is a bit
3543 * tricky since someone else could have added tuples to the page while
3544 * we weren't looking. We have to recheck the available space after
3545 * reacquiring the buffer lock. But don't bother to do that if the
3546 * former amount of free space is still not enough; it's unlikely
3547 * there's more free now than before.
3549 * What's more, if we need to get a new page, we will need to acquire
3550 * buffer locks on both old and new pages. To avoid deadlock against
3551 * some other backend trying to get the same two locks in the other
3552 * order, we must be consistent about the order we get the locks in.
3553 * We use the rule "lock the lower-numbered page of the relation
3554 * first". To implement this, we must do RelationGetBufferForTuple
3555 * while not holding the lock on the old page, and we must rely on it
3556 * to get the locks on both pages in the correct order.
3558 if (newtupsize > pagefree)
3560 /* Assume there's no chance to put heaptup on same page. */
3561 newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
3563 &vmbuffer_new, &vmbuffer);
3567 /* Re-acquire the lock on the old tuple's page. */
3568 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3569 /* Re-check using the up-to-date free space */
3570 pagefree = PageGetHeapFreeSpace(page);
3571 if (newtupsize > pagefree)
3574 * Rats, it doesn't fit anymore. We must now unlock and
3575 * relock to avoid deadlock. Fortunately, this path should
3578 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3579 newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
3581 &vmbuffer_new, &vmbuffer);
3585 /* OK, it fits here, so we're done. */
3592 /* No TOAST work needed, and it'll fit on same page */
3593 already_marked = false;
3599 * We're about to create the new tuple -- check for conflict first, to
3600 * avoid possibly having to roll back work we've just done.
3602 * NOTE: For a tuple insert, we only need to check for table locks, since
3603 * predicate locking at the index level will cover ranges for anything
3604 * except a table scan. Therefore, only provide the relation.
3606 CheckForSerializableConflictIn(relation, NULL, InvalidBuffer);
3609 * At this point newbuf and buffer are both pinned and locked, and newbuf
3610 * has enough space for the new tuple. If they are the same buffer, only
3614 if (newbuf == buffer)
3617 * Since the new tuple is going into the same page, we might be able
3618 * to do a HOT update. Check if any of the index columns have been
3619 * changed. If not, then HOT update is possible.
3622 use_hot_update = true;
3626 /* Set a hint that the old page could use prune/defrag */
3631 * Compute replica identity tuple before entering the critical section so
3632 * we don't PANIC upon a memory allocation failure.
3633 * ExtractReplicaIdentity() will return NULL if nothing needs to be
3636 old_key_tuple = ExtractReplicaIdentity(relation, &oldtup, !satisfies_id, &old_key_copied);
3638 /* NO EREPORT(ERROR) from here till changes are logged */
3639 START_CRIT_SECTION();
3642 * If this transaction commits, the old tuple will become DEAD sooner or
3643 * later. Set flag that this page is a candidate for pruning once our xid
3644 * falls below the OldestXmin horizon. If the transaction finally aborts,
3645 * the subsequent page pruning will be a no-op and the hint will be
3648 * XXX Should we set hint on newbuf as well? If the transaction aborts,
3649 * there would be a prunable tuple in the newbuf; but for now we choose
3650 * not to optimize for aborts. Note that heap_xlog_update must be kept in
3651 * sync if this decision changes.
3653 PageSetPrunable(page, xid);
3657 /* Mark the old tuple as HOT-updated */
3658 HeapTupleSetHotUpdated(&oldtup);
3659 /* And mark the new tuple as heap-only */
3660 HeapTupleSetHeapOnly(heaptup);
3661 /* Mark the caller's copy too, in case different from heaptup */
3662 HeapTupleSetHeapOnly(newtup);
3666 /* Make sure tuples are correctly marked as not-HOT */
3667 HeapTupleClearHotUpdated(&oldtup);
3668 HeapTupleClearHeapOnly(heaptup);
3669 HeapTupleClearHeapOnly(newtup);
3672 RelationPutHeapTuple(relation, newbuf, heaptup); /* insert new tuple */
3674 if (!already_marked)
3676 /* Clear obsolete visibility flags ... */
3677 oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3678 oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3679 /* ... and store info about transaction updating this tuple */
3680 Assert(TransactionIdIsValid(xmax_old_tuple));
3681 HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
3682 oldtup.t_data->t_infomask |= infomask_old_tuple;
3683 oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
3684 HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3687 /* record address of new tuple in t_ctid of old one */
3688 oldtup.t_data->t_ctid = heaptup->t_self;
3690 /* clear PD_ALL_VISIBLE flags */
3691 if (PageIsAllVisible(BufferGetPage(buffer)))
3693 all_visible_cleared = true;
3694 PageClearAllVisible(BufferGetPage(buffer));
3695 visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
3698 if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
3700 all_visible_cleared_new = true;
3701 PageClearAllVisible(BufferGetPage(newbuf));
3702 visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
3706 if (newbuf != buffer)
3707 MarkBufferDirty(newbuf);
3708 MarkBufferDirty(buffer);
3711 if (RelationNeedsWAL(relation))
3716 * For logical decoding we need combocids to properly decode the
3719 if (RelationIsAccessibleInLogicalDecoding(relation))
3721 log_heap_new_cid(relation, &oldtup);
3722 log_heap_new_cid(relation, heaptup);
3725 recptr = log_heap_update(relation, buffer,
3726 newbuf, &oldtup, heaptup,
3728 all_visible_cleared,
3729 all_visible_cleared_new);
3730 if (newbuf != buffer)
3732 PageSetLSN(BufferGetPage(newbuf), recptr);
3734 PageSetLSN(BufferGetPage(buffer), recptr);
3739 if (newbuf != buffer)
3740 LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
3741 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3744 * Mark old tuple for invalidation from system caches at next command
3745 * boundary, and mark the new tuple for invalidation in case we abort. We
3746 * have to do this before releasing the buffer because oldtup is in the
3747 * buffer. (heaptup is all in local memory, but it's necessary to process
3748 * both tuple versions in one call to inval.c so we can avoid redundant
3751 CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
3753 /* Now we can release the buffer(s) */
3754 if (newbuf != buffer)
3755 ReleaseBuffer(newbuf);
3756 ReleaseBuffer(buffer);
3757 if (BufferIsValid(vmbuffer_new))
3758 ReleaseBuffer(vmbuffer_new);
3759 if (BufferIsValid(vmbuffer))
3760 ReleaseBuffer(vmbuffer);
3763 * Release the lmgr tuple lock, if we had it.
3765 if (have_tuple_lock)
3766 UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3768 pgstat_count_heap_update(relation, use_hot_update);
3771 * If heaptup is a private copy, release it. Don't forget to copy t_self
3772 * back to the caller's image, too.
3774 if (heaptup != newtup)
3776 newtup->t_self = heaptup->t_self;
3777 heap_freetuple(heaptup);
3780 if (old_key_tuple != NULL && old_key_copied)
3781 heap_freetuple(old_key_tuple);
3783 bms_free(hot_attrs);
3784 bms_free(key_attrs);
3786 return HeapTupleMayBeUpdated;
3790 * Check if the specified attribute's value is same in both given tuples.
3791 * Subroutine for HeapSatisfiesHOTandKeyUpdate.
3794 heap_tuple_attr_equals(TupleDesc tupdesc, int attrnum,
3795 HeapTuple tup1, HeapTuple tup2)
3801 Form_pg_attribute att;
3804 * If it's a whole-tuple reference, say "not equal". It's not really
3805 * worth supporting this case, since it could only succeed after a no-op
3806 * update, which is hardly a case worth optimizing for.
3812 * Likewise, automatically say "not equal" for any system attribute other
3813 * than OID and tableOID; we cannot expect these to be consistent in a HOT
3814 * chain, or even to be set correctly yet in the new tuple.
3818 if (attrnum != ObjectIdAttributeNumber &&
3819 attrnum != TableOidAttributeNumber)
3824 * Extract the corresponding values. XXX this is pretty inefficient if
3825 * there are many indexed columns. Should HeapSatisfiesHOTandKeyUpdate do
3826 * a single heap_deform_tuple call on each tuple, instead? But that
3827 * doesn't work for system columns ...
3829 value1 = heap_getattr(tup1, attrnum, tupdesc, &isnull1);
3830 value2 = heap_getattr(tup2, attrnum, tupdesc, &isnull2);
3833 * If one value is NULL and other is not, then they are certainly not
3836 if (isnull1 != isnull2)
3840 * If both are NULL, they can be considered equal.
3846 * We do simple binary comparison of the two datums. This may be overly
3847 * strict because there can be multiple binary representations for the
3848 * same logical value. But we should be OK as long as there are no false
3849 * positives. Using a type-specific equality operator is messy because
3850 * there could be multiple notions of equality in different operator
3851 * classes; furthermore, we cannot safely invoke user-defined functions
3852 * while holding exclusive buffer lock.
3856 /* The only allowed system columns are OIDs, so do this */
3857 return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
3861 Assert(attrnum <= tupdesc->natts);
3862 att = tupdesc->attrs[attrnum - 1];
3863 return datumIsEqual(value1, value2, att->attbyval, att->attlen);
3868 * Check which columns are being updated.
3870 * This simultaneously checks conditions for HOT updates, for FOR KEY
3871 * SHARE updates, and REPLICA IDENTITY concerns. Since much of the time they
3872 * will be checking very similar sets of columns, and doing the same tests on
3873 * them, it makes sense to optimize and do them together.
3875 * We receive three bitmapsets comprising the three sets of columns we're
3876 * interested in. Note these are destructively modified; that is OK since
3877 * this is invoked at most once in heap_update.
3879 * hot_result is set to TRUE if it's okay to do a HOT update (i.e. it does not
3880 * modified indexed columns); key_result is set to TRUE if the update does not
3881 * modify columns used in the key; id_result is set to TRUE if the update does
3882 * not modify columns in any index marked as the REPLICA IDENTITY.
3885 HeapSatisfiesHOTandKeyUpdate(Relation relation, Bitmapset *hot_attrs,
3886 Bitmapset *key_attrs, Bitmapset *id_attrs,
3887 bool *satisfies_hot, bool *satisfies_key,
3889 HeapTuple oldtup, HeapTuple newtup)
3891 int next_hot_attnum;
3892 int next_key_attnum;
3894 bool hot_result = true;
3895 bool key_result = true;
3896 bool id_result = true;
3898 /* If REPLICA IDENTITY is set to FULL, id_attrs will be empty. */
3899 Assert(bms_is_subset(id_attrs, key_attrs));
3900 Assert(bms_is_subset(key_attrs, hot_attrs));
3903 * If one of these sets contains no remaining bits, bms_first_member will
3904 * return -1, and after adding FirstLowInvalidHeapAttributeNumber (which
3905 * is negative!) we'll get an attribute number that can't possibly be
3906 * real, and thus won't match any actual attribute number.
3908 next_hot_attnum = bms_first_member(hot_attrs);
3909 next_hot_attnum += FirstLowInvalidHeapAttributeNumber;
3910 next_key_attnum = bms_first_member(key_attrs);
3911 next_key_attnum += FirstLowInvalidHeapAttributeNumber;
3912 next_id_attnum = bms_first_member(id_attrs);
3913 next_id_attnum += FirstLowInvalidHeapAttributeNumber;
3921 * Since the HOT attributes are a superset of the key attributes and
3922 * the key attributes are a superset of the id attributes, this logic
3923 * is guaranteed to identify the next column that needs to be checked.
3925 if (hot_result && next_hot_attnum > FirstLowInvalidHeapAttributeNumber)
3926 check_now = next_hot_attnum;
3927 else if (key_result && next_key_attnum > FirstLowInvalidHeapAttributeNumber)
3928 check_now = next_key_attnum;
3929 else if (id_result && next_id_attnum > FirstLowInvalidHeapAttributeNumber)
3930 check_now = next_id_attnum;
3934 /* See whether it changed. */
3935 changed = !heap_tuple_attr_equals(RelationGetDescr(relation),
3936 check_now, oldtup, newtup);
3939 if (check_now == next_hot_attnum)
3941 if (check_now == next_key_attnum)
3943 if (check_now == next_id_attnum)
3946 /* if all are false now, we can stop checking */
3947 if (!hot_result && !key_result && !id_result)
3952 * Advance the next attribute numbers for the sets that contain the
3953 * attribute we just checked. As we work our way through the columns,
3954 * the next_attnum values will rise; but when each set becomes empty,
3955 * bms_first_member() will return -1 and the attribute number will end
3956 * up with a value less than FirstLowInvalidHeapAttributeNumber.
3958 if (hot_result && check_now == next_hot_attnum)
3960 next_hot_attnum = bms_first_member(hot_attrs);
3961 next_hot_attnum += FirstLowInvalidHeapAttributeNumber;
3963 if (key_result && check_now == next_key_attnum)
3965 next_key_attnum = bms_first_member(key_attrs);
3966 next_key_attnum += FirstLowInvalidHeapAttributeNumber;
3968 if (id_result && check_now == next_id_attnum)
3970 next_id_attnum = bms_first_member(id_attrs);
3971 next_id_attnum += FirstLowInvalidHeapAttributeNumber;
3975 *satisfies_hot = hot_result;
3976 *satisfies_key = key_result;
3977 *satisfies_id = id_result;
3981 * simple_heap_update - replace a tuple
3983 * This routine may be used to update a tuple when concurrent updates of
3984 * the target tuple are not expected (for example, because we have a lock
3985 * on the relation associated with the tuple). Any failure is reported
3989 simple_heap_update(Relation relation, ItemPointer otid, HeapTuple tup)
3992 HeapUpdateFailureData hufd;
3993 LockTupleMode lockmode;
3995 result = heap_update(relation, otid, tup,
3996 GetCurrentCommandId(true), InvalidSnapshot,
3997 true /* wait for commit */ ,
4001 case HeapTupleSelfUpdated:
4002 /* Tuple was already updated in current command? */
4003 elog(ERROR, "tuple already updated by self");
4006 case HeapTupleMayBeUpdated:
4007 /* done successfully */
4010 case HeapTupleUpdated:
4011 elog(ERROR, "tuple concurrently updated");
4015 elog(ERROR, "unrecognized heap_update status: %u", result);
4022 * Return the MultiXactStatus corresponding to the given tuple lock mode.
4024 static MultiXactStatus
4025 get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
4030 retval = tupleLockExtraInfo[mode].updstatus;
4032 retval = tupleLockExtraInfo[mode].lockstatus;
4035 elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4036 is_update ? "true" : "false");
4038 return (MultiXactStatus) retval;
4043 * heap_lock_tuple - lock a tuple in shared or exclusive mode
4045 * Note that this acquires a buffer pin, which the caller must release.
4048 * relation: relation containing tuple (caller must hold suitable lock)
4049 * tuple->t_self: TID of tuple to lock (rest of struct need not be valid)
4050 * cid: current command ID (used for visibility test, and stored into
4051 * tuple's cmax if lock is successful)
4052 * mode: indicates if shared or exclusive tuple lock is desired
4053 * wait_policy: what to do if tuple lock is not available
4054 * follow_updates: if true, follow the update chain to also lock descendant
4057 * Output parameters:
4058 * *tuple: all fields filled in
4059 * *buffer: set to buffer holding tuple (pinned but not locked at exit)
4060 * *hufd: filled in failure cases (see below)
4062 * Function result may be:
4063 * HeapTupleMayBeUpdated: lock was successfully acquired
4064 * HeapTupleSelfUpdated: lock failed because tuple updated by self
4065 * HeapTupleUpdated: lock failed because tuple updated by other xact
4066 * HeapTupleWouldBlock: lock couldn't be acquired and wait_policy is skip
4068 * In the failure cases, the routine fills *hufd with the tuple's t_ctid,
4069 * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax
4070 * (the last only for HeapTupleSelfUpdated, since we
4071 * cannot obtain cmax from a combocid generated by another transaction).
4072 * See comments for struct HeapUpdateFailureData for additional info.
4074 * See README.tuplock for a thorough explanation of this mechanism.
4077 heap_lock_tuple(Relation relation, HeapTuple tuple,
4078 CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
4079 bool follow_updates,
4080 Buffer *buffer, HeapUpdateFailureData *hufd)
4083 ItemPointer tid = &(tuple->t_self);
4088 uint16 old_infomask,
4091 bool have_tuple_lock = false;
4093 *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4094 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4096 page = BufferGetPage(*buffer);
4097 lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4098 Assert(ItemIdIsNormal(lp));
4100 tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4101 tuple->t_len = ItemIdGetLength(lp);
4102 tuple->t_tableOid = RelationGetRelid(relation);
4105 result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4107 if (result == HeapTupleInvisible)
4109 UnlockReleaseBuffer(*buffer);
4110 elog(ERROR, "attempted to lock invisible tuple");
4112 else if (result == HeapTupleBeingUpdated)
4114 TransactionId xwait;
4118 ItemPointerData t_ctid;
4120 /* must copy state data before unlocking buffer */
4121 xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4122 infomask = tuple->t_data->t_infomask;
4123 infomask2 = tuple->t_data->t_infomask2;
4124 ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4126 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4129 * If any subtransaction of the current top transaction already holds
4130 * a lock as strong or stronger than what we're requesting, we
4131 * effectively hold the desired lock already. We *must* succeed
4132 * without trying to take the tuple lock, else we will deadlock
4133 * against anyone wanting to acquire a stronger lock.
4135 if (infomask & HEAP_XMAX_IS_MULTI)
4139 MultiXactMember *members;
4142 * We don't need to allow old multixacts here; if that had been
4143 * the case, HeapTupleSatisfiesUpdate would have returned
4144 * MayBeUpdated and we wouldn't be here.
4147 GetMultiXactIdMembers(xwait, &members, false,
4148 HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4150 for (i = 0; i < nmembers; i++)
4152 if (TransactionIdIsCurrentTransactionId(members[i].xid))
4154 LockTupleMode membermode;
4156 membermode = TUPLOCK_from_mxstatus(members[i].status);
4158 if (membermode >= mode)
4160 if (have_tuple_lock)
4161 UnlockTupleTuplock(relation, tid, mode);
4164 return HeapTupleMayBeUpdated;
4174 * Acquire tuple lock to establish our priority for the tuple.
4175 * LockTuple will release us when we are next-in-line for the tuple.
4176 * We must do this even if we are share-locking.
4178 * If we are forced to "start over" below, we keep the tuple lock;
4179 * this arranges that we stay at the head of the line while rechecking
4182 if (!have_tuple_lock)
4184 switch (wait_policy)
4187 LockTupleTuplock(relation, tid, mode);
4190 if (!ConditionalLockTupleTuplock(relation, tid, mode))
4192 result = HeapTupleWouldBlock;
4193 /* recovery code expects to have buffer lock held */
4194 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4199 if (!ConditionalLockTupleTuplock(relation, tid, mode))
4201 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4202 errmsg("could not obtain lock on row in relation \"%s\"",
4203 RelationGetRelationName(relation))));
4206 have_tuple_lock = true;
4210 * Initially assume that we will have to wait for the locking
4211 * transaction(s) to finish. We check various cases below in which
4212 * this can be turned off.
4214 require_sleep = true;
4215 if (mode == LockTupleKeyShare)
4218 * If we're requesting KeyShare, and there's no update present, we
4219 * don't need to wait. Even if there is an update, we can still
4220 * continue if the key hasn't been modified.
4222 * However, if there are updates, we need to walk the update chain
4223 * to mark future versions of the row as locked, too. That way,
4224 * if somebody deletes that future version, we're protected
4225 * against the key going away. This locking of future versions
4226 * could block momentarily, if a concurrent transaction is
4227 * deleting a key; or it could return a value to the effect that
4228 * the transaction deleting the key has already committed. So we
4229 * do this before re-locking the buffer; otherwise this would be
4230 * prone to deadlocks.
4232 * Note that the TID we're locking was grabbed before we unlocked
4233 * the buffer. For it to change while we're not looking, the
4234 * other properties we're testing for below after re-locking the
4235 * buffer would also change, in which case we would restart this
4238 if (!(infomask2 & HEAP_KEYS_UPDATED))
4242 updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4245 * If there are updates, follow the update chain; bail out if
4246 * that cannot be done.
4248 if (follow_updates && updated)
4252 res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4253 GetCurrentTransactionId(),
4255 if (res != HeapTupleMayBeUpdated)
4258 /* recovery code expects to have buffer lock held */
4259 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4264 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4267 * Make sure it's still an appropriate lock, else start over.
4268 * Also, if it wasn't updated before we released the lock, but
4269 * is updated now, we start over too; the reason is that we
4270 * now need to follow the update chain to lock the new
4273 if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4274 ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4278 /* Things look okay, so we can skip sleeping */
4279 require_sleep = false;
4282 * Note we allow Xmax to change here; other updaters/lockers
4283 * could have modified it before we grabbed the buffer lock.
4284 * However, this is not a problem, because with the recheck we
4285 * just did we ensure that they still don't conflict with the
4290 else if (mode == LockTupleShare)
4293 * If we're requesting Share, we can similarly avoid sleeping if
4294 * there's no update and no exclusive lock present.
4296 if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4297 !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4299 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4302 * Make sure it's still an appropriate lock, else start over.
4303 * See above about allowing xmax to change.
4305 if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4306 HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
4308 require_sleep = false;
4311 else if (mode == LockTupleNoKeyExclusive)
4314 * If we're requesting NoKeyExclusive, we might also be able to
4315 * avoid sleeping; just ensure that there's no other lock type
4316 * than KeyShare. Note that this is a bit more involved than just
4317 * checking hint bits -- we need to expand the multixact to figure
4318 * out lock modes for each one (unless there was only one such
4321 if (infomask & HEAP_XMAX_IS_MULTI)
4324 MultiXactMember *members;
4327 * We don't need to allow old multixacts here; if that had
4328 * been the case, HeapTupleSatisfiesUpdate would have returned
4329 * MayBeUpdated and we wouldn't be here.
4332 GetMultiXactIdMembers(xwait, &members, false,
4333 HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4338 * No need to keep the previous xmax here. This is
4339 * unlikely to happen.
4341 require_sleep = false;
4346 bool allowed = true;
4348 for (i = 0; i < nmembers; i++)
4350 if (members[i].status != MultiXactStatusForKeyShare)
4359 * if the xmax changed under us in the meantime, start
4362 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4363 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4364 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
4370 /* otherwise, we're good */
4371 require_sleep = false;
4377 else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4379 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4381 /* if the xmax changed in the meantime, start over */
4382 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4383 !TransactionIdEquals(
4384 HeapTupleHeaderGetRawXmax(tuple->t_data),
4387 /* otherwise, we're good */
4388 require_sleep = false;
4393 * By here, we either have already acquired the buffer exclusive lock,
4394 * or we must wait for the locking transaction or multixact; so below
4395 * we ensure that we grab buffer lock after the sleep.
4400 if (infomask & HEAP_XMAX_IS_MULTI)
4402 MultiXactStatus status = get_mxact_status_for_lock(mode, false);
4404 /* We only ever lock tuples, never update them */
4405 if (status >= MultiXactStatusNoKeyUpdate)
4406 elog(ERROR, "invalid lock mode in heap_lock_tuple");
4408 /* wait for multixact to end, or die trying */
4409 switch (wait_policy)
4412 MultiXactIdWait((MultiXactId) xwait, status, infomask,
4413 relation, &tuple->t_data->t_ctid, XLTW_Lock, NULL);
4416 if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
4417 status, infomask, relation,
4420 result = HeapTupleWouldBlock;
4421 /* recovery code expects to have buffer lock held */
4422 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4427 if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
4428 status, infomask, relation,
4431 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4432 errmsg("could not obtain lock on row in relation \"%s\"",
4433 RelationGetRelationName(relation))));
4438 /* if there are updates, follow the update chain */
4439 if (follow_updates &&
4440 !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4444 res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4445 GetCurrentTransactionId(),
4447 if (res != HeapTupleMayBeUpdated)
4450 /* recovery code expects to have buffer lock held */
4451 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4456 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4459 * If xwait had just locked the tuple then some other xact
4460 * could update this tuple before we get to this point. Check
4461 * for xmax change, and start over if so.
4463 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4464 !TransactionIdEquals(
4465 HeapTupleHeaderGetRawXmax(tuple->t_data),
4470 * Of course, the multixact might not be done here: if we're
4471 * requesting a light lock mode, other transactions with light
4472 * locks could still be alive, as well as locks owned by our
4473 * own xact or other subxacts of this backend. We need to
4474 * preserve the surviving MultiXact members. Note that it
4475 * isn't absolutely necessary in the latter case, but doing so
4481 /* wait for regular transaction to end, or die trying */
4482 switch (wait_policy)
4485 XactLockTableWait(xwait, relation, &tuple->t_data->t_ctid,
4489 if (!ConditionalXactLockTableWait(xwait))
4491 result = HeapTupleWouldBlock;
4492 /* recovery code expects to have buffer lock held */
4493 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4498 if (!ConditionalXactLockTableWait(xwait))
4500 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4501 errmsg("could not obtain lock on row in relation \"%s\"",
4502 RelationGetRelationName(relation))));
4506 /* if there are updates, follow the update chain */
4507 if (follow_updates &&
4508 !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4512 res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4513 GetCurrentTransactionId(),
4515 if (res != HeapTupleMayBeUpdated)
4518 /* recovery code expects to have buffer lock held */
4519 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4524 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4527 * xwait is done, but if xwait had just locked the tuple then
4528 * some other xact could update this tuple before we get to
4529 * this point. Check for xmax change, and start over if so.
4531 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4532 !TransactionIdEquals(
4533 HeapTupleHeaderGetRawXmax(tuple->t_data),
4538 * Otherwise check if it committed or aborted. Note we cannot
4539 * be here if the tuple was only locked by somebody who didn't
4540 * conflict with us; that should have been handled above. So
4541 * that transaction must necessarily be gone by now.
4543 UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
4547 /* By here, we're certain that we hold buffer exclusive lock again */
4550 * We may lock if previous xmax aborted, or if it committed but only
4551 * locked the tuple without updating it; or if we didn't have to wait
4552 * at all for whatever reason.
4554 if (!require_sleep ||
4555 (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
4556 HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4557 HeapTupleHeaderIsOnlyLocked(tuple->t_data))
4558 result = HeapTupleMayBeUpdated;
4560 result = HeapTupleUpdated;
4564 if (result != HeapTupleMayBeUpdated)
4566 Assert(result == HeapTupleSelfUpdated || result == HeapTupleUpdated ||
4567 result == HeapTupleWouldBlock);
4568 Assert(!(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
4569 hufd->ctid = tuple->t_data->t_ctid;
4570 hufd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
4571 if (result == HeapTupleSelfUpdated)
4572 hufd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
4574 hufd->cmax = InvalidCommandId;
4575 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4576 if (have_tuple_lock)
4577 UnlockTupleTuplock(relation, tid, mode);
4581 xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
4582 old_infomask = tuple->t_data->t_infomask;
4585 * We might already hold the desired lock (or stronger), possibly under a
4586 * different subtransaction of the current top transaction. If so, there
4587 * is no need to change state or issue a WAL record. We already handled
4588 * the case where this is true for xmax being a MultiXactId, so now check
4589 * for cases where it is a plain TransactionId.
4591 * Note in particular that this covers the case where we already hold
4592 * exclusive lock on the tuple and the caller only wants key share or
4593 * share lock. It would certainly not do to give up the exclusive lock.
4595 if (!(old_infomask & (HEAP_XMAX_INVALID |
4596 HEAP_XMAX_COMMITTED |
4597 HEAP_XMAX_IS_MULTI)) &&
4598 (mode == LockTupleKeyShare ?
4599 (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask) ||
4600 HEAP_XMAX_IS_SHR_LOCKED(old_infomask) ||
4601 HEAP_XMAX_IS_EXCL_LOCKED(old_infomask)) :
4602 mode == LockTupleShare ?
4603 (HEAP_XMAX_IS_SHR_LOCKED(old_infomask) ||
4604 HEAP_XMAX_IS_EXCL_LOCKED(old_infomask)) :
4605 (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))) &&
4606 TransactionIdIsCurrentTransactionId(xmax))
4608 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4609 /* Probably can't hold tuple lock here, but may as well check */
4610 if (have_tuple_lock)
4611 UnlockTupleTuplock(relation, tid, mode);
4612 return HeapTupleMayBeUpdated;
4616 * If this is the first possibly-multixact-able operation in the current
4617 * transaction, set my per-backend OldestMemberMXactId setting. We can be
4618 * certain that the transaction will never become a member of any older
4619 * MultiXactIds than that. (We have to do this even if we end up just
4620 * using our own TransactionId below, since some other backend could
4621 * incorporate our XID into a MultiXact immediately afterwards.)
4623 MultiXactIdSetOldestMember();
4626 * Compute the new xmax and infomask to store into the tuple. Note we do
4627 * not modify the tuple just yet, because that would leave it in the wrong
4628 * state if multixact.c elogs.
4630 compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
4631 GetCurrentTransactionId(), mode, false,
4632 &xid, &new_infomask, &new_infomask2);
4634 START_CRIT_SECTION();
4637 * Store transaction information of xact locking the tuple.
4639 * Note: Cmax is meaningless in this context, so don't set it; this avoids
4640 * possibly generating a useless combo CID. Moreover, if we're locking a
4641 * previously updated tuple, it's important to preserve the Cmax.
4643 * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
4644 * we would break the HOT chain.
4646 tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
4647 tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4648 tuple->t_data->t_infomask |= new_infomask;
4649 tuple->t_data->t_infomask2 |= new_infomask2;
4650 if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4651 HeapTupleHeaderClearHotUpdated(tuple->t_data);
4652 HeapTupleHeaderSetXmax(tuple->t_data, xid);
4655 * Make sure there is no forward chain link in t_ctid. Note that in the
4656 * cases where the tuple has been updated, we must not overwrite t_ctid,
4657 * because it was set by the updater. Moreover, if the tuple has been
4658 * updated, we need to follow the update chain to lock the new versions of
4659 * the tuple as well.
4661 if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4662 tuple->t_data->t_ctid = *tid;
4664 MarkBufferDirty(*buffer);
4667 * XLOG stuff. You might think that we don't need an XLOG record because
4668 * there is no state change worth restoring after a crash. You would be
4669 * wrong however: we have just written either a TransactionId or a
4670 * MultiXactId that may never have been seen on disk before, and we need
4671 * to make sure that there are XLOG entries covering those ID numbers.
4672 * Else the same IDs might be re-used after a crash, which would be
4673 * disastrous if this page made it to disk before the crash. Essentially
4674 * we have to enforce the WAL log-before-data rule even in this case.
4675 * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
4676 * entries for everything anyway.)
4678 if (RelationNeedsWAL(relation))
4684 XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
4686 xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
4687 xlrec.locking_xid = xid;
4688 xlrec.infobits_set = compute_infobits(new_infomask,
4689 tuple->t_data->t_infomask2);
4690 XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
4692 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
4694 PageSetLSN(page, recptr);
4699 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4702 * Don't update the visibility map here. Locking a tuple doesn't change
4707 * Now that we have successfully marked the tuple as locked, we can
4708 * release the lmgr tuple lock, if we had it.
4710 if (have_tuple_lock)
4711 UnlockTupleTuplock(relation, tid, mode);
4713 return HeapTupleMayBeUpdated;
4718 * Given an original set of Xmax and infomask, and a transaction (identified by
4719 * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
4720 * corresponding infomasks to use on the tuple.
4722 * Note that this might have side effects such as creating a new MultiXactId.
4724 * Most callers will have called HeapTupleSatisfiesUpdate before this function;
4725 * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
4726 * but it was not running anymore. There is a race condition, which is that the
4727 * MultiXactId may have finished since then, but that uncommon case is handled
4728 * either here, or within MultiXactIdExpand.
4730 * There is a similar race condition possible when the old xmax was a regular
4731 * TransactionId. We test TransactionIdIsInProgress again just to narrow the
4732 * window, but it's still possible to end up creating an unnecessary
4733 * MultiXactId. Fortunately this is harmless.
4736 compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
4737 uint16 old_infomask2, TransactionId add_to_xmax,
4738 LockTupleMode mode, bool is_update,
4739 TransactionId *result_xmax, uint16 *result_infomask,
4740 uint16 *result_infomask2)
4742 TransactionId new_xmax;
4743 uint16 new_infomask,
4746 Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
4751 if (old_infomask & HEAP_XMAX_INVALID)
4754 * No previous locker; we just insert our own TransactionId.
4756 * Note that it's critical that this case be the first one checked,
4757 * because there are several blocks below that come back to this one
4758 * to implement certain optimizations; old_infomask might contain
4759 * other dirty bits in those cases, but we don't really care.
4763 new_xmax = add_to_xmax;
4764 if (mode == LockTupleExclusive)
4765 new_infomask2 |= HEAP_KEYS_UPDATED;
4769 new_infomask |= HEAP_XMAX_LOCK_ONLY;
4772 case LockTupleKeyShare:
4773 new_xmax = add_to_xmax;
4774 new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
4776 case LockTupleShare:
4777 new_xmax = add_to_xmax;
4778 new_infomask |= HEAP_XMAX_SHR_LOCK;
4780 case LockTupleNoKeyExclusive:
4781 new_xmax = add_to_xmax;
4782 new_infomask |= HEAP_XMAX_EXCL_LOCK;
4784 case LockTupleExclusive:
4785 new_xmax = add_to_xmax;
4786 new_infomask |= HEAP_XMAX_EXCL_LOCK;
4787 new_infomask2 |= HEAP_KEYS_UPDATED;
4790 new_xmax = InvalidTransactionId; /* silence compiler */
4791 elog(ERROR, "invalid lock mode");
4795 else if (old_infomask & HEAP_XMAX_IS_MULTI)
4797 MultiXactStatus new_status;
4800 * Currently we don't allow XMAX_COMMITTED to be set for multis, so
4803 Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
4806 * A multixact together with LOCK_ONLY set but neither lock bit set
4807 * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
4808 * anymore. This check is critical for databases upgraded by
4809 * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
4810 * that such multis are never passed.
4812 if (!(old_infomask & HEAP_LOCK_MASK) &&
4813 HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
4815 old_infomask &= ~HEAP_XMAX_IS_MULTI;
4816 old_infomask |= HEAP_XMAX_INVALID;
4821 * If the XMAX is already a MultiXactId, then we need to expand it to
4822 * include add_to_xmax; but if all the members were lockers and are
4823 * all gone, we can do away with the IS_MULTI bit and just set
4824 * add_to_xmax as the only locker/updater. If all lockers are gone
4825 * and we have an updater that aborted, we can also do without a
4828 * The cost of doing GetMultiXactIdMembers would be paid by
4829 * MultiXactIdExpand if we weren't to do this, so this check is not
4830 * incurring extra work anyhow.
4832 if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
4834 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
4835 TransactionIdDidAbort(MultiXactIdGetUpdateXid(xmax,
4839 * Reset these bits and restart; otherwise fall through to
4840 * create a new multi below.
4842 old_infomask &= ~HEAP_XMAX_IS_MULTI;
4843 old_infomask |= HEAP_XMAX_INVALID;
4848 new_status = get_mxact_status_for_lock(mode, is_update);
4850 new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
4852 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
4854 else if (old_infomask & HEAP_XMAX_COMMITTED)
4857 * It's a committed update, so we need to preserve him as updater of
4860 MultiXactStatus status;
4861 MultiXactStatus new_status;
4863 if (old_infomask2 & HEAP_KEYS_UPDATED)
4864 status = MultiXactStatusUpdate;
4866 status = MultiXactStatusNoKeyUpdate;
4868 new_status = get_mxact_status_for_lock(mode, is_update);
4871 * since it's not running, it's obviously impossible for the old
4872 * updater to be identical to the current one, so we need not check
4873 * for that case as we do in the block above.
4875 new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
4876 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
4878 else if (TransactionIdIsInProgress(xmax))
4881 * If the XMAX is a valid, in-progress TransactionId, then we need to
4882 * create a new MultiXactId that includes both the old locker or
4883 * updater and our own TransactionId.
4885 MultiXactStatus new_status;
4886 MultiXactStatus old_status;
4887 LockTupleMode old_mode;
4889 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
4891 if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
4892 old_status = MultiXactStatusForKeyShare;
4893 else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
4894 old_status = MultiXactStatusForShare;
4895 else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
4897 if (old_infomask2 & HEAP_KEYS_UPDATED)
4898 old_status = MultiXactStatusForUpdate;
4900 old_status = MultiXactStatusForNoKeyUpdate;
4905 * LOCK_ONLY can be present alone only when a page has been
4906 * upgraded by pg_upgrade. But in that case,
4907 * TransactionIdIsInProgress() should have returned false. We
4908 * assume it's no longer locked in this case.
4910 elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
4911 old_infomask |= HEAP_XMAX_INVALID;
4912 old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
4918 /* it's an update, but which kind? */
4919 if (old_infomask2 & HEAP_KEYS_UPDATED)
4920 old_status = MultiXactStatusUpdate;
4922 old_status = MultiXactStatusNoKeyUpdate;
4925 old_mode = TUPLOCK_from_mxstatus(old_status);
4928 * If the lock to be acquired is for the same TransactionId as the
4929 * existing lock, there's an optimization possible: consider only the
4930 * strongest of both locks as the only one present, and restart.
4932 if (xmax == add_to_xmax)
4935 * Note that it's not possible for the original tuple to be
4936 * updated: we wouldn't be here because the tuple would have been
4937 * invisible and we wouldn't try to update it. As a subtlety,
4938 * this code can also run when traversing an update chain to lock
4939 * future versions of a tuple. But we wouldn't be here either,
4940 * because the add_to_xmax would be different from the original
4943 Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
4945 /* acquire the strongest of both */
4946 if (mode < old_mode)
4948 /* mustn't touch is_update */
4950 old_infomask |= HEAP_XMAX_INVALID;
4954 /* otherwise, just fall back to creating a new multixact */
4955 new_status = get_mxact_status_for_lock(mode, is_update);
4956 new_xmax = MultiXactIdCreate(xmax, old_status,
4957 add_to_xmax, new_status);
4958 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
4960 else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
4961 TransactionIdDidCommit(xmax))
4964 * It's a committed update, so we gotta preserve him as updater of the
4967 MultiXactStatus status;
4968 MultiXactStatus new_status;
4970 if (old_infomask2 & HEAP_KEYS_UPDATED)
4971 status = MultiXactStatusUpdate;
4973 status = MultiXactStatusNoKeyUpdate;
4975 new_status = get_mxact_status_for_lock(mode, is_update);
4978 * since it's not running, it's obviously impossible for the old
4979 * updater to be identical to the current one, so we need not check
4980 * for that case as we do in the block above.
4982 new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
4983 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
4988 * Can get here iff the locking/updating transaction was running when
4989 * the infomask was extracted from the tuple, but finished before
4990 * TransactionIdIsInProgress got to run. Deal with it as if there was
4991 * no locker at all in the first place.
4993 old_infomask |= HEAP_XMAX_INVALID;
4997 *result_infomask = new_infomask;
4998 *result_infomask2 = new_infomask2;
4999 *result_xmax = new_xmax;
5003 * Subroutine for heap_lock_updated_tuple_rec.
5005 * Given an hypothetical multixact status held by the transaction identified
5006 * with the given xid, does the current transaction need to wait, fail, or can
5007 * it continue if it wanted to acquire a lock of the given mode? "needwait"
5008 * is set to true if waiting is necessary; if it can continue, then
5009 * HeapTupleMayBeUpdated is returned. In case of a conflict, a different
5010 * HeapTupleSatisfiesUpdate return code is returned.
5012 * The held status is said to be hypothetical because it might correspond to a
5013 * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
5014 * way for simplicity of API.
5017 test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
5018 LockTupleMode mode, bool *needwait)
5020 MultiXactStatus wantedstatus;
5023 wantedstatus = get_mxact_status_for_lock(mode, false);
5026 * Note: we *must* check TransactionIdIsInProgress before
5027 * TransactionIdDidAbort/Commit; see comment at top of tqual.c for an
5030 if (TransactionIdIsCurrentTransactionId(xid))
5033 * Updated by our own transaction? Just return failure. This
5034 * shouldn't normally happen.
5036 return HeapTupleSelfUpdated;
5038 else if (TransactionIdIsInProgress(xid))
5041 * If the locking transaction is running, what we do depends on
5042 * whether the lock modes conflict: if they do, then we must wait for
5043 * it to finish; otherwise we can fall through to lock this tuple
5044 * version without waiting.
5046 if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5047 LOCKMODE_from_mxstatus(wantedstatus)))
5053 * If we set needwait above, then this value doesn't matter;
5054 * otherwise, this value signals to caller that it's okay to proceed.
5056 return HeapTupleMayBeUpdated;
5058 else if (TransactionIdDidAbort(xid))
5059 return HeapTupleMayBeUpdated;
5060 else if (TransactionIdDidCommit(xid))
5063 * The other transaction committed. If it was only a locker, then the
5064 * lock is completely gone now and we can return success; but if it
5065 * was an update, then what we do depends on whether the two lock
5066 * modes conflict. If they conflict, then we must report error to
5067 * caller. But if they don't, we can fall through to allow the current
5068 * transaction to lock the tuple.
5070 * Note: the reason we worry about ISUPDATE here is because as soon as
5071 * a transaction ends, all its locks are gone and meaningless, and
5072 * thus we can ignore them; whereas its updates persist. In the
5073 * TransactionIdIsInProgress case, above, we don't need to check
5074 * because we know the lock is still "alive" and thus a conflict needs
5075 * always be checked.
5077 if (!ISUPDATE_from_mxstatus(status))
5078 return HeapTupleMayBeUpdated;
5080 if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5081 LOCKMODE_from_mxstatus(wantedstatus)))
5083 return HeapTupleUpdated;
5085 return HeapTupleMayBeUpdated;
5088 /* Not in progress, not aborted, not committed -- must have crashed */
5089 return HeapTupleMayBeUpdated;
5094 * Recursive part of heap_lock_updated_tuple
5096 * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
5097 * xid with the given mode; if this tuple is updated, recurse to lock the new
5101 heap_lock_updated_tuple_rec(Relation rel, ItemPointer tid, TransactionId xid,
5104 ItemPointerData tupid;
5105 HeapTupleData mytup;
5107 uint16 new_infomask,
5113 TransactionId priorXmax = InvalidTransactionId;
5115 ItemPointerCopy(tid, &tupid);
5120 new_xmax = InvalidTransactionId;
5121 ItemPointerCopy(&tupid, &(mytup.t_self));
5123 if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false, NULL))
5126 * if we fail to find the updated version of the tuple, it's
5127 * because it was vacuumed/pruned away after its creator
5128 * transaction aborted. So behave as if we got to the end of the
5129 * chain, and there's no further tuple to lock: return success to
5132 return HeapTupleMayBeUpdated;
5136 CHECK_FOR_INTERRUPTS();
5137 LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5140 * Check the tuple XMIN against prior XMAX, if any. If we reached the
5141 * end of the chain, we're done, so return success.
5143 if (TransactionIdIsValid(priorXmax) &&
5144 !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
5147 UnlockReleaseBuffer(buf);
5148 return HeapTupleMayBeUpdated;
5151 old_infomask = mytup.t_data->t_infomask;
5152 old_infomask2 = mytup.t_data->t_infomask2;
5153 xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5156 * If this tuple version has been updated or locked by some concurrent
5157 * transaction(s), what we do depends on whether our lock mode
5158 * conflicts with what those other transactions hold, and also on the
5161 if (!(old_infomask & HEAP_XMAX_INVALID))
5163 TransactionId rawxmax;
5166 rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5167 if (old_infomask & HEAP_XMAX_IS_MULTI)
5171 MultiXactMember *members;
5173 nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
5174 HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5175 for (i = 0; i < nmembers; i++)
5179 res = test_lockmode_for_conflict(members[i].status,
5185 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5186 XactLockTableWait(members[i].xid, rel,
5187 &mytup.t_data->t_ctid,
5192 if (res != HeapTupleMayBeUpdated)
5194 UnlockReleaseBuffer(buf);
5205 MultiXactStatus status;
5208 * For a non-multi Xmax, we first need to compute the
5209 * corresponding MultiXactStatus by using the infomask bits.
5211 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5213 if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5214 status = MultiXactStatusForKeyShare;
5215 else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5216 status = MultiXactStatusForShare;
5217 else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5219 if (old_infomask2 & HEAP_KEYS_UPDATED)
5220 status = MultiXactStatusForUpdate;
5222 status = MultiXactStatusForNoKeyUpdate;
5227 * LOCK_ONLY present alone (a pg_upgraded tuple marked
5228 * as share-locked in the old cluster) shouldn't be
5229 * seen in the middle of an update chain.
5231 elog(ERROR, "invalid lock status in tuple");
5236 /* it's an update, but which kind? */
5237 if (old_infomask2 & HEAP_KEYS_UPDATED)
5238 status = MultiXactStatusUpdate;
5240 status = MultiXactStatusNoKeyUpdate;
5243 res = test_lockmode_for_conflict(status, rawxmax, mode,
5247 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5248 XactLockTableWait(rawxmax, rel, &mytup.t_data->t_ctid,
5252 if (res != HeapTupleMayBeUpdated)
5254 UnlockReleaseBuffer(buf);
5260 /* compute the new Xmax and infomask values for the tuple ... */
5261 compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
5263 &new_xmax, &new_infomask, &new_infomask2);
5265 START_CRIT_SECTION();
5267 /* ... and set them */
5268 HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
5269 mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
5270 mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5271 mytup.t_data->t_infomask |= new_infomask;
5272 mytup.t_data->t_infomask2 |= new_infomask2;
5274 MarkBufferDirty(buf);
5277 if (RelationNeedsWAL(rel))
5279 xl_heap_lock_updated xlrec;
5281 Page page = BufferGetPage(buf);
5284 XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
5286 xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
5287 xlrec.xmax = new_xmax;
5288 xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
5290 XLogRegisterData((char *) &xlrec, SizeOfHeapLockUpdated);
5292 recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
5294 PageSetLSN(page, recptr);
5299 /* if we find the end of update chain, we're done. */
5300 if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
5301 ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
5302 HeapTupleHeaderIsOnlyLocked(mytup.t_data))
5304 UnlockReleaseBuffer(buf);
5305 return HeapTupleMayBeUpdated;
5308 /* tail recursion */
5309 priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
5310 ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
5311 UnlockReleaseBuffer(buf);
5316 * heap_lock_updated_tuple
5317 * Follow update chain when locking an updated tuple, acquiring locks (row
5318 * marks) on the updated versions.
5320 * The initial tuple is assumed to be already locked.
5322 * This function doesn't check visibility, it just inconditionally marks the
5323 * tuple(s) as locked. If any tuple in the updated chain is being deleted
5324 * concurrently (or updated with the key being modified), sleep until the
5325 * transaction doing it is finished.
5327 * Note that we don't acquire heavyweight tuple locks on the tuples we walk
5328 * when we have to wait for other transactions to release them, as opposed to
5329 * what heap_lock_tuple does. The reason is that having more than one
5330 * transaction walking the chain is probably uncommon enough that risk of
5331 * starvation is not likely: one of the preconditions for being here is that
5332 * the snapshot in use predates the update that created this tuple (because we
5333 * started at an earlier version of the tuple), but at the same time such a
5334 * transaction cannot be using repeatable read or serializable isolation
5335 * levels, because that would lead to a serializability failure.
5338 heap_lock_updated_tuple(Relation rel, HeapTuple tuple, ItemPointer ctid,
5339 TransactionId xid, LockTupleMode mode)
5341 if (!ItemPointerEquals(&tuple->t_self, ctid))
5344 * If this is the first possibly-multixact-able operation in the
5345 * current transaction, set my per-backend OldestMemberMXactId
5346 * setting. We can be certain that the transaction will never become a
5347 * member of any older MultiXactIds than that. (We have to do this
5348 * even if we end up just using our own TransactionId below, since
5349 * some other backend could incorporate our XID into a MultiXact
5350 * immediately afterwards.)
5352 MultiXactIdSetOldestMember();
5354 return heap_lock_updated_tuple_rec(rel, ctid, xid, mode);
5357 /* nothing to lock */
5358 return HeapTupleMayBeUpdated;
5363 * heap_inplace_update - update a tuple "in place" (ie, overwrite it)
5365 * Overwriting violates both MVCC and transactional safety, so the uses
5366 * of this function in Postgres are extremely limited. Nonetheless we
5367 * find some places to use it.
5369 * The tuple cannot change size, and therefore it's reasonable to assume
5370 * that its null bitmap (if any) doesn't change either. So we just
5371 * overwrite the data portion of the tuple without touching the null
5372 * bitmap or any of the header fields.
5374 * tuple is an in-memory tuple structure containing the data to be written
5375 * over the target tuple. Also, tuple->t_self identifies the target tuple.
5378 heap_inplace_update(Relation relation, HeapTuple tuple)
5382 OffsetNumber offnum;
5384 HeapTupleHeader htup;
5388 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&(tuple->t_self)));
5389 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
5390 page = (Page) BufferGetPage(buffer);
5392 offnum = ItemPointerGetOffsetNumber(&(tuple->t_self));
5393 if (PageGetMaxOffsetNumber(page) >= offnum)
5394 lp = PageGetItemId(page, offnum);
5396 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5397 elog(ERROR, "heap_inplace_update: invalid lp");
5399 htup = (HeapTupleHeader) PageGetItem(page, lp);
5401 oldlen = ItemIdGetLength(lp) - htup->t_hoff;
5402 newlen = tuple->t_len - tuple->t_data->t_hoff;
5403 if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
5404 elog(ERROR, "heap_inplace_update: wrong tuple length");
5406 /* NO EREPORT(ERROR) from here till changes are logged */
5407 START_CRIT_SECTION();
5409 memcpy((char *) htup + htup->t_hoff,
5410 (char *) tuple->t_data + tuple->t_data->t_hoff,
5413 MarkBufferDirty(buffer);
5416 if (RelationNeedsWAL(relation))
5418 xl_heap_inplace xlrec;
5421 xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
5424 XLogRegisterData((char *) &xlrec, SizeOfHeapInplace);
5426 XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5427 XLogRegisterBufData(0, (char *) htup + htup->t_hoff, newlen);
5429 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
5431 PageSetLSN(page, recptr);
5436 UnlockReleaseBuffer(buffer);
5439 * Send out shared cache inval if necessary. Note that because we only
5440 * pass the new version of the tuple, this mustn't be used for any
5441 * operations that could change catcache lookup keys. But we aren't
5442 * bothering with index updates either, so that's true a fortiori.
5444 if (!IsBootstrapProcessingMode())
5445 CacheInvalidateHeapTuple(relation, tuple, NULL);
5448 #define FRM_NOOP 0x0001
5449 #define FRM_INVALIDATE_XMAX 0x0002
5450 #define FRM_RETURN_IS_XID 0x0004
5451 #define FRM_RETURN_IS_MULTI 0x0008
5452 #define FRM_MARK_COMMITTED 0x0010
5456 * Determine what to do during freezing when a tuple is marked by a
5459 * NB -- this might have the side-effect of creating a new MultiXactId!
5461 * "flags" is an output value; it's used to tell caller what to do on return.
5462 * Possible flags are:
5464 * don't do anything -- keep existing Xmax
5465 * FRM_INVALIDATE_XMAX
5466 * mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
5468 * The Xid return value is a single update Xid to set as xmax.
5469 * FRM_MARK_COMMITTED
5470 * Xmax can be marked as HEAP_XMAX_COMMITTED
5471 * FRM_RETURN_IS_MULTI
5472 * The return value is a new MultiXactId to set as new Xmax.
5473 * (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
5475 static TransactionId
5476 FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
5477 TransactionId cutoff_xid, MultiXactId cutoff_multi,
5480 TransactionId xid = InvalidTransactionId;
5482 MultiXactMember *members;
5486 MultiXactMember *newmembers;
5488 TransactionId update_xid;
5489 bool update_committed;
5494 /* We should only be called in Multis */
5495 Assert(t_infomask & HEAP_XMAX_IS_MULTI);
5497 if (!MultiXactIdIsValid(multi))
5499 /* Ensure infomask bits are appropriately set/reset */
5500 *flags |= FRM_INVALIDATE_XMAX;
5501 return InvalidTransactionId;
5503 else if (MultiXactIdPrecedes(multi, cutoff_multi))
5506 * This old multi cannot possibly have members still running. If it
5507 * was a locker only, it can be removed without any further
5508 * consideration; but if it contained an update, we might need to
5511 * Don't assert MultiXactIdIsRunning if the multi came from a
5512 * pg_upgrade'd share-locked tuple, though, as doing that causes an
5513 * error to be raised unnecessarily.
5515 Assert((!(t_infomask & HEAP_LOCK_MASK) &&
5516 HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)) ||
5517 !MultiXactIdIsRunning(multi,
5518 HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)));
5519 if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
5521 *flags |= FRM_INVALIDATE_XMAX;
5522 xid = InvalidTransactionId; /* not strictly necessary */
5526 /* replace multi by update xid */
5527 xid = MultiXactIdGetUpdateXid(multi, t_infomask);
5529 /* wasn't only a lock, xid needs to be valid */
5530 Assert(TransactionIdIsValid(xid));
5533 * If the xid is older than the cutoff, it has to have aborted,
5534 * otherwise the tuple would have gotten pruned away.
5536 if (TransactionIdPrecedes(xid, cutoff_xid))
5538 Assert(!TransactionIdDidCommit(xid));
5539 *flags |= FRM_INVALIDATE_XMAX;
5540 xid = InvalidTransactionId; /* not strictly necessary */
5544 *flags |= FRM_RETURN_IS_XID;
5552 * This multixact might have or might not have members still running, but
5553 * we know it's valid and is newer than the cutoff point for multis.
5554 * However, some member(s) of it may be below the cutoff for Xids, so we
5555 * need to walk the whole members array to figure out what to do, if
5559 allow_old = !(t_infomask & HEAP_LOCK_MASK) &&
5560 HEAP_XMAX_IS_LOCKED_ONLY(t_infomask);
5562 GetMultiXactIdMembers(multi, &members, allow_old,
5563 HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
5566 /* Nothing worth keeping */
5567 *flags |= FRM_INVALIDATE_XMAX;
5568 return InvalidTransactionId;
5571 /* is there anything older than the cutoff? */
5572 need_replace = false;
5573 for (i = 0; i < nmembers; i++)
5575 if (TransactionIdPrecedes(members[i].xid, cutoff_xid))
5577 need_replace = true;
5583 * In the simplest case, there is no member older than the cutoff; we can
5584 * keep the existing MultiXactId as is.
5590 return InvalidTransactionId;
5594 * If the multi needs to be updated, figure out which members do we need
5598 newmembers = palloc(sizeof(MultiXactMember) * nmembers);
5599 has_lockers = false;
5600 update_xid = InvalidTransactionId;
5601 update_committed = false;
5603 for (i = 0; i < nmembers; i++)
5606 * Determine whether to keep this member or ignore it.
5608 if (ISUPDATE_from_mxstatus(members[i].status))
5610 TransactionId xid = members[i].xid;
5613 * It's an update; should we keep it? If the transaction is known
5614 * aborted or crashed then it's okay to ignore it, otherwise not.
5615 * Note that an updater older than cutoff_xid cannot possibly be
5616 * committed, because HeapTupleSatisfiesVacuum would have returned
5617 * HEAPTUPLE_DEAD and we would not be trying to freeze the tuple.
5619 * As with all tuple visibility routines, it's critical to test
5620 * TransactionIdIsInProgress before TransactionIdDidCommit,
5621 * because of race conditions explained in detail in tqual.c.
5623 if (TransactionIdIsCurrentTransactionId(xid) ||
5624 TransactionIdIsInProgress(xid))
5626 Assert(!TransactionIdIsValid(update_xid));
5629 else if (TransactionIdDidCommit(xid))
5632 * The transaction committed, so we can tell caller to set
5633 * HEAP_XMAX_COMMITTED. (We can only do this because we know
5634 * the transaction is not running.)
5636 Assert(!TransactionIdIsValid(update_xid));
5637 update_committed = true;
5642 * Not in progress, not committed -- must be aborted or crashed;
5647 * Since the tuple wasn't marked HEAPTUPLE_DEAD by vacuum, the
5648 * update Xid cannot possibly be older than the xid cutoff.
5650 Assert(!TransactionIdIsValid(update_xid) ||
5651 !TransactionIdPrecedes(update_xid, cutoff_xid));
5654 * If we determined that it's an Xid corresponding to an update
5655 * that must be retained, additionally add it to the list of
5656 * members of the new Multi, in case we end up using that. (We
5657 * might still decide to use only an update Xid and not a multi,
5658 * but it's easier to maintain the list as we walk the old members
5661 if (TransactionIdIsValid(update_xid))
5662 newmembers[nnewmembers++] = members[i];
5666 /* We only keep lockers if they are still running */
5667 if (TransactionIdIsCurrentTransactionId(members[i].xid) ||
5668 TransactionIdIsInProgress(members[i].xid))
5670 /* running locker cannot possibly be older than the cutoff */
5671 Assert(!TransactionIdPrecedes(members[i].xid, cutoff_xid));
5672 newmembers[nnewmembers++] = members[i];
5680 if (nnewmembers == 0)
5682 /* nothing worth keeping!? Tell caller to remove the whole thing */
5683 *flags |= FRM_INVALIDATE_XMAX;
5684 xid = InvalidTransactionId;
5686 else if (TransactionIdIsValid(update_xid) && !has_lockers)
5689 * If there's a single member and it's an update, pass it back alone
5690 * without creating a new Multi. (XXX we could do this when there's a
5691 * single remaining locker, too, but that would complicate the API too
5692 * much; moreover, the case with the single updater is more
5693 * interesting, because those are longer-lived.)
5695 Assert(nnewmembers == 1);
5696 *flags |= FRM_RETURN_IS_XID;
5697 if (update_committed)
5698 *flags |= FRM_MARK_COMMITTED;
5704 * Create a new multixact with the surviving members of the previous
5705 * one, to set as new Xmax in the tuple.
5707 xid = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
5708 *flags |= FRM_RETURN_IS_MULTI;
5717 * heap_prepare_freeze_tuple
5719 * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
5720 * are older than the specified cutoff XID and cutoff MultiXactId. If so,
5721 * setup enough state (in the *frz output argument) to later execute and
5722 * WAL-log what we would need to do, and return TRUE. Return FALSE if nothing
5725 * Caller is responsible for setting the offset field, if appropriate.
5727 * It is assumed that the caller has checked the tuple with
5728 * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
5729 * (else we should be removing the tuple, not freezing it).
5731 * NB: cutoff_xid *must* be <= the current global xmin, to ensure that any
5732 * XID older than it could neither be running nor seen as running by any
5733 * open transaction. This ensures that the replacement will not change
5734 * anyone's idea of the tuple state.
5735 * Similarly, cutoff_multi must be less than or equal to the smallest
5736 * MultiXactId used by any transaction currently open.
5738 * If the tuple is in a shared buffer, caller must hold an exclusive lock on
5741 * NB: It is not enough to set hint bits to indicate something is
5742 * committed/invalid -- they might not be set on a standby, or after crash
5743 * recovery. We really need to remove old xids.
5746 heap_prepare_freeze_tuple(HeapTupleHeader tuple, TransactionId cutoff_xid,
5747 TransactionId cutoff_multi,
5748 xl_heap_freeze_tuple *frz)
5751 bool changed = false;
5752 bool freeze_xmax = false;
5756 frz->t_infomask2 = tuple->t_infomask2;
5757 frz->t_infomask = tuple->t_infomask;
5758 frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
5761 xid = HeapTupleHeaderGetXmin(tuple);
5762 if (TransactionIdIsNormal(xid) &&
5763 TransactionIdPrecedes(xid, cutoff_xid))
5765 frz->t_infomask |= HEAP_XMIN_FROZEN;
5770 * Process xmax. To thoroughly examine the current Xmax value we need to
5771 * resolve a MultiXactId to its member Xids, in case some of them are
5772 * below the given cutoff for Xids. In that case, those values might need
5773 * freezing, too. Also, if a multi needs freezing, we cannot simply take
5774 * it out --- if there's a live updater Xid, it needs to be kept.
5776 * Make sure to keep heap_tuple_needs_freeze in sync with this.
5778 xid = HeapTupleHeaderGetRawXmax(tuple);
5780 if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
5782 TransactionId newxmax;
5785 newxmax = FreezeMultiXactId(xid, tuple->t_infomask,
5786 cutoff_xid, cutoff_multi, &flags);
5788 if (flags & FRM_INVALIDATE_XMAX)
5790 else if (flags & FRM_RETURN_IS_XID)
5793 * NB -- some of these transformations are only valid because we
5794 * know the return Xid is a tuple updater (i.e. not merely a
5795 * locker.) Also note that the only reason we don't explicitely
5796 * worry about HEAP_KEYS_UPDATED is because it lives in
5797 * t_infomask2 rather than t_infomask.
5799 frz->t_infomask &= ~HEAP_XMAX_BITS;
5800 frz->xmax = newxmax;
5801 if (flags & FRM_MARK_COMMITTED)
5802 frz->t_infomask &= HEAP_XMAX_COMMITTED;
5805 else if (flags & FRM_RETURN_IS_MULTI)
5811 * We can't use GetMultiXactIdHintBits directly on the new multi
5812 * here; that routine initializes the masks to all zeroes, which
5813 * would lose other bits we need. Doing it this way ensures all
5814 * unrelated bits remain untouched.
5816 frz->t_infomask &= ~HEAP_XMAX_BITS;
5817 frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5818 GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
5819 frz->t_infomask |= newbits;
5820 frz->t_infomask2 |= newbits2;
5822 frz->xmax = newxmax;
5828 Assert(flags & FRM_NOOP);
5831 else if (TransactionIdIsNormal(xid) &&
5832 TransactionIdPrecedes(xid, cutoff_xid))
5839 frz->xmax = InvalidTransactionId;
5842 * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
5843 * LOCKED. Normalize to INVALID just to be sure no one gets confused.
5844 * Also get rid of the HEAP_KEYS_UPDATED bit.
5846 frz->t_infomask &= ~HEAP_XMAX_BITS;
5847 frz->t_infomask |= HEAP_XMAX_INVALID;
5848 frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
5849 frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5854 * Old-style VACUUM FULL is gone, but we have to keep this code as long as
5855 * we support having MOVED_OFF/MOVED_IN tuples in the database.
5857 if (tuple->t_infomask & HEAP_MOVED)
5859 xid = HeapTupleHeaderGetXvac(tuple);
5860 if (TransactionIdIsNormal(xid) &&
5861 TransactionIdPrecedes(xid, cutoff_xid))
5864 * If a MOVED_OFF tuple is not dead, the xvac transaction must
5865 * have failed; whereas a non-dead MOVED_IN tuple must mean the
5866 * xvac transaction succeeded.
5868 if (tuple->t_infomask & HEAP_MOVED_OFF)
5869 frz->frzflags |= XLH_INVALID_XVAC;
5871 frz->frzflags |= XLH_FREEZE_XVAC;
5874 * Might as well fix the hint bits too; usually XMIN_COMMITTED
5875 * will already be set here, but there's a small chance not.
5877 Assert(!(tuple->t_infomask & HEAP_XMIN_INVALID));
5878 frz->t_infomask |= HEAP_XMIN_COMMITTED;
5887 * heap_execute_freeze_tuple
5888 * Execute the prepared freezing of a tuple.
5890 * Caller is responsible for ensuring that no other backend can access the
5891 * storage underlying this tuple, either by holding an exclusive lock on the
5892 * buffer containing it (which is what lazy VACUUM does), or by having it by
5893 * in private storage (which is what CLUSTER and friends do).
5895 * Note: it might seem we could make the changes without exclusive lock, since
5896 * TransactionId read/write is assumed atomic anyway. However there is a race
5897 * condition: someone who just fetched an old XID that we overwrite here could
5898 * conceivably not finish checking the XID against pg_clog before we finish
5899 * the VACUUM and perhaps truncate off the part of pg_clog he needs. Getting
5900 * exclusive lock ensures no other backend is in process of checking the
5901 * tuple status. Also, getting exclusive lock makes it safe to adjust the
5904 * NB: All code in here must be safe to execute during crash recovery!
5907 heap_execute_freeze_tuple(HeapTupleHeader tuple, xl_heap_freeze_tuple *frz)
5909 HeapTupleHeaderSetXmax(tuple, frz->xmax);
5911 if (frz->frzflags & XLH_FREEZE_XVAC)
5912 HeapTupleHeaderSetXvac(tuple, FrozenTransactionId);
5914 if (frz->frzflags & XLH_INVALID_XVAC)
5915 HeapTupleHeaderSetXvac(tuple, InvalidTransactionId);
5917 tuple->t_infomask = frz->t_infomask;
5918 tuple->t_infomask2 = frz->t_infomask2;
5923 * Freeze tuple in place, without WAL logging.
5925 * Useful for callers like CLUSTER that perform their own WAL logging.
5928 heap_freeze_tuple(HeapTupleHeader tuple, TransactionId cutoff_xid,
5929 TransactionId cutoff_multi)
5931 xl_heap_freeze_tuple frz;
5934 do_freeze = heap_prepare_freeze_tuple(tuple, cutoff_xid, cutoff_multi,
5938 * Note that because this is not a WAL-logged operation, we don't need to
5939 * fill in the offset in the freeze record.
5943 heap_execute_freeze_tuple(tuple, &frz);
5948 * For a given MultiXactId, return the hint bits that should be set in the
5951 * Normally this should be called for a multixact that was just created, and
5952 * so is on our local cache, so the GetMembers call is fast.
5955 GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
5956 uint16 *new_infomask2)
5959 MultiXactMember *members;
5961 uint16 bits = HEAP_XMAX_IS_MULTI;
5963 bool has_update = false;
5964 LockTupleMode strongest = LockTupleKeyShare;
5967 * We only use this in multis we just created, so they cannot be values
5970 nmembers = GetMultiXactIdMembers(multi, &members, false, false);
5972 for (i = 0; i < nmembers; i++)
5977 * Remember the strongest lock mode held by any member of the
5980 mode = TUPLOCK_from_mxstatus(members[i].status);
5981 if (mode > strongest)
5984 /* See what other bits we need */
5985 switch (members[i].status)
5987 case MultiXactStatusForKeyShare:
5988 case MultiXactStatusForShare:
5989 case MultiXactStatusForNoKeyUpdate:
5992 case MultiXactStatusForUpdate:
5993 bits2 |= HEAP_KEYS_UPDATED;
5996 case MultiXactStatusNoKeyUpdate:
6000 case MultiXactStatusUpdate:
6001 bits2 |= HEAP_KEYS_UPDATED;
6007 if (strongest == LockTupleExclusive ||
6008 strongest == LockTupleNoKeyExclusive)
6009 bits |= HEAP_XMAX_EXCL_LOCK;
6010 else if (strongest == LockTupleShare)
6011 bits |= HEAP_XMAX_SHR_LOCK;
6012 else if (strongest == LockTupleKeyShare)
6013 bits |= HEAP_XMAX_KEYSHR_LOCK;
6016 bits |= HEAP_XMAX_LOCK_ONLY;
6021 *new_infomask = bits;
6022 *new_infomask2 = bits2;
6026 * MultiXactIdGetUpdateXid
6028 * Given a multixact Xmax and corresponding infomask, which does not have the
6029 * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
6032 * Caller is expected to check the status of the updating transaction, if
6035 static TransactionId
6036 MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
6038 TransactionId update_xact = InvalidTransactionId;
6039 MultiXactMember *members;
6042 Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
6043 Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6046 * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
6049 nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
6055 for (i = 0; i < nmembers; i++)
6057 /* Ignore lockers */
6058 if (!ISUPDATE_from_mxstatus(members[i].status))
6061 /* there can be at most one updater */
6062 Assert(update_xact == InvalidTransactionId);
6063 update_xact = members[i].xid;
6064 #ifndef USE_ASSERT_CHECKING
6067 * in an assert-enabled build, walk the whole array to ensure
6068 * there's no other updater.
6081 * HeapTupleGetUpdateXid
6082 * As above, but use a HeapTupleHeader
6084 * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
6085 * checking the hint bits.
6088 HeapTupleGetUpdateXid(HeapTupleHeader tuple)
6090 return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tuple),
6095 * Do_MultiXactIdWait
6096 * Actual implementation for the two functions below.
6098 * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
6099 * needed to ensure we only sleep on conflicting members, and the infomask is
6100 * used to optimize multixact access in case it's a lock-only multi); 'nowait'
6101 * indicates whether to use conditional lock acquisition, to allow callers to
6102 * fail if lock is unavailable. 'rel', 'ctid' and 'oper' are used to set up
6103 * context information for error messages. 'remaining', if not NULL, receives
6104 * the number of members that are still running, including any (non-aborted)
6105 * subtransactions of our own transaction.
6107 * We do this by sleeping on each member using XactLockTableWait. Any
6108 * members that belong to the current backend are *not* waited for, however;
6109 * this would not merely be useless but would lead to Assert failure inside
6110 * XactLockTableWait. By the time this returns, it is certain that all
6111 * transactions *of other backends* that were members of the MultiXactId
6112 * that conflict with the requested status are dead (and no new ones can have
6113 * been added, since it is not legal to add members to an existing
6116 * But by the time we finish sleeping, someone else may have changed the Xmax
6117 * of the containing tuple, so the caller needs to iterate on us somehow.
6119 * Note that in case we return false, the number of remaining members is
6120 * not to be trusted.
6123 Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
6124 uint16 infomask, bool nowait,
6125 Relation rel, ItemPointer ctid, XLTW_Oper oper,
6130 MultiXactMember *members;
6134 allow_old = !(infomask & HEAP_LOCK_MASK) && HEAP_XMAX_IS_LOCKED_ONLY(infomask);
6135 nmembers = GetMultiXactIdMembers(multi, &members, allow_old,
6136 HEAP_XMAX_IS_LOCKED_ONLY(infomask));
6142 for (i = 0; i < nmembers; i++)
6144 TransactionId memxid = members[i].xid;
6145 MultiXactStatus memstatus = members[i].status;
6147 if (TransactionIdIsCurrentTransactionId(memxid))
6153 if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
6154 LOCKMODE_from_mxstatus(status)))
6156 if (remaining && TransactionIdIsInProgress(memxid))
6162 * This member conflicts with our multi, so we have to sleep (or
6163 * return failure, if asked to avoid waiting.)
6165 * Note that we don't set up an error context callback ourselves,
6166 * but instead we pass the info down to XactLockTableWait. This
6167 * might seem a bit wasteful because the context is set up and
6168 * tore down for each member of the multixact, but in reality it
6169 * should be barely noticeable, and it avoids duplicate code.
6173 result = ConditionalXactLockTableWait(memxid);
6178 XactLockTableWait(memxid, rel, ctid, oper);
6185 *remaining = remain;
6192 * Sleep on a MultiXactId.
6194 * By the time we finish sleeping, someone else may have changed the Xmax
6195 * of the containing tuple, so the caller needs to iterate on us somehow.
6197 * We return (in *remaining, if not NULL) the number of members that are still
6198 * running, including any (non-aborted) subtransactions of our own transaction.
6201 MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
6202 Relation rel, ItemPointer ctid, XLTW_Oper oper,
6205 (void) Do_MultiXactIdWait(multi, status, infomask, false,
6206 rel, ctid, oper, remaining);
6210 * ConditionalMultiXactIdWait
6211 * As above, but only lock if we can get the lock without blocking.
6213 * By the time we finish sleeping, someone else may have changed the Xmax
6214 * of the containing tuple, so the caller needs to iterate on us somehow.
6216 * If the multixact is now all gone, return true. Returns false if some
6217 * transactions might still be running.
6219 * We return (in *remaining, if not NULL) the number of members that are still
6220 * running, including any (non-aborted) subtransactions of our own transaction.
6223 ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
6224 uint16 infomask, Relation rel, int *remaining)
6226 return Do_MultiXactIdWait(multi, status, infomask, true,
6227 rel, NULL, XLTW_None, remaining);
6231 * heap_tuple_needs_freeze
6233 * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
6234 * are older than the specified cutoff XID or MultiXactId. If so, return TRUE.
6236 * It doesn't matter whether the tuple is alive or dead, we are checking
6237 * to see if a tuple needs to be removed or frozen to avoid wraparound.
6239 * NB: Cannot rely on hint bits here, they might not be set after a crash or
6243 heap_tuple_needs_freeze(HeapTupleHeader tuple, TransactionId cutoff_xid,
6244 MultiXactId cutoff_multi, Buffer buf)
6248 xid = HeapTupleHeaderGetXmin(tuple);
6249 if (TransactionIdIsNormal(xid) &&
6250 TransactionIdPrecedes(xid, cutoff_xid))
6254 * The considerations for multixacts are complicated; look at
6255 * heap_freeze_tuple for justifications. This routine had better be in
6256 * sync with that one!
6258 if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
6262 multi = HeapTupleHeaderGetRawXmax(tuple);
6263 if (!MultiXactIdIsValid(multi))
6265 /* no xmax set, ignore */
6268 else if (MultiXactIdPrecedes(multi, cutoff_multi))
6272 MultiXactMember *members;
6277 /* need to check whether any member of the mxact is too old */
6279 allow_old = !(tuple->t_infomask & HEAP_LOCK_MASK) &&
6280 HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask);
6281 nmembers = GetMultiXactIdMembers(multi, &members, allow_old,
6282 HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
6284 for (i = 0; i < nmembers; i++)
6286 if (TransactionIdPrecedes(members[i].xid, cutoff_xid))
6298 xid = HeapTupleHeaderGetRawXmax(tuple);
6299 if (TransactionIdIsNormal(xid) &&
6300 TransactionIdPrecedes(xid, cutoff_xid))
6304 if (tuple->t_infomask & HEAP_MOVED)
6306 xid = HeapTupleHeaderGetXvac(tuple);
6307 if (TransactionIdIsNormal(xid) &&
6308 TransactionIdPrecedes(xid, cutoff_xid))
6316 * If 'tuple' contains any visible XID greater than latestRemovedXid,
6317 * ratchet forwards latestRemovedXid to the greatest one found.
6318 * This is used as the basis for generating Hot Standby conflicts, so
6319 * if a tuple was never visible then removing it should not conflict
6323 HeapTupleHeaderAdvanceLatestRemovedXid(HeapTupleHeader tuple,
6324 TransactionId *latestRemovedXid)
6326 TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
6327 TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
6328 TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
6330 if (tuple->t_infomask & HEAP_MOVED)
6332 if (TransactionIdPrecedes(*latestRemovedXid, xvac))
6333 *latestRemovedXid = xvac;
6337 * Ignore tuples inserted by an aborted transaction or if the tuple was
6338 * updated/deleted by the inserting transaction.
6340 * Look for a committed hint bit, or if no xmin bit is set, check clog.
6341 * This needs to work on both master and standby, where it is used to
6342 * assess btree delete records.
6344 if (HeapTupleHeaderXminCommitted(tuple) ||
6345 (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
6348 TransactionIdFollows(xmax, *latestRemovedXid))
6349 *latestRemovedXid = xmax;
6352 /* *latestRemovedXid may still be invalid at end */
6356 * Perform XLogInsert to register a heap cleanup info message. These
6357 * messages are sent once per VACUUM and are required because
6358 * of the phasing of removal operations during a lazy VACUUM.
6359 * see comments for vacuum_log_cleanup_info().
6362 log_heap_cleanup_info(RelFileNode rnode, TransactionId latestRemovedXid)
6364 xl_heap_cleanup_info xlrec;
6368 xlrec.latestRemovedXid = latestRemovedXid;
6371 XLogRegisterData((char *) &xlrec, SizeOfHeapCleanupInfo);
6373 recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_CLEANUP_INFO);
6379 * Perform XLogInsert for a heap-clean operation. Caller must already
6380 * have modified the buffer and marked it dirty.
6382 * Note: prior to Postgres 8.3, the entries in the nowunused[] array were
6383 * zero-based tuple indexes. Now they are one-based like other uses
6386 * We also include latestRemovedXid, which is the greatest XID present in
6387 * the removed tuples. That allows recovery processing to cancel or wait
6388 * for long standby queries that can still see these tuples.
6391 log_heap_clean(Relation reln, Buffer buffer,
6392 OffsetNumber *redirected, int nredirected,
6393 OffsetNumber *nowdead, int ndead,
6394 OffsetNumber *nowunused, int nunused,
6395 TransactionId latestRemovedXid)
6397 xl_heap_clean xlrec;
6400 /* Caller should not call me on a non-WAL-logged relation */
6401 Assert(RelationNeedsWAL(reln));
6403 xlrec.latestRemovedXid = latestRemovedXid;
6404 xlrec.nredirected = nredirected;
6405 xlrec.ndead = ndead;
6408 XLogRegisterData((char *) &xlrec, SizeOfHeapClean);
6410 XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6413 * The OffsetNumber arrays are not actually in the buffer, but we pretend
6414 * that they are. When XLogInsert stores the whole buffer, the offset
6415 * arrays need not be stored too. Note that even if all three arrays are
6416 * empty, we want to expose the buffer as a candidate for whole-page
6417 * storage, since this record type implies a defragmentation operation
6418 * even if no item pointers changed state.
6420 if (nredirected > 0)
6421 XLogRegisterBufData(0, (char *) redirected,
6422 nredirected * sizeof(OffsetNumber) * 2);
6425 XLogRegisterBufData(0, (char *) nowdead,
6426 ndead * sizeof(OffsetNumber));
6429 XLogRegisterBufData(0, (char *) nowunused,
6430 nunused * sizeof(OffsetNumber));
6432 recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_CLEAN);
6438 * Perform XLogInsert for a heap-freeze operation. Caller must have already
6439 * modified the buffer and marked it dirty.
6442 log_heap_freeze(Relation reln, Buffer buffer, TransactionId cutoff_xid,
6443 xl_heap_freeze_tuple *tuples, int ntuples)
6445 xl_heap_freeze_page xlrec;
6448 /* Caller should not call me on a non-WAL-logged relation */
6449 Assert(RelationNeedsWAL(reln));
6450 /* nor when there are no tuples to freeze */
6451 Assert(ntuples > 0);
6453 xlrec.cutoff_xid = cutoff_xid;
6454 xlrec.ntuples = ntuples;
6457 XLogRegisterData((char *) &xlrec, SizeOfHeapFreezePage);
6460 * The freeze plan array is not actually in the buffer, but pretend that
6461 * it is. When XLogInsert stores the whole buffer, the freeze plan need
6462 * not be stored too.
6464 XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6465 XLogRegisterBufData(0, (char *) tuples,
6466 ntuples * sizeof(xl_heap_freeze_tuple));
6468 recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_FREEZE_PAGE);
6474 * Perform XLogInsert for a heap-visible operation. 'block' is the block
6475 * being marked all-visible, and vm_buffer is the buffer containing the
6476 * corresponding visibility map block. Both should have already been modified
6479 * If checksums are enabled, we also generate a full-page image of
6480 * heap_buffer, if necessary.
6483 log_heap_visible(RelFileNode rnode, Buffer heap_buffer, Buffer vm_buffer,
6484 TransactionId cutoff_xid)
6486 xl_heap_visible xlrec;
6490 Assert(BufferIsValid(heap_buffer));
6491 Assert(BufferIsValid(vm_buffer));
6493 xlrec.cutoff_xid = cutoff_xid;
6495 XLogRegisterData((char *) &xlrec, SizeOfHeapVisible);
6497 XLogRegisterBuffer(0, vm_buffer, 0);
6499 flags = REGBUF_STANDARD;
6500 if (!XLogHintBitIsNeeded())
6501 flags |= REGBUF_NO_IMAGE;
6502 XLogRegisterBuffer(1, heap_buffer, flags);
6504 recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE);
6510 * Perform XLogInsert for a heap-update operation. Caller must already
6511 * have modified the buffer(s) and marked them dirty.
6514 log_heap_update(Relation reln, Buffer oldbuf,
6515 Buffer newbuf, HeapTuple oldtup, HeapTuple newtup,
6516 HeapTuple old_key_tuple,
6517 bool all_visible_cleared, bool new_all_visible_cleared)
6519 xl_heap_update xlrec;
6520 xl_heap_header xlhdr;
6521 xl_heap_header xlhdr_idx;
6523 uint16 prefix_suffix[2];
6524 uint16 prefixlen = 0,
6527 Page page = BufferGetPage(newbuf);
6528 bool need_tuple_data = RelationIsLogicallyLogged(reln);
6532 /* Caller should not call me on a non-WAL-logged relation */
6533 Assert(RelationNeedsWAL(reln));
6537 if (HeapTupleIsHeapOnly(newtup))
6538 info = XLOG_HEAP_HOT_UPDATE;
6540 info = XLOG_HEAP_UPDATE;
6543 * If the old and new tuple are on the same page, we only need to log the
6544 * parts of the new tuple that were changed. That saves on the amount of
6545 * WAL we need to write. Currently, we just count any unchanged bytes in
6546 * the beginning and end of the tuple. That's quick to check, and
6547 * perfectly covers the common case that only one field is updated.
6549 * We could do this even if the old and new tuple are on different pages,
6550 * but only if we don't make a full-page image of the old page, which is
6551 * difficult to know in advance. Also, if the old tuple is corrupt for
6552 * some reason, it would allow the corruption to propagate the new page,
6553 * so it seems best to avoid. Under the general assumption that most
6554 * updates tend to create the new tuple version on the same page, there
6555 * isn't much to be gained by doing this across pages anyway.
6557 * Skip this if we're taking a full-page image of the new page, as we
6558 * don't include the new tuple in the WAL record in that case. Also
6559 * disable if wal_level='logical', as logical decoding needs to be able to
6560 * read the new tuple in whole from the WAL record alone.
6562 if (oldbuf == newbuf && !need_tuple_data &&
6563 !XLogCheckBufferNeedsBackup(newbuf))
6565 char *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
6566 char *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
6567 int oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
6568 int newlen = newtup->t_len - newtup->t_data->t_hoff;
6570 /* Check for common prefix between old and new tuple */
6571 for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
6573 if (newp[prefixlen] != oldp[prefixlen])
6578 * Storing the length of the prefix takes 2 bytes, so we need to save
6579 * at least 3 bytes or there's no point.
6584 /* Same for suffix */
6585 for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
6587 if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
6594 /* Prepare main WAL data chain */
6596 if (all_visible_cleared)
6597 xlrec.flags |= XLOG_HEAP_ALL_VISIBLE_CLEARED;
6598 if (new_all_visible_cleared)
6599 xlrec.flags |= XLOG_HEAP_NEW_ALL_VISIBLE_CLEARED;
6601 xlrec.flags |= XLOG_HEAP_PREFIX_FROM_OLD;
6603 xlrec.flags |= XLOG_HEAP_SUFFIX_FROM_OLD;
6604 if (need_tuple_data)
6606 xlrec.flags |= XLOG_HEAP_CONTAINS_NEW_TUPLE;
6609 if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
6610 xlrec.flags |= XLOG_HEAP_CONTAINS_OLD_TUPLE;
6612 xlrec.flags |= XLOG_HEAP_CONTAINS_OLD_KEY;
6616 /* If new tuple is the single and first tuple on page... */
6617 if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
6618 PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
6620 info |= XLOG_HEAP_INIT_PAGE;
6626 /* Prepare WAL data for the old page */
6627 xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
6628 xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
6629 xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
6630 oldtup->t_data->t_infomask2);
6632 /* Prepare WAL data for the new page */
6633 xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
6634 xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
6636 bufflags = REGBUF_STANDARD;
6638 bufflags |= REGBUF_WILL_INIT;
6639 if (need_tuple_data)
6640 bufflags |= REGBUF_KEEP_DATA;
6642 XLogRegisterBuffer(0, newbuf, bufflags);
6643 if (oldbuf != newbuf)
6644 XLogRegisterBuffer(1, oldbuf, REGBUF_STANDARD);
6646 XLogRegisterData((char *) &xlrec, SizeOfHeapUpdate);
6649 * Prepare WAL data for the new tuple.
6651 if (prefixlen > 0 || suffixlen > 0)
6653 if (prefixlen > 0 && suffixlen > 0)
6655 prefix_suffix[0] = prefixlen;
6656 prefix_suffix[1] = suffixlen;
6657 XLogRegisterBufData(0, (char *) &prefix_suffix, sizeof(uint16) * 2);
6659 else if (prefixlen > 0)
6661 XLogRegisterBufData(0, (char *) &prefixlen, sizeof(uint16));
6665 XLogRegisterBufData(0, (char *) &suffixlen, sizeof(uint16));
6669 xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
6670 xlhdr.t_infomask = newtup->t_data->t_infomask;
6671 xlhdr.t_hoff = newtup->t_data->t_hoff;
6672 Assert(offsetof(HeapTupleHeaderData, t_bits) + prefixlen + suffixlen <= newtup->t_len);
6675 * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
6677 * The 'data' doesn't include the common prefix or suffix.
6679 XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
6682 XLogRegisterBufData(0,
6683 ((char *) newtup->t_data) + offsetof(HeapTupleHeaderData, t_bits),
6684 newtup->t_len - offsetof(HeapTupleHeaderData, t_bits) -suffixlen);
6689 * Have to write the null bitmap and data after the common prefix as
6690 * two separate rdata entries.
6692 /* bitmap [+ padding] [+ oid] */
6693 if (newtup->t_data->t_hoff - offsetof(HeapTupleHeaderData, t_bits) >0)
6695 XLogRegisterBufData(0,
6696 ((char *) newtup->t_data) + offsetof(HeapTupleHeaderData, t_bits),
6697 newtup->t_data->t_hoff - offsetof(HeapTupleHeaderData, t_bits));
6700 /* data after common prefix */
6701 XLogRegisterBufData(0,
6702 ((char *) newtup->t_data) + newtup->t_data->t_hoff + prefixlen,
6703 newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
6706 /* We need to log a tuple identity */
6707 if (need_tuple_data && old_key_tuple)
6709 /* don't really need this, but its more comfy to decode */
6710 xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
6711 xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
6712 xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
6714 XLogRegisterData((char *) &xlhdr_idx, SizeOfHeapHeader);
6716 /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
6717 XLogRegisterData((char *) old_key_tuple->t_data + offsetof(HeapTupleHeaderData, t_bits),
6718 old_key_tuple->t_len - offsetof(HeapTupleHeaderData, t_bits));
6721 recptr = XLogInsert(RM_HEAP_ID, info);
6727 * Perform XLogInsert of a XLOG_HEAP2_NEW_CID record
6729 * This is only used in wal_level >= WAL_LEVEL_LOGICAL, and only for catalog
6733 log_heap_new_cid(Relation relation, HeapTuple tup)
6735 xl_heap_new_cid xlrec;
6738 HeapTupleHeader hdr = tup->t_data;
6740 Assert(ItemPointerIsValid(&tup->t_self));
6741 Assert(tup->t_tableOid != InvalidOid);
6743 xlrec.top_xid = GetTopTransactionId();
6744 xlrec.target_node = relation->rd_node;
6745 xlrec.target_tid = tup->t_self;
6748 * If the tuple got inserted & deleted in the same TX we definitely have a
6749 * combocid, set cmin and cmax.
6751 if (hdr->t_infomask & HEAP_COMBOCID)
6753 Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
6754 Assert(!HeapTupleHeaderXminInvalid(hdr));
6755 xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
6756 xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
6757 xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
6759 /* No combocid, so only cmin or cmax can be set by this TX */
6765 * We need to check for LOCK ONLY because multixacts might be
6766 * transferred to the new tuple in case of FOR KEY SHARE updates in
6767 * which case there will be a xmax, although the tuple just got
6770 if (hdr->t_infomask & HEAP_XMAX_INVALID ||
6771 HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
6773 xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
6774 xlrec.cmax = InvalidCommandId;
6776 /* Tuple from a different tx updated or deleted. */
6779 xlrec.cmin = InvalidCommandId;
6780 xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
6783 xlrec.combocid = InvalidCommandId;
6787 * Note that we don't need to register the buffer here, because this
6788 * operation does not modify the page. The insert/update/delete that
6789 * called us certainly did, but that's WAL-logged separately.
6792 XLogRegisterData((char *) &xlrec, SizeOfHeapNewCid);
6794 recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
6800 * Build a heap tuple representing the configured REPLICA IDENTITY to represent
6801 * the old tuple in a UPDATE or DELETE.
6803 * Returns NULL if there's no need to log a identity or if there's no suitable
6804 * key in the Relation relation.
6807 ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_changed, bool *copy)
6809 TupleDesc desc = RelationGetDescr(relation);
6813 char replident = relation->rd_rel->relreplident;
6814 HeapTuple key_tuple = NULL;
6815 bool nulls[MaxHeapAttributeNumber];
6816 Datum values[MaxHeapAttributeNumber];
6821 if (!RelationIsLogicallyLogged(relation))
6824 if (replident == REPLICA_IDENTITY_NOTHING)
6827 if (replident == REPLICA_IDENTITY_FULL)
6830 * When logging the entire old tuple, it very well could contain
6831 * toasted columns. If so, force them to be inlined.
6833 if (HeapTupleHasExternal(tp))
6836 tp = toast_flatten_tuple(tp, RelationGetDescr(relation));
6841 /* if the key hasn't changed and we're only logging the key, we're done */
6845 /* find the replica identity index */
6846 replidindex = RelationGetReplicaIndex(relation);
6847 if (!OidIsValid(replidindex))
6849 elog(DEBUG4, "could not find configured replica identity for table \"%s\"",
6850 RelationGetRelationName(relation));
6854 idx_rel = RelationIdGetRelation(replidindex);
6855 idx_desc = RelationGetDescr(idx_rel);
6857 /* deform tuple, so we have fast access to columns */
6858 heap_deform_tuple(tp, desc, values, nulls);
6860 /* set all columns to NULL, regardless of whether they actually are */
6861 memset(nulls, 1, sizeof(nulls));
6864 * Now set all columns contained in the index to NOT NULL, they cannot
6865 * currently be NULL.
6867 for (natt = 0; natt < idx_desc->natts; natt++)
6869 int attno = idx_rel->rd_index->indkey.values[natt];
6874 * The OID column can appear in an index definition, but that's
6875 * OK, becuse we always copy the OID if present (see below). Other
6876 * system columns may not.
6878 if (attno == ObjectIdAttributeNumber)
6880 elog(ERROR, "system column in index");
6882 nulls[attno - 1] = false;
6885 key_tuple = heap_form_tuple(desc, values, nulls);
6887 RelationClose(idx_rel);
6890 * Always copy oids if the table has them, even if not included in the
6891 * index. The space in the logged tuple is used anyway, so there's little
6892 * point in not including the information.
6894 if (relation->rd_rel->relhasoids)
6895 HeapTupleSetOid(key_tuple, HeapTupleGetOid(tp));
6898 * If the tuple, which by here only contains indexed columns, still has
6899 * toasted columns, force them to be inlined. This is somewhat unlikely
6900 * since there's limits on the size of indexed columns, so we don't
6901 * duplicate toast_flatten_tuple()s functionality in the above loop over
6902 * the indexed columns, even if it would be more efficient.
6904 if (HeapTupleHasExternal(key_tuple))
6906 HeapTuple oldtup = key_tuple;
6908 key_tuple = toast_flatten_tuple(oldtup, RelationGetDescr(relation));
6909 heap_freetuple(oldtup);
6916 * Handles CLEANUP_INFO
6919 heap_xlog_cleanup_info(XLogReaderState *record)
6921 xl_heap_cleanup_info *xlrec = (xl_heap_cleanup_info *) XLogRecGetData(record);
6924 ResolveRecoveryConflictWithSnapshot(xlrec->latestRemovedXid, xlrec->node);
6927 * Actual operation is a no-op. Record type exists to provide a means for
6928 * conflict processing to occur before we begin index vacuum actions. see
6929 * vacuumlazy.c and also comments in btvacuumpage()
6932 /* Backup blocks are not used in cleanup_info records */
6933 Assert(!XLogRecHasAnyBlockRefs(record));
6937 * Handles HEAP2_CLEAN record type
6940 heap_xlog_clean(XLogReaderState *record)
6942 XLogRecPtr lsn = record->EndRecPtr;
6943 xl_heap_clean *xlrec = (xl_heap_clean *) XLogRecGetData(record);
6948 XLogRedoAction action;
6950 XLogRecGetBlockTag(record, 0, &rnode, NULL, &blkno);
6953 * We're about to remove tuples. In Hot Standby mode, ensure that there's
6954 * no queries running for which the removed tuples are still visible.
6956 * Not all HEAP2_CLEAN records remove tuples with xids, so we only want to
6957 * conflict on the records that cause MVCC failures for user queries. If
6958 * latestRemovedXid is invalid, skip conflict processing.
6960 if (InHotStandby && TransactionIdIsValid(xlrec->latestRemovedXid))
6961 ResolveRecoveryConflictWithSnapshot(xlrec->latestRemovedXid, rnode);
6964 * If we have a full-page image, restore it (using a cleanup lock) and
6967 action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true,
6969 if (action == BLK_NEEDS_REDO)
6971 Page page = (Page) BufferGetPage(buffer);
6973 OffsetNumber *redirected;
6974 OffsetNumber *nowdead;
6975 OffsetNumber *nowunused;
6981 redirected = (OffsetNumber *) XLogRecGetBlockData(record, 0, &datalen);
6983 nredirected = xlrec->nredirected;
6984 ndead = xlrec->ndead;
6985 end = (OffsetNumber *) ((char *) redirected + datalen);
6986 nowdead = redirected + (nredirected * 2);
6987 nowunused = nowdead + ndead;
6988 nunused = (end - nowunused);
6989 Assert(nunused >= 0);
6991 /* Update all item pointers per the record, and repair fragmentation */
6992 heap_page_prune_execute(buffer,
6993 redirected, nredirected,
6995 nowunused, nunused);
6997 freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
7000 * Note: we don't worry about updating the page's prunability hints.
7001 * At worst this will cause an extra prune cycle to occur soon.
7004 PageSetLSN(page, lsn);
7005 MarkBufferDirty(buffer);
7007 if (BufferIsValid(buffer))
7008 UnlockReleaseBuffer(buffer);
7011 * Update the FSM as well.
7013 * XXX: Don't do this if the page was restored from full page image. We
7014 * don't bother to update the FSM in that case, it doesn't need to be
7015 * totally accurate anyway.
7017 if (action == BLK_NEEDS_REDO)
7018 XLogRecordPageWithFreeSpace(rnode, blkno, freespace);
7022 * Replay XLOG_HEAP2_VISIBLE record.
7024 * The critical integrity requirement here is that we must never end up with
7025 * a situation where the visibility map bit is set, and the page-level
7026 * PD_ALL_VISIBLE bit is clear. If that were to occur, then a subsequent
7027 * page modification would fail to clear the visibility map bit.
7030 heap_xlog_visible(XLogReaderState *record)
7032 XLogRecPtr lsn = record->EndRecPtr;
7033 xl_heap_visible *xlrec = (xl_heap_visible *) XLogRecGetData(record);
7034 Buffer vmbuffer = InvalidBuffer;
7039 XLogRedoAction action;
7041 XLogRecGetBlockTag(record, 1, &rnode, NULL, &blkno);
7044 * If there are any Hot Standby transactions running that have an xmin
7045 * horizon old enough that this page isn't all-visible for them, they
7046 * might incorrectly decide that an index-only scan can skip a heap fetch.
7048 * NB: It might be better to throw some kind of "soft" conflict here that
7049 * forces any index-only scan that is in flight to perform heap fetches,
7050 * rather than killing the transaction outright.
7053 ResolveRecoveryConflictWithSnapshot(xlrec->cutoff_xid, rnode);
7056 * Read the heap page, if it still exists. If the heap file has dropped or
7057 * truncated later in recovery, we don't need to update the page, but we'd
7058 * better still update the visibility map.
7060 action = XLogReadBufferForRedo(record, 1, &buffer);
7061 if (action == BLK_NEEDS_REDO)
7064 * We don't bump the LSN of the heap page when setting the visibility
7065 * map bit (unless checksums are enabled, in which case we must),
7066 * because that would generate an unworkable volume of full-page
7067 * writes. This exposes us to torn page hazards, but since we're not
7068 * inspecting the existing page contents in any way, we don't care.
7070 * However, all operations that clear the visibility map bit *do* bump
7071 * the LSN, and those operations will only be replayed if the XLOG LSN
7072 * follows the page LSN. Thus, if the page LSN has advanced past our
7073 * XLOG record's LSN, we mustn't mark the page all-visible, because
7074 * the subsequent update won't be replayed to clear the flag.
7076 page = BufferGetPage(buffer);
7077 PageSetAllVisible(page);
7078 MarkBufferDirty(buffer);
7080 else if (action == BLK_RESTORED)
7083 * If heap block was backed up, restore it. This can only happen with
7084 * checksums enabled.
7086 Assert(DataChecksumsEnabled());
7088 if (BufferIsValid(buffer))
7089 UnlockReleaseBuffer(buffer);
7092 * Even if we skipped the heap page update due to the LSN interlock, it's
7093 * still safe to update the visibility map. Any WAL record that clears
7094 * the visibility map bit does so before checking the page LSN, so any
7095 * bits that need to be cleared will still be cleared.
7097 if (XLogReadBufferForRedoExtended(record, 0, RBM_ZERO_ON_ERROR, false,
7098 &vmbuffer) == BLK_NEEDS_REDO)
7100 Page vmpage = BufferGetPage(vmbuffer);
7103 /* initialize the page if it was read as zeros */
7104 if (PageIsNew(vmpage))
7105 PageInit(vmpage, BLCKSZ, 0);
7108 * XLogReplayBufferExtended locked the buffer. But visibilitymap_set
7109 * will handle locking itself.
7111 LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
7113 reln = CreateFakeRelcacheEntry(rnode);
7114 visibilitymap_pin(reln, blkno, &vmbuffer);
7117 * Don't set the bit if replay has already passed this point.
7119 * It might be safe to do this unconditionally; if replay has passed
7120 * this point, we'll replay at least as far this time as we did
7121 * before, and if this bit needs to be cleared, the record responsible
7122 * for doing so should be again replayed, and clear it. For right
7123 * now, out of an abundance of conservatism, we use the same test here
7124 * we did for the heap page. If this results in a dropped bit, no
7125 * real harm is done; and the next VACUUM will fix it.
7127 if (lsn > PageGetLSN(vmpage))
7128 visibilitymap_set(reln, blkno, InvalidBuffer, lsn, vmbuffer,
7131 ReleaseBuffer(vmbuffer);
7132 FreeFakeRelcacheEntry(reln);
7134 else if (BufferIsValid(vmbuffer))
7135 UnlockReleaseBuffer(vmbuffer);
7139 * Replay XLOG_HEAP2_FREEZE_PAGE records
7142 heap_xlog_freeze_page(XLogReaderState *record)
7144 XLogRecPtr lsn = record->EndRecPtr;
7145 xl_heap_freeze_page *xlrec = (xl_heap_freeze_page *) XLogRecGetData(record);
7146 TransactionId cutoff_xid = xlrec->cutoff_xid;
7151 * In Hot Standby mode, ensure that there's no queries running which still
7152 * consider the frozen xids as running.
7158 XLogRecGetBlockTag(record, 0, &rnode, NULL, NULL);
7159 ResolveRecoveryConflictWithSnapshot(cutoff_xid, rnode);
7162 if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
7164 Page page = BufferGetPage(buffer);
7165 xl_heap_freeze_tuple *tuples;
7167 tuples = (xl_heap_freeze_tuple *) XLogRecGetBlockData(record, 0, NULL);
7169 /* now execute freeze plan for each frozen tuple */
7170 for (ntup = 0; ntup < xlrec->ntuples; ntup++)
7172 xl_heap_freeze_tuple *xlrec_tp;
7174 HeapTupleHeader tuple;
7176 xlrec_tp = &tuples[ntup];
7177 lp = PageGetItemId(page, xlrec_tp->offset); /* offsets are one-based */
7178 tuple = (HeapTupleHeader) PageGetItem(page, lp);
7180 heap_execute_freeze_tuple(tuple, xlrec_tp);
7183 PageSetLSN(page, lsn);
7184 MarkBufferDirty(buffer);
7186 if (BufferIsValid(buffer))
7187 UnlockReleaseBuffer(buffer);
7191 * Given an "infobits" field from an XLog record, set the correct bits in the
7192 * given infomask and infomask2 for the tuple touched by the record.
7194 * (This is the reverse of compute_infobits).
7197 fix_infomask_from_infobits(uint8 infobits, uint16 *infomask, uint16 *infomask2)
7199 *infomask &= ~(HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY |
7200 HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_EXCL_LOCK);
7201 *infomask2 &= ~HEAP_KEYS_UPDATED;
7203 if (infobits & XLHL_XMAX_IS_MULTI)
7204 *infomask |= HEAP_XMAX_IS_MULTI;
7205 if (infobits & XLHL_XMAX_LOCK_ONLY)
7206 *infomask |= HEAP_XMAX_LOCK_ONLY;
7207 if (infobits & XLHL_XMAX_EXCL_LOCK)
7208 *infomask |= HEAP_XMAX_EXCL_LOCK;
7209 /* note HEAP_XMAX_SHR_LOCK isn't considered here */
7210 if (infobits & XLHL_XMAX_KEYSHR_LOCK)
7211 *infomask |= HEAP_XMAX_KEYSHR_LOCK;
7213 if (infobits & XLHL_KEYS_UPDATED)
7214 *infomask2 |= HEAP_KEYS_UPDATED;
7218 heap_xlog_delete(XLogReaderState *record)
7220 XLogRecPtr lsn = record->EndRecPtr;
7221 xl_heap_delete *xlrec = (xl_heap_delete *) XLogRecGetData(record);
7225 HeapTupleHeader htup;
7227 RelFileNode target_node;
7228 ItemPointerData target_tid;
7230 XLogRecGetBlockTag(record, 0, &target_node, NULL, &blkno);
7231 ItemPointerSetBlockNumber(&target_tid, blkno);
7232 ItemPointerSetOffsetNumber(&target_tid, xlrec->offnum);
7235 * The visibility map may need to be fixed even if the heap page is
7236 * already up-to-date.
7238 if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7240 Relation reln = CreateFakeRelcacheEntry(target_node);
7241 Buffer vmbuffer = InvalidBuffer;
7243 visibilitymap_pin(reln, blkno, &vmbuffer);
7244 visibilitymap_clear(reln, blkno, vmbuffer);
7245 ReleaseBuffer(vmbuffer);
7246 FreeFakeRelcacheEntry(reln);
7249 if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
7251 page = BufferGetPage(buffer);
7253 if (PageGetMaxOffsetNumber(page) >= xlrec->offnum)
7254 lp = PageGetItemId(page, xlrec->offnum);
7256 if (PageGetMaxOffsetNumber(page) < xlrec->offnum || !ItemIdIsNormal(lp))
7257 elog(PANIC, "heap_delete_redo: invalid lp");
7259 htup = (HeapTupleHeader) PageGetItem(page, lp);
7261 htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
7262 htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7263 HeapTupleHeaderClearHotUpdated(htup);
7264 fix_infomask_from_infobits(xlrec->infobits_set,
7265 &htup->t_infomask, &htup->t_infomask2);
7266 HeapTupleHeaderSetXmax(htup, xlrec->xmax);
7267 HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
7269 /* Mark the page as a candidate for pruning */
7270 PageSetPrunable(page, XLogRecGetXid(record));
7272 if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7273 PageClearAllVisible(page);
7275 /* Make sure there is no forward chain link in t_ctid */
7276 htup->t_ctid = target_tid;
7277 PageSetLSN(page, lsn);
7278 MarkBufferDirty(buffer);
7280 if (BufferIsValid(buffer))
7281 UnlockReleaseBuffer(buffer);
7285 heap_xlog_insert(XLogReaderState *record)
7287 XLogRecPtr lsn = record->EndRecPtr;
7288 xl_heap_insert *xlrec = (xl_heap_insert *) XLogRecGetData(record);
7293 HeapTupleHeaderData hdr;
7294 char data[MaxHeapTupleSize];
7296 HeapTupleHeader htup;
7297 xl_heap_header xlhdr;
7300 RelFileNode target_node;
7302 ItemPointerData target_tid;
7303 XLogRedoAction action;
7305 XLogRecGetBlockTag(record, 0, &target_node, NULL, &blkno);
7306 ItemPointerSetBlockNumber(&target_tid, blkno);
7307 ItemPointerSetOffsetNumber(&target_tid, xlrec->offnum);
7310 * The visibility map may need to be fixed even if the heap page is
7311 * already up-to-date.
7313 if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7315 Relation reln = CreateFakeRelcacheEntry(target_node);
7316 Buffer vmbuffer = InvalidBuffer;
7318 visibilitymap_pin(reln, blkno, &vmbuffer);
7319 visibilitymap_clear(reln, blkno, vmbuffer);
7320 ReleaseBuffer(vmbuffer);
7321 FreeFakeRelcacheEntry(reln);
7325 * If we inserted the first and only tuple on the page, re-initialize the
7326 * page from scratch.
7328 if (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE)
7330 buffer = XLogInitBufferForRedo(record, 0);
7331 page = BufferGetPage(buffer);
7332 PageInit(page, BufferGetPageSize(buffer), 0);
7333 action = BLK_NEEDS_REDO;
7336 action = XLogReadBufferForRedo(record, 0, &buffer);
7337 if (action == BLK_NEEDS_REDO)
7342 page = BufferGetPage(buffer);
7344 if (PageGetMaxOffsetNumber(page) + 1 < xlrec->offnum)
7345 elog(PANIC, "heap_insert_redo: invalid max offset number");
7347 data = XLogRecGetBlockData(record, 0, &datalen);
7349 newlen = datalen - SizeOfHeapHeader;
7350 Assert(datalen > SizeOfHeapHeader && newlen <= MaxHeapTupleSize);
7351 memcpy((char *) &xlhdr, data, SizeOfHeapHeader);
7352 data += SizeOfHeapHeader;
7355 MemSet((char *) htup, 0, sizeof(HeapTupleHeaderData));
7356 /* PG73FORMAT: get bitmap [+ padding] [+ oid] + data */
7357 memcpy((char *) htup + offsetof(HeapTupleHeaderData, t_bits),
7360 newlen += offsetof(HeapTupleHeaderData, t_bits);
7361 htup->t_infomask2 = xlhdr.t_infomask2;
7362 htup->t_infomask = xlhdr.t_infomask;
7363 htup->t_hoff = xlhdr.t_hoff;
7364 HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
7365 HeapTupleHeaderSetCmin(htup, FirstCommandId);
7366 htup->t_ctid = target_tid;
7368 if (PageAddItem(page, (Item) htup, newlen, xlrec->offnum,
7369 true, true) == InvalidOffsetNumber)
7370 elog(PANIC, "heap_insert_redo: failed to add tuple");
7372 freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
7374 PageSetLSN(page, lsn);
7376 if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7377 PageClearAllVisible(page);
7379 MarkBufferDirty(buffer);
7381 if (BufferIsValid(buffer))
7382 UnlockReleaseBuffer(buffer);
7385 * If the page is running low on free space, update the FSM as well.
7386 * Arbitrarily, our definition of "low" is less than 20%. We can't do much
7387 * better than that without knowing the fill-factor for the table.
7389 * XXX: Don't do this if the page was restored from full page image. We
7390 * don't bother to update the FSM in that case, it doesn't need to be
7391 * totally accurate anyway.
7393 if (action == BLK_NEEDS_REDO && freespace < BLCKSZ / 5)
7394 XLogRecordPageWithFreeSpace(target_node, blkno, freespace);
7398 * Handles MULTI_INSERT record type.
7401 heap_xlog_multi_insert(XLogReaderState *record)
7403 XLogRecPtr lsn = record->EndRecPtr;
7404 xl_heap_multi_insert *xlrec;
7411 HeapTupleHeaderData hdr;
7412 char data[MaxHeapTupleSize];
7414 HeapTupleHeader htup;
7418 bool isinit = (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE) != 0;
7419 XLogRedoAction action;
7422 * Insertion doesn't overwrite MVCC data, so no conflict processing is
7425 xlrec = (xl_heap_multi_insert *) XLogRecGetData(record);
7427 XLogRecGetBlockTag(record, 0, &rnode, NULL, &blkno);
7430 * The visibility map may need to be fixed even if the heap page is
7431 * already up-to-date.
7433 if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7435 Relation reln = CreateFakeRelcacheEntry(rnode);
7436 Buffer vmbuffer = InvalidBuffer;
7438 visibilitymap_pin(reln, blkno, &vmbuffer);
7439 visibilitymap_clear(reln, blkno, vmbuffer);
7440 ReleaseBuffer(vmbuffer);
7441 FreeFakeRelcacheEntry(reln);
7446 buffer = XLogInitBufferForRedo(record, 0);
7447 page = BufferGetPage(buffer);
7448 PageInit(page, BufferGetPageSize(buffer), 0);
7449 action = BLK_NEEDS_REDO;
7452 action = XLogReadBufferForRedo(record, 0, &buffer);
7453 if (action == BLK_NEEDS_REDO)
7459 /* Tuples are stored as block data */
7460 tupdata = XLogRecGetBlockData(record, 0, &len);
7461 endptr = tupdata + len;
7463 page = (Page) BufferGetPage(buffer);
7465 for (i = 0; i < xlrec->ntuples; i++)
7467 OffsetNumber offnum;
7468 xl_multi_insert_tuple *xlhdr;
7471 * If we're reinitializing the page, the tuples are stored in
7472 * order from FirstOffsetNumber. Otherwise there's an array of
7473 * offsets in the WAL record, and the tuples come after that.
7476 offnum = FirstOffsetNumber + i;
7478 offnum = xlrec->offsets[i];
7479 if (PageGetMaxOffsetNumber(page) + 1 < offnum)
7480 elog(PANIC, "heap_multi_insert_redo: invalid max offset number");
7482 xlhdr = (xl_multi_insert_tuple *) SHORTALIGN(tupdata);
7483 tupdata = ((char *) xlhdr) + SizeOfMultiInsertTuple;
7485 newlen = xlhdr->datalen;
7486 Assert(newlen <= MaxHeapTupleSize);
7488 MemSet((char *) htup, 0, sizeof(HeapTupleHeaderData));
7489 /* PG73FORMAT: get bitmap [+ padding] [+ oid] + data */
7490 memcpy((char *) htup + offsetof(HeapTupleHeaderData, t_bits),
7495 newlen += offsetof(HeapTupleHeaderData, t_bits);
7496 htup->t_infomask2 = xlhdr->t_infomask2;
7497 htup->t_infomask = xlhdr->t_infomask;
7498 htup->t_hoff = xlhdr->t_hoff;
7499 HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
7500 HeapTupleHeaderSetCmin(htup, FirstCommandId);
7501 ItemPointerSetBlockNumber(&htup->t_ctid, blkno);
7502 ItemPointerSetOffsetNumber(&htup->t_ctid, offnum);
7504 offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
7505 if (offnum == InvalidOffsetNumber)
7506 elog(PANIC, "heap_multi_insert_redo: failed to add tuple");
7508 if (tupdata != endptr)
7509 elog(PANIC, "heap_multi_insert_redo: total tuple length mismatch");
7511 freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
7513 PageSetLSN(page, lsn);
7515 if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7516 PageClearAllVisible(page);
7518 MarkBufferDirty(buffer);
7520 if (BufferIsValid(buffer))
7521 UnlockReleaseBuffer(buffer);
7524 * If the page is running low on free space, update the FSM as well.
7525 * Arbitrarily, our definition of "low" is less than 20%. We can't do much
7526 * better than that without knowing the fill-factor for the table.
7528 * XXX: Don't do this if the page was restored from full page image. We
7529 * don't bother to update the FSM in that case, it doesn't need to be
7530 * totally accurate anyway.
7532 if (action == BLK_NEEDS_REDO && freespace < BLCKSZ / 5)
7533 XLogRecordPageWithFreeSpace(rnode, blkno, freespace);
7537 * Handles UPDATE and HOT_UPDATE
7540 heap_xlog_update(XLogReaderState *record, bool hot_update)
7542 XLogRecPtr lsn = record->EndRecPtr;
7543 xl_heap_update *xlrec = (xl_heap_update *) XLogRecGetData(record);
7547 ItemPointerData newtid;
7551 OffsetNumber offnum;
7553 HeapTupleData oldtup;
7554 HeapTupleHeader htup;
7555 uint16 prefixlen = 0,
7560 HeapTupleHeaderData hdr;
7561 char data[MaxHeapTupleSize];
7563 xl_heap_header xlhdr;
7566 XLogRedoAction oldaction;
7567 XLogRedoAction newaction;
7569 /* initialize to keep the compiler quiet */
7570 oldtup.t_data = NULL;
7573 XLogRecGetBlockTag(record, 0, &rnode, NULL, &newblk);
7574 if (XLogRecGetBlockTag(record, 1, NULL, NULL, &oldblk))
7576 /* HOT updates are never done across pages */
7577 Assert(!hot_update);
7582 ItemPointerSet(&newtid, newblk, xlrec->new_offnum);
7585 * The visibility map may need to be fixed even if the heap page is
7586 * already up-to-date.
7588 if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7590 Relation reln = CreateFakeRelcacheEntry(rnode);
7591 Buffer vmbuffer = InvalidBuffer;
7593 visibilitymap_pin(reln, oldblk, &vmbuffer);
7594 visibilitymap_clear(reln, oldblk, vmbuffer);
7595 ReleaseBuffer(vmbuffer);
7596 FreeFakeRelcacheEntry(reln);
7600 * In normal operation, it is important to lock the two pages in
7601 * page-number order, to avoid possible deadlocks against other update
7602 * operations going the other way. However, during WAL replay there can
7603 * be no other update happening, so we don't need to worry about that. But
7604 * we *do* need to worry that we don't expose an inconsistent state to Hot
7605 * Standby queries --- so the original page can't be unlocked before we've
7606 * added the new tuple to the new page.
7609 /* Deal with old tuple version */
7610 oldaction = XLogReadBufferForRedo(record, (oldblk == newblk) ? 0 : 1,
7612 if (oldaction == BLK_NEEDS_REDO)
7614 page = BufferGetPage(obuffer);
7615 offnum = xlrec->old_offnum;
7616 if (PageGetMaxOffsetNumber(page) >= offnum)
7617 lp = PageGetItemId(page, offnum);
7619 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
7620 elog(PANIC, "heap_update_redo: invalid lp");
7622 htup = (HeapTupleHeader) PageGetItem(page, lp);
7624 oldtup.t_data = htup;
7625 oldtup.t_len = ItemIdGetLength(lp);
7627 htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
7628 htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7630 HeapTupleHeaderSetHotUpdated(htup);
7632 HeapTupleHeaderClearHotUpdated(htup);
7633 fix_infomask_from_infobits(xlrec->old_infobits_set, &htup->t_infomask,
7634 &htup->t_infomask2);
7635 HeapTupleHeaderSetXmax(htup, xlrec->old_xmax);
7636 HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
7637 /* Set forward chain link in t_ctid */
7638 htup->t_ctid = newtid;
7640 /* Mark the page as a candidate for pruning */
7641 PageSetPrunable(page, XLogRecGetXid(record));
7643 if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7644 PageClearAllVisible(page);
7646 PageSetLSN(page, lsn);
7647 MarkBufferDirty(obuffer);
7651 * Read the page the new tuple goes into, if different from old.
7653 if (oldblk == newblk)
7656 newaction = oldaction;
7658 else if (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE)
7660 nbuffer = XLogInitBufferForRedo(record, 0);
7661 page = (Page) BufferGetPage(nbuffer);
7662 PageInit(page, BufferGetPageSize(nbuffer), 0);
7663 newaction = BLK_NEEDS_REDO;
7666 newaction = XLogReadBufferForRedo(record, 0, &nbuffer);
7669 * The visibility map may need to be fixed even if the heap page is
7670 * already up-to-date.
7672 if (xlrec->flags & XLOG_HEAP_NEW_ALL_VISIBLE_CLEARED)
7674 Relation reln = CreateFakeRelcacheEntry(rnode);
7675 Buffer vmbuffer = InvalidBuffer;
7677 visibilitymap_pin(reln, newblk, &vmbuffer);
7678 visibilitymap_clear(reln, newblk, vmbuffer);
7679 ReleaseBuffer(vmbuffer);
7680 FreeFakeRelcacheEntry(reln);
7683 /* Deal with new tuple */
7684 if (newaction == BLK_NEEDS_REDO)
7691 recdata = XLogRecGetBlockData(record, 0, &datalen);
7692 recdata_end = recdata + datalen;
7694 page = BufferGetPage(nbuffer);
7696 offnum = xlrec->new_offnum;
7697 if (PageGetMaxOffsetNumber(page) + 1 < offnum)
7698 elog(PANIC, "heap_update_redo: invalid max offset number");
7700 if (xlrec->flags & XLOG_HEAP_PREFIX_FROM_OLD)
7702 Assert(newblk == oldblk);
7703 memcpy(&prefixlen, recdata, sizeof(uint16));
7704 recdata += sizeof(uint16);
7706 if (xlrec->flags & XLOG_HEAP_SUFFIX_FROM_OLD)
7708 Assert(newblk == oldblk);
7709 memcpy(&suffixlen, recdata, sizeof(uint16));
7710 recdata += sizeof(uint16);
7713 memcpy((char *) &xlhdr, recdata, SizeOfHeapHeader);
7714 recdata += SizeOfHeapHeader;
7716 tuplen = recdata_end - recdata;
7717 Assert(tuplen <= MaxHeapTupleSize);
7720 MemSet((char *) htup, 0, sizeof(HeapTupleHeaderData));
7723 * Reconstruct the new tuple using the prefix and/or suffix from the
7724 * old tuple, and the data stored in the WAL record.
7726 newp = (char *) htup + offsetof(HeapTupleHeaderData, t_bits);
7731 /* copy bitmap [+ padding] [+ oid] from WAL record */
7732 len = xlhdr.t_hoff - offsetof(HeapTupleHeaderData, t_bits);
7733 memcpy(newp, recdata, len);
7737 /* copy prefix from old tuple */
7738 memcpy(newp, (char *) oldtup.t_data + oldtup.t_data->t_hoff, prefixlen);
7741 /* copy new tuple data from WAL record */
7742 len = tuplen - (xlhdr.t_hoff - offsetof(HeapTupleHeaderData, t_bits));
7743 memcpy(newp, recdata, len);
7750 * copy bitmap [+ padding] [+ oid] + data from record, all in one
7753 memcpy(newp, recdata, tuplen);
7757 Assert(recdata == recdata_end);
7759 /* copy suffix from old tuple */
7761 memcpy(newp, (char *) oldtup.t_data + oldtup.t_len - suffixlen, suffixlen);
7763 newlen = offsetof(HeapTupleHeaderData, t_bits) + tuplen + prefixlen + suffixlen;
7764 htup->t_infomask2 = xlhdr.t_infomask2;
7765 htup->t_infomask = xlhdr.t_infomask;
7766 htup->t_hoff = xlhdr.t_hoff;
7768 HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
7769 HeapTupleHeaderSetCmin(htup, FirstCommandId);
7770 HeapTupleHeaderSetXmax(htup, xlrec->new_xmax);
7771 /* Make sure there is no forward chain link in t_ctid */
7772 htup->t_ctid = newtid;
7774 offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
7775 if (offnum == InvalidOffsetNumber)
7776 elog(PANIC, "heap_update_redo: failed to add tuple");
7778 if (xlrec->flags & XLOG_HEAP_NEW_ALL_VISIBLE_CLEARED)
7779 PageClearAllVisible(page);
7781 freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
7783 PageSetLSN(page, lsn);
7784 MarkBufferDirty(nbuffer);
7787 if (BufferIsValid(nbuffer) && nbuffer != obuffer)
7788 UnlockReleaseBuffer(nbuffer);
7789 if (BufferIsValid(obuffer))
7790 UnlockReleaseBuffer(obuffer);
7793 * If the new page is running low on free space, update the FSM as well.
7794 * Arbitrarily, our definition of "low" is less than 20%. We can't do much
7795 * better than that without knowing the fill-factor for the table.
7797 * However, don't update the FSM on HOT updates, because after crash
7798 * recovery, either the old or the new tuple will certainly be dead and
7799 * prunable. After pruning, the page will have roughly as much free space
7800 * as it did before the update, assuming the new tuple is about the same
7801 * size as the old one.
7803 * XXX: Don't do this if the page was restored from full page image. We
7804 * don't bother to update the FSM in that case, it doesn't need to be
7805 * totally accurate anyway.
7807 if (newaction == BLK_NEEDS_REDO && !hot_update && freespace < BLCKSZ / 5)
7808 XLogRecordPageWithFreeSpace(rnode, newblk, freespace);
7812 heap_xlog_lock(XLogReaderState *record)
7814 XLogRecPtr lsn = record->EndRecPtr;
7815 xl_heap_lock *xlrec = (xl_heap_lock *) XLogRecGetData(record);
7818 OffsetNumber offnum;
7820 HeapTupleHeader htup;
7822 if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
7824 page = (Page) BufferGetPage(buffer);
7826 offnum = xlrec->offnum;
7827 if (PageGetMaxOffsetNumber(page) >= offnum)
7828 lp = PageGetItemId(page, offnum);
7830 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
7831 elog(PANIC, "heap_lock_redo: invalid lp");
7833 htup = (HeapTupleHeader) PageGetItem(page, lp);
7835 fix_infomask_from_infobits(xlrec->infobits_set, &htup->t_infomask,
7836 &htup->t_infomask2);
7839 * Clear relevant update flags, but only if the modified infomask says
7840 * there's no update.
7842 if (HEAP_XMAX_IS_LOCKED_ONLY(htup->t_infomask))
7844 HeapTupleHeaderClearHotUpdated(htup);
7845 /* Make sure there is no forward chain link in t_ctid */
7846 ItemPointerSet(&htup->t_ctid,
7847 BufferGetBlockNumber(buffer),
7850 HeapTupleHeaderSetXmax(htup, xlrec->locking_xid);
7851 HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
7852 PageSetLSN(page, lsn);
7853 MarkBufferDirty(buffer);
7855 if (BufferIsValid(buffer))
7856 UnlockReleaseBuffer(buffer);
7860 heap_xlog_lock_updated(XLogReaderState *record)
7862 XLogRecPtr lsn = record->EndRecPtr;
7863 xl_heap_lock_updated *xlrec;
7866 OffsetNumber offnum;
7868 HeapTupleHeader htup;
7870 xlrec = (xl_heap_lock_updated *) XLogRecGetData(record);
7872 if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
7874 page = BufferGetPage(buffer);
7876 offnum = xlrec->offnum;
7877 if (PageGetMaxOffsetNumber(page) >= offnum)
7878 lp = PageGetItemId(page, offnum);
7880 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
7881 elog(PANIC, "heap_xlog_lock_updated: invalid lp");
7883 htup = (HeapTupleHeader) PageGetItem(page, lp);
7885 fix_infomask_from_infobits(xlrec->infobits_set, &htup->t_infomask,
7886 &htup->t_infomask2);
7887 HeapTupleHeaderSetXmax(htup, xlrec->xmax);
7889 PageSetLSN(page, lsn);
7890 MarkBufferDirty(buffer);
7892 if (BufferIsValid(buffer))
7893 UnlockReleaseBuffer(buffer);
7897 heap_xlog_inplace(XLogReaderState *record)
7899 XLogRecPtr lsn = record->EndRecPtr;
7900 xl_heap_inplace *xlrec = (xl_heap_inplace *) XLogRecGetData(record);
7903 OffsetNumber offnum;
7905 HeapTupleHeader htup;
7909 if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
7911 char *newtup = XLogRecGetBlockData(record, 0, &newlen);
7913 page = BufferGetPage(buffer);
7915 offnum = xlrec->offnum;
7916 if (PageGetMaxOffsetNumber(page) >= offnum)
7917 lp = PageGetItemId(page, offnum);
7919 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
7920 elog(PANIC, "heap_inplace_redo: invalid lp");
7922 htup = (HeapTupleHeader) PageGetItem(page, lp);
7924 oldlen = ItemIdGetLength(lp) - htup->t_hoff;
7925 if (oldlen != newlen)
7926 elog(PANIC, "heap_inplace_redo: wrong tuple length");
7928 memcpy((char *) htup + htup->t_hoff, newtup, newlen);
7930 PageSetLSN(page, lsn);
7931 MarkBufferDirty(buffer);
7933 if (BufferIsValid(buffer))
7934 UnlockReleaseBuffer(buffer);
7938 heap_redo(XLogReaderState *record)
7940 uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
7943 * These operations don't overwrite MVCC data so no conflict processing is
7944 * required. The ones in heap2 rmgr do.
7947 switch (info & XLOG_HEAP_OPMASK)
7949 case XLOG_HEAP_INSERT:
7950 heap_xlog_insert(record);
7952 case XLOG_HEAP_DELETE:
7953 heap_xlog_delete(record);
7955 case XLOG_HEAP_UPDATE:
7956 heap_xlog_update(record, false);
7958 case XLOG_HEAP_HOT_UPDATE:
7959 heap_xlog_update(record, true);
7961 case XLOG_HEAP_LOCK:
7962 heap_xlog_lock(record);
7964 case XLOG_HEAP_INPLACE:
7965 heap_xlog_inplace(record);
7968 elog(PANIC, "heap_redo: unknown op code %u", info);
7973 heap2_redo(XLogReaderState *record)
7975 uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
7977 switch (info & XLOG_HEAP_OPMASK)
7979 case XLOG_HEAP2_CLEAN:
7980 heap_xlog_clean(record);
7982 case XLOG_HEAP2_FREEZE_PAGE:
7983 heap_xlog_freeze_page(record);
7985 case XLOG_HEAP2_CLEANUP_INFO:
7986 heap_xlog_cleanup_info(record);
7988 case XLOG_HEAP2_VISIBLE:
7989 heap_xlog_visible(record);
7991 case XLOG_HEAP2_MULTI_INSERT:
7992 heap_xlog_multi_insert(record);
7994 case XLOG_HEAP2_LOCK_UPDATED:
7995 heap_xlog_lock_updated(record);
7997 case XLOG_HEAP2_NEW_CID:
8000 * Nothing to do on a real replay, only used during logical
8004 case XLOG_HEAP2_REWRITE:
8005 heap_xlog_logical_rewrite(record);
8008 elog(PANIC, "heap2_redo: unknown op code %u", info);
8013 * heap_sync - sync a heap, for use when no WAL has been written
8015 * This forces the heap contents (including TOAST heap if any) down to disk.
8016 * If we skipped using WAL, and WAL is otherwise needed, we must force the
8017 * relation down to disk before it's safe to commit the transaction. This
8018 * requires writing out any dirty buffers and then doing a forced fsync.
8020 * Indexes are not touched. (Currently, index operations associated with
8021 * the commands that use this are WAL-logged and so do not need fsync.
8022 * That behavior might change someday, but in any case it's likely that
8023 * any fsync decisions required would be per-index and hence not appropriate
8027 heap_sync(Relation rel)
8029 /* non-WAL-logged tables never need fsync */
8030 if (!RelationNeedsWAL(rel))
8034 FlushRelationBuffers(rel);
8035 /* FlushRelationBuffers will have opened rd_smgr */
8036 smgrimmedsync(rel->rd_smgr, MAIN_FORKNUM);
8038 /* FSM is not critical, don't bother syncing it */
8040 /* toast heap, if any */
8041 if (OidIsValid(rel->rd_rel->reltoastrelid))
8045 toastrel = heap_open(rel->rd_rel->reltoastrelid, AccessShareLock);
8046 FlushRelationBuffers(toastrel);
8047 smgrimmedsync(toastrel->rd_smgr, MAIN_FORKNUM);
8048 heap_close(toastrel, AccessShareLock);