1 /*-------------------------------------------------------------------------
4 * heap access method code
6 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/access/heap/heapam.c,v 1.137 2002/05/24 19:52:43 tgl Exp $
15 * relation_open - open any relation by relation OID
16 * relation_openrv - open any relation specified by a RangeVar
17 * relation_openr - open a system relation by name
18 * relation_close - close any relation
19 * heap_open - open a heap relation by relation OID
20 * heap_openrv - open a heap relation specified by a RangeVar
21 * heap_openr - open a system heap relation by name
22 * heap_close - (now just a macro for relation_close)
23 * heap_beginscan - begin relation scan
24 * heap_rescan - restart a relation scan
25 * heap_endscan - end relation scan
26 * heap_getnext - retrieve next tuple in scan
27 * heap_fetch - retrieve tuple with tid
28 * heap_insert - insert tuple into a relation
29 * heap_delete - delete a tuple from a relation
30 * heap_update - replace a tuple in a relation with another tuple
31 * heap_markpos - mark scan position
32 * heap_restrpos - restore position to marked location
35 * This file contains the heap_ routines which implement
36 * the POSTGRES heap access method used for all POSTGRES
39 *-------------------------------------------------------------------------
43 #include "access/heapam.h"
44 #include "access/hio.h"
45 #include "access/tuptoaster.h"
46 #include "access/valid.h"
47 #include "access/xlogutils.h"
48 #include "catalog/catalog.h"
49 #include "catalog/namespace.h"
50 #include "miscadmin.h"
51 #include "utils/inval.h"
52 #include "utils/relcache.h"
56 /* comments are in heap_update */
57 static xl_heaptid _locked_tuple_;
58 static void _heap_unlock_tuple(void *data);
59 static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
60 ItemPointerData from, Buffer newbuf, HeapTuple newtup, bool move);
63 /* ----------------------------------------------------------------
64 * heap support routines
65 * ----------------------------------------------------------------
69 * initscan - scan code common to heap_beginscan and heap_rescan
73 initscan(HeapScanDesc scan, ScanKey key)
76 * Make sure we have up-to-date idea of number of blocks in relation.
77 * It is sufficient to do this once at scan start, since any tuples
78 * added while the scan is in progress will be invisible to my
79 * transaction anyway...
81 scan->rs_rd->rd_nblocks = RelationGetNumberOfBlocks(scan->rs_rd);
83 scan->rs_ctup.t_datamcxt = NULL;
84 scan->rs_ctup.t_data = NULL;
85 scan->rs_cbuf = InvalidBuffer;
87 /* we don't have a marked position... */
88 ItemPointerSetInvalid(&(scan->rs_mctid));
91 * copy the scan key, if appropriate
94 memcpy(scan->rs_key, key, scan->rs_nkeys * sizeof(ScanKeyData));
98 * heapgettup - fetch next heap tuple
100 * routine used by heap_getnext() which does most of the
101 * real work in scanning tuples.
103 * The passed-in *buffer must be either InvalidBuffer or the pinned
104 * current page of the scan. If we have to move to another page,
105 * we will unpin this buffer (if valid). On return, *buffer is either
106 * InvalidBuffer or the ID of a pinned buffer.
110 heapgettup(Relation relation,
123 OffsetNumber lineoff;
128 * increment access statistics
130 IncrHeapAccessStat(local_heapgettup);
131 IncrHeapAccessStat(global_heapgettup);
133 tid = (tuple->t_data == NULL) ? (ItemPointer) NULL : &(tuple->t_self);
138 * check validity of arguments, here and for other functions too Note: no
139 * locking manipulations needed--this is a local function
142 if (ItemPointerIsValid(tid))
144 elog(LOG, "heapgettup(%s, tid=0x%x[%d,%d], dir=%d, ...)",
145 RelationGetRelationName(relation), tid, tid->ip_blkid,
150 elog(LOG, "heapgettup(%s, tid=0x%x, dir=%d, ...)",
151 RelationGetRelationName(relation), tid, dir);
153 elog(LOG, "heapgettup(..., b=0x%x, nkeys=%d, key=0x%x", buffer, nkeys, key);
155 elog(LOG, "heapgettup: relation(%c)=`%s', %p",
156 relation->rd_rel->relkind, RelationGetRelationName(relation),
158 #endif /* !defined(HEAPLOGALL) */
160 if (!ItemPointerIsValid(tid))
162 Assert(!PointerIsValid(tid));
166 tuple->t_tableOid = relation->rd_id;
169 * return null immediately if relation is empty
171 if ((pages = relation->rd_nblocks) == 0)
173 if (BufferIsValid(*buffer))
174 ReleaseBuffer(*buffer);
175 *buffer = InvalidBuffer;
176 tuple->t_datamcxt = NULL;
177 tuple->t_data = NULL;
182 * calculate next starting lineoff, given scan direction
187 * ``no movement'' scan direction: refetch same tuple
191 if (BufferIsValid(*buffer))
192 ReleaseBuffer(*buffer);
193 *buffer = InvalidBuffer;
194 tuple->t_datamcxt = NULL;
195 tuple->t_data = NULL;
199 *buffer = ReleaseAndReadBuffer(*buffer,
201 ItemPointerGetBlockNumber(tid));
202 if (!BufferIsValid(*buffer))
203 elog(ERROR, "heapgettup: failed ReadBuffer");
205 LockBuffer(*buffer, BUFFER_LOCK_SHARE);
207 dp = (Page) BufferGetPage(*buffer);
208 lineoff = ItemPointerGetOffsetNumber(tid);
209 lpp = PageGetItemId(dp, lineoff);
211 tuple->t_datamcxt = NULL;
212 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
213 tuple->t_len = ItemIdGetLength(lpp);
214 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
221 * reverse scan direction
225 page = pages - 1; /* final page */
229 page = ItemPointerGetBlockNumber(tid); /* current page */
232 Assert(page < pages);
234 *buffer = ReleaseAndReadBuffer(*buffer,
237 if (!BufferIsValid(*buffer))
238 elog(ERROR, "heapgettup: failed ReadBuffer");
240 LockBuffer(*buffer, BUFFER_LOCK_SHARE);
242 dp = (Page) BufferGetPage(*buffer);
243 lines = PageGetMaxOffsetNumber(dp);
246 lineoff = lines; /* final offnum */
250 lineoff = /* previous offnum */
251 OffsetNumberPrev(ItemPointerGetOffsetNumber(tid));
253 /* page and lineoff now reference the physically previous tid */
258 * forward scan direction
262 page = 0; /* first page */
263 lineoff = FirstOffsetNumber; /* first offnum */
267 page = ItemPointerGetBlockNumber(tid); /* current page */
268 lineoff = /* next offnum */
269 OffsetNumberNext(ItemPointerGetOffsetNumber(tid));
272 Assert(page < pages);
274 *buffer = ReleaseAndReadBuffer(*buffer,
277 if (!BufferIsValid(*buffer))
278 elog(ERROR, "heapgettup: failed ReadBuffer");
280 LockBuffer(*buffer, BUFFER_LOCK_SHARE);
282 dp = (Page) BufferGetPage(*buffer);
283 lines = PageGetMaxOffsetNumber(dp);
284 /* page and lineoff now reference the physically next tid */
287 /* 'dir' is now non-zero */
290 * calculate line pointer and number of remaining items to check on
293 lpp = PageGetItemId(dp, lineoff);
295 linesleft = lineoff - 1;
297 linesleft = lines - lineoff;
300 * advance the scan until we find a qualifying tuple or run out of
305 while (linesleft >= 0)
307 if (ItemIdIsUsed(lpp))
311 tuple->t_datamcxt = NULL;
312 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
313 tuple->t_len = ItemIdGetLength(lpp);
314 ItemPointerSet(&(tuple->t_self), page, lineoff);
317 * if current tuple qualifies, return it.
319 HeapTupleSatisfies(tuple, relation, *buffer, (PageHeader) dp,
320 snapshot, nkeys, key, valid);
323 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
329 * otherwise move to the next item on the page
334 --lpp; /* move back in this page's ItemId array */
339 ++lpp; /* move forward in this page's ItemId
346 * if we get here, it means we've exhausted the items on this page
347 * and it's time to move to the next.
349 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
352 * return NULL if we've exhausted all the pages
354 if ((dir < 0) ? (page == 0) : (page + 1 >= pages))
356 if (BufferIsValid(*buffer))
357 ReleaseBuffer(*buffer);
358 *buffer = InvalidBuffer;
359 tuple->t_datamcxt = NULL;
360 tuple->t_data = NULL;
364 page = (dir < 0) ? (page - 1) : (page + 1);
366 Assert(page < pages);
368 *buffer = ReleaseAndReadBuffer(*buffer,
371 if (!BufferIsValid(*buffer))
372 elog(ERROR, "heapgettup: failed ReadBuffer");
374 LockBuffer(*buffer, BUFFER_LOCK_SHARE);
375 dp = (Page) BufferGetPage(*buffer);
376 lines = PageGetMaxOffsetNumber((Page) dp);
377 linesleft = lines - 1;
381 lpp = PageGetItemId(dp, lines);
385 lineoff = FirstOffsetNumber;
386 lpp = PageGetItemId(dp, FirstOffsetNumber);
392 #if defined(DISABLE_COMPLEX_MACRO)
394 * This is formatted so oddly so that the correspondence to the macro
395 * definition in access/heapam.h is maintained.
398 fastgetattr(HeapTuple tup, int attnum, TupleDesc tupleDesc,
404 ((isnull) ? (*(isnull) = false) : (dummyret) NULL),
405 HeapTupleNoNulls(tup) ?
407 (tupleDesc)->attrs[(attnum) - 1]->attcacheoff >= 0 ?
409 fetchatt((tupleDesc)->attrs[(attnum) - 1],
410 (char *) (tup)->t_data + (tup)->t_data->t_hoff +
411 (tupleDesc)->attrs[(attnum) - 1]->attcacheoff)
414 nocachegetattr((tup), (attnum), (tupleDesc), (isnull))
418 att_isnull((attnum) - 1, (tup)->t_data->t_bits) ?
420 ((isnull) ? (*(isnull) = true) : (dummyret) NULL),
425 nocachegetattr((tup), (attnum), (tupleDesc), (isnull))
435 #endif /* defined(DISABLE_COMPLEX_MACRO) */
438 /* ----------------------------------------------------------------
439 * heap access method interface
440 * ----------------------------------------------------------------
444 * relation_open - open any relation by relation OID
446 * If lockmode is not "NoLock", the specified kind of lock is
447 * obtained on the relation. (Generally, NoLock should only be
448 * used if the caller knows it has some appropriate lock on the
451 * An error is raised if the relation does not exist.
453 * NB: a "relation" is anything with a pg_class entry. The caller is
454 * expected to check whether the relkind is something it can handle.
458 relation_open(Oid relationId, LOCKMODE lockmode)
462 Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
465 * increment access statistics
467 IncrHeapAccessStat(local_open);
468 IncrHeapAccessStat(global_open);
470 /* The relcache does all the real work... */
471 r = RelationIdGetRelation(relationId);
473 if (!RelationIsValid(r))
474 elog(ERROR, "Relation %u does not exist", relationId);
476 if (lockmode != NoLock)
477 LockRelation(r, lockmode);
483 * relation_openrv - open any relation specified by a RangeVar
485 * As above, but the relation is specified by a RangeVar.
489 relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
494 * In bootstrap mode, don't do any namespace processing.
496 if (IsBootstrapProcessingMode())
498 Assert(relation->schemaname == NULL);
499 return relation_openr(relation->relname, lockmode);
503 * Check for shared-cache-inval messages before trying to open the
504 * relation. This is needed to cover the case where the name
505 * identifies a rel that has been dropped and recreated since the
506 * start of our transaction: if we don't flush the old syscache entry
507 * then we'll latch onto that entry and suffer an error when we do
508 * LockRelation. Note that relation_open does not need to do this,
509 * since a relation's OID never changes.
511 * We skip this if asked for NoLock, on the assumption that the caller
512 * has already ensured some appropriate lock is held.
514 if (lockmode != NoLock)
515 AcceptInvalidationMessages();
517 /* Look up the appropriate relation using namespace search */
518 relOid = RangeVarGetRelid(relation, false);
520 /* Let relation_open do the rest */
521 return relation_open(relOid, lockmode);
525 * relation_openr - open a system relation specified by name.
527 * As above, but the relation is specified by an unqualified name;
528 * it is assumed to live in the system catalog namespace.
532 relation_openr(const char *sysRelationName, LOCKMODE lockmode)
536 Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
539 * increment access statistics
541 IncrHeapAccessStat(local_openr);
542 IncrHeapAccessStat(global_openr);
545 * We assume we should not need to worry about the rel's OID changing,
546 * hence no need for AcceptInvalidationMessages here.
549 /* The relcache does all the real work... */
550 r = RelationSysNameGetRelation(sysRelationName);
552 if (!RelationIsValid(r))
553 elog(ERROR, "Relation \"%s\" does not exist", sysRelationName);
555 if (lockmode != NoLock)
556 LockRelation(r, lockmode);
562 * relation_close - close any relation
564 * If lockmode is not "NoLock", we first release the specified lock.
566 * Note that it is often sensible to hold a lock beyond relation_close;
567 * in that case, the lock is released automatically at xact end.
571 relation_close(Relation relation, LOCKMODE lockmode)
573 Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
576 * increment access statistics
578 IncrHeapAccessStat(local_close);
579 IncrHeapAccessStat(global_close);
581 if (lockmode != NoLock)
582 UnlockRelation(relation, lockmode);
584 /* The relcache does the real work... */
585 RelationClose(relation);
590 * heap_open - open a heap relation by relation OID
592 * This is essentially relation_open plus check that the relation
593 * is not an index or special relation. (The caller should also check
594 * that it's not a view before assuming it has storage.)
598 heap_open(Oid relationId, LOCKMODE lockmode)
602 r = relation_open(relationId, lockmode);
604 if (r->rd_rel->relkind == RELKIND_INDEX)
605 elog(ERROR, "%s is an index relation",
606 RelationGetRelationName(r));
607 else if (r->rd_rel->relkind == RELKIND_SPECIAL)
608 elog(ERROR, "%s is a special relation",
609 RelationGetRelationName(r));
611 pgstat_initstats(&r->pgstat_info, r);
617 * heap_openrv - open a heap relation specified
620 * As above, but relation is specified by a RangeVar.
624 heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
628 r = relation_openrv(relation, lockmode);
630 if (r->rd_rel->relkind == RELKIND_INDEX)
631 elog(ERROR, "%s is an index relation",
632 RelationGetRelationName(r));
633 else if (r->rd_rel->relkind == RELKIND_SPECIAL)
634 elog(ERROR, "%s is a special relation",
635 RelationGetRelationName(r));
637 pgstat_initstats(&r->pgstat_info, r);
643 * heap_openr - open a system heap relation specified by name.
645 * As above, but the relation is specified by an unqualified name;
646 * it is assumed to live in the system catalog namespace.
650 heap_openr(const char *sysRelationName, LOCKMODE lockmode)
654 r = relation_openr(sysRelationName, lockmode);
656 if (r->rd_rel->relkind == RELKIND_INDEX)
657 elog(ERROR, "%s is an index relation",
658 RelationGetRelationName(r));
659 else if (r->rd_rel->relkind == RELKIND_SPECIAL)
660 elog(ERROR, "%s is a special relation",
661 RelationGetRelationName(r));
663 pgstat_initstats(&r->pgstat_info, r);
670 * heap_beginscan - begin relation scan
674 heap_beginscan(Relation relation, Snapshot snapshot,
675 int nkeys, ScanKey key)
680 * increment access statistics
682 IncrHeapAccessStat(local_beginscan);
683 IncrHeapAccessStat(global_beginscan);
688 if (!RelationIsValid(relation))
689 elog(ERROR, "heap_beginscan: !RelationIsValid(relation)");
692 * increment relation ref count while scanning relation
694 * This is just to make really sure the relcache entry won't go away
695 * while the scan has a pointer to it. Caller should be holding the
696 * rel open anyway, so this is redundant in all normal scenarios...
698 RelationIncrementReferenceCount(relation);
700 /* XXX someday assert SelfTimeQual if relkind == RELKIND_UNCATALOGED */
701 if (relation->rd_rel->relkind == RELKIND_UNCATALOGED)
702 snapshot = SnapshotSelf;
705 * allocate and initialize scan descriptor
707 scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
709 scan->rs_rd = relation;
710 scan->rs_snapshot = snapshot;
711 scan->rs_nkeys = nkeys;
714 * we do this here instead of in initscan() because heap_rescan also
715 * calls initscan() and we don't want to allocate memory again
718 scan->rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
722 pgstat_initstats(&scan->rs_pgstat_info, relation);
730 * heap_rescan - restart a relation scan
734 heap_rescan(HeapScanDesc scan,
738 * increment access statistics
740 IncrHeapAccessStat(local_rescan);
741 IncrHeapAccessStat(global_rescan);
746 if (BufferIsValid(scan->rs_cbuf))
747 ReleaseBuffer(scan->rs_cbuf);
750 * reinitialize scan descriptor
754 pgstat_reset_heap_scan(&scan->rs_pgstat_info);
758 * heap_endscan - end relation scan
760 * See how to integrate with index scans.
761 * Check handling if reldesc caching.
765 heap_endscan(HeapScanDesc scan)
768 * increment access statistics
770 IncrHeapAccessStat(local_endscan);
771 IncrHeapAccessStat(global_endscan);
773 /* Note: no locking manipulations needed */
778 if (BufferIsValid(scan->rs_cbuf))
779 ReleaseBuffer(scan->rs_cbuf);
782 * decrement relation reference count and free scan descriptor storage
784 RelationDecrementReferenceCount(scan->rs_rd);
793 * heap_getnext - retrieve next tuple in scan
795 * Fix to work with index relations.
796 * We don't return the buffer anymore, but you can get it from the
797 * returned HeapTuple.
802 #define HEAPDEBUG_1 \
803 elog(LOG, "heap_getnext([%s,nkeys=%d],dir=%d) called", \
804 RelationGetRelationName(scan->rs_rd), scan->rs_nkeys, (int) direction)
806 #define HEAPDEBUG_2 \
807 elog(LOG, "heap_getnext returning EOS")
809 #define HEAPDEBUG_3 \
810 elog(LOG, "heap_getnext returning tuple")
815 #endif /* !defined(HEAPDEBUGALL) */
819 heap_getnext(HeapScanDesc scan, ScanDirection direction)
822 * increment access statistics
824 IncrHeapAccessStat(local_getnext);
825 IncrHeapAccessStat(global_getnext);
827 /* Note: no locking manipulations needed */
833 elog(ERROR, "heap_getnext: NULL relscan");
835 HEAPDEBUG_1; /* heap_getnext( info ) */
838 * Note: we depend here on the -1/0/1 encoding of ScanDirection.
840 heapgettup(scan->rs_rd,
848 if (scan->rs_ctup.t_data == NULL && !BufferIsValid(scan->rs_cbuf))
850 HEAPDEBUG_2; /* heap_getnext returning EOS */
854 pgstat_count_heap_scan(&scan->rs_pgstat_info);
857 * if we get here it means we have a new current scan tuple, so point
858 * to the proper return buffer and return the tuple.
861 HEAPDEBUG_3; /* heap_getnext returning tuple */
863 if (scan->rs_ctup.t_data != NULL)
864 pgstat_count_heap_getnext(&scan->rs_pgstat_info);
866 return ((scan->rs_ctup.t_data == NULL) ? NULL : &(scan->rs_ctup));
870 * heap_fetch - retrieve tuple with given tid
872 * On entry, tuple->t_self is the TID to fetch. We pin the buffer holding
873 * the tuple, fill in the remaining fields of *tuple, and check the tuple
874 * against the specified snapshot.
876 * If successful (tuple found and passes snapshot time qual), then *userbuf
877 * is set to the buffer holding the tuple and TRUE is returned. The caller
878 * must unpin the buffer when done with the tuple.
880 * If the tuple is not found, then tuple->t_data is set to NULL, *userbuf
881 * is set to InvalidBuffer, and FALSE is returned.
883 * If the tuple is found but fails the time qual check, then FALSE will be
884 * returned. When the caller specifies keep_buf = true, we retain the pin
885 * on the buffer and return it in *userbuf (so the caller can still access
886 * the tuple); when keep_buf = false, the pin is released and *userbuf is set
889 * It is somewhat inconsistent that we elog() on invalid block number but
890 * return false on invalid item number. This is historical. The only
891 * justification I can see is that the caller can relatively easily check the
892 * block number for validity, but cannot check the item number without reading
896 heap_fetch(Relation relation,
901 PgStat_Info *pgstat_info)
903 ItemPointer tid = &(tuple->t_self);
911 * increment access statistics
913 IncrHeapAccessStat(local_fetch);
914 IncrHeapAccessStat(global_fetch);
917 * get the buffer from the relation descriptor. Note that this does a
920 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
922 if (!BufferIsValid(buffer))
923 elog(ERROR, "heap_fetch: ReadBuffer(%s, %lu) failed",
924 RelationGetRelationName(relation),
925 (unsigned long) ItemPointerGetBlockNumber(tid));
928 * Need share lock on buffer to examine tuple commit status.
930 LockBuffer(buffer, BUFFER_LOCK_SHARE);
933 * get the item line pointer corresponding to the requested tid
935 dp = (PageHeader) BufferGetPage(buffer);
936 offnum = ItemPointerGetOffsetNumber(tid);
937 lp = PageGetItemId(dp, offnum);
940 * must check for deleted tuple (see for example analyze.c, which is
941 * careful to pass an offnum in range, but doesn't know if the offnum
942 * actually corresponds to an undeleted tuple).
944 if (!ItemIdIsUsed(lp))
946 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
947 ReleaseBuffer(buffer);
948 *userbuf = InvalidBuffer;
949 tuple->t_datamcxt = NULL;
950 tuple->t_data = NULL;
955 * fill in *tuple fields
957 tuple->t_datamcxt = NULL;
958 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
959 tuple->t_len = ItemIdGetLength(lp);
960 tuple->t_tableOid = relation->rd_id;
963 * check time qualification of tuple, then release lock
965 HeapTupleSatisfies(tuple, relation, buffer, dp,
966 snapshot, 0, (ScanKey) NULL, valid);
968 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
973 * All checks passed, so return the tuple as valid. Caller is now
974 * responsible for releasing the buffer.
979 * Count the successful fetch in *pgstat_info if given,
980 * otherwise in the relation's default statistics area.
982 if (pgstat_info != NULL)
983 pgstat_count_heap_fetch(pgstat_info);
985 pgstat_count_heap_fetch(&relation->pgstat_info);
990 /* Tuple failed time qual, but maybe caller wants to see it anyway. */
998 /* Okay to release pin on buffer. */
999 ReleaseBuffer(buffer);
1001 *userbuf = InvalidBuffer;
1007 * heap_get_latest_tid - get the latest tid of a specified tuple
1010 heap_get_latest_tid(Relation relation,
1017 OffsetNumber offnum;
1019 HeapTupleHeader t_data;
1020 ItemPointerData ctid;
1026 * get the buffer from the relation descriptor Note that this does a
1030 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1032 if (!BufferIsValid(buffer))
1033 elog(ERROR, "heap_get_latest_tid: %s relation: ReadBuffer(%lx) failed",
1034 RelationGetRelationName(relation), (long) tid);
1036 LockBuffer(buffer, BUFFER_LOCK_SHARE);
1039 * get the item line pointer corresponding to the requested tid
1041 dp = (PageHeader) BufferGetPage(buffer);
1042 offnum = ItemPointerGetOffsetNumber(tid);
1043 invalidBlock = true;
1046 lp = PageGetItemId(dp, offnum);
1047 if (ItemIdIsUsed(lp))
1048 invalidBlock = false;
1052 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1053 ReleaseBuffer(buffer);
1058 * more sanity checks
1061 tp.t_datamcxt = NULL;
1062 t_data = tp.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
1063 tp.t_len = ItemIdGetLength(lp);
1065 ctid = tp.t_data->t_ctid;
1068 * check time qualification of tid
1071 HeapTupleSatisfies(&tp, relation, buffer, dp,
1072 snapshot, 0, (ScanKey) NULL, valid);
1075 if ((t_data->t_infomask & HEAP_XMIN_COMMITTED) != 0 &&
1076 !ItemPointerEquals(tid, &ctid))
1079 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1080 ReleaseBuffer(buffer);
1086 heap_get_latest_tid(relation, snapshot, &ctid);
1094 * heap_insert - insert tuple into a heap
1096 * The new tuple is stamped with current transaction ID and the specified
1100 heap_insert(Relation relation, HeapTuple tup, CommandId cid)
1104 /* increment access statistics */
1105 IncrHeapAccessStat(local_insert);
1106 IncrHeapAccessStat(global_insert);
1108 if (relation->rd_rel->relhasoids)
1111 * If the object id of this tuple has already been assigned, trust
1112 * the caller. There are a couple of ways this can happen. At
1113 * initial db creation, the backend program sets oids for tuples.
1114 * When we define an index, we set the oid. Finally, in the
1115 * future, we may allow users to set their own object ids in order
1116 * to support a persistent object store (objects need to contain
1117 * pointers to one another).
1119 if (!OidIsValid(tup->t_data->t_oid))
1120 tup->t_data->t_oid = newoid();
1122 CheckMaxObjectId(tup->t_data->t_oid);
1125 TransactionIdStore(GetCurrentTransactionId(), &(tup->t_data->t_xmin));
1126 tup->t_data->t_cmin = cid;
1127 StoreInvalidTransactionId(&(tup->t_data->t_xmax));
1128 tup->t_data->t_cmax = FirstCommandId;
1129 tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
1130 tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
1131 tup->t_tableOid = relation->rd_id;
1133 #ifdef TUPLE_TOASTER_ACTIVE
1136 * If the new tuple is too big for storage or contains already toasted
1137 * attributes from some other relation, invoke the toaster.
1139 if (HeapTupleHasExtended(tup) ||
1140 (MAXALIGN(tup->t_len) > TOAST_TUPLE_THRESHOLD))
1141 heap_tuple_toast_attrs(relation, tup, NULL);
1144 /* Find buffer to insert this tuple into */
1145 buffer = RelationGetBufferForTuple(relation, tup->t_len, InvalidBuffer);
1147 /* NO ELOG(ERROR) from here till changes are logged */
1148 START_CRIT_SECTION();
1149 RelationPutHeapTuple(relation, buffer, tup);
1151 pgstat_count_heap_insert(&relation->pgstat_info);
1155 xl_heap_insert xlrec;
1156 xl_heap_header xlhdr;
1158 XLogRecData rdata[3];
1159 Page page = BufferGetPage(buffer);
1160 uint8 info = XLOG_HEAP_INSERT;
1162 xlrec.target.node = relation->rd_node;
1163 xlrec.target.tid = tup->t_self;
1164 rdata[0].buffer = InvalidBuffer;
1165 rdata[0].data = (char *) &xlrec;
1166 rdata[0].len = SizeOfHeapInsert;
1167 rdata[0].next = &(rdata[1]);
1169 xlhdr.t_oid = tup->t_data->t_oid;
1170 xlhdr.t_natts = tup->t_data->t_natts;
1171 xlhdr.t_hoff = tup->t_data->t_hoff;
1172 xlhdr.mask = tup->t_data->t_infomask;
1173 rdata[1].buffer = buffer;
1174 rdata[1].data = (char *) &xlhdr;
1175 rdata[1].len = SizeOfHeapHeader;
1176 rdata[1].next = &(rdata[2]);
1178 rdata[2].buffer = buffer;
1179 rdata[2].data = (char *) tup->t_data + offsetof(HeapTupleHeaderData, t_bits);
1180 rdata[2].len = tup->t_len - offsetof(HeapTupleHeaderData, t_bits);
1181 rdata[2].next = NULL;
1183 /* If this is the single and first tuple on page... */
1184 if (ItemPointerGetOffsetNumber(&(tup->t_self)) == FirstOffsetNumber &&
1185 PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
1187 info |= XLOG_HEAP_INIT_PAGE;
1188 rdata[1].buffer = rdata[2].buffer = InvalidBuffer;
1191 recptr = XLogInsert(RM_HEAP_ID, info, rdata);
1193 PageSetLSN(page, recptr);
1194 PageSetSUI(page, ThisStartUpID);
1198 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1199 WriteBuffer(buffer);
1202 * If tuple is cachable, mark it for invalidation from the caches in case
1203 * we abort. Note it is OK to do this after WriteBuffer releases the
1204 * buffer, because the "tup" data structure is all in local memory,
1205 * not in the shared buffer.
1207 CacheInvalidateHeapTuple(relation, tup);
1209 return tup->t_data->t_oid;
1213 * simple_heap_insert - insert a tuple
1215 * Currently, this routine differs from heap_insert only in supplying
1216 * a default command ID. But it should be used rather than using
1217 * heap_insert directly in most places where we are modifying system catalogs.
1220 simple_heap_insert(Relation relation, HeapTuple tup)
1222 return heap_insert(relation, tup, GetCurrentCommandId());
1226 * heap_delete - delete a tuple
1228 * NB: do not call this directly unless you are prepared to deal with
1229 * concurrent-update conditions. Use simple_heap_delete instead.
1232 heap_delete(Relation relation, ItemPointer tid,
1233 ItemPointer ctid, CommandId cid)
1241 /* increment access statistics */
1242 IncrHeapAccessStat(local_delete);
1243 IncrHeapAccessStat(global_delete);
1245 Assert(ItemPointerIsValid(tid));
1247 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1249 if (!BufferIsValid(buffer))
1250 elog(ERROR, "heap_delete: failed ReadBuffer");
1252 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
1254 dp = (PageHeader) BufferGetPage(buffer);
1255 lp = PageGetItemId(dp, ItemPointerGetOffsetNumber(tid));
1256 tp.t_datamcxt = NULL;
1257 tp.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
1258 tp.t_len = ItemIdGetLength(lp);
1260 tp.t_tableOid = relation->rd_id;
1263 result = HeapTupleSatisfiesUpdate(&tp, cid);
1265 if (result == HeapTupleInvisible)
1267 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1268 ReleaseBuffer(buffer);
1269 elog(ERROR, "heap_delete: (am)invalid tid");
1271 else if (result == HeapTupleBeingUpdated)
1273 TransactionId xwait = tp.t_data->t_xmax;
1275 /* sleep until concurrent transaction ends */
1276 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1277 XactLockTableWait(xwait);
1279 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
1280 if (TransactionIdDidAbort(xwait))
1284 * xwait is committed but if xwait had just marked the tuple for
1285 * update then some other xaction could update this tuple before
1286 * we got to this point.
1288 if (!TransactionIdEquals(tp.t_data->t_xmax, xwait))
1290 if (!(tp.t_data->t_infomask & HEAP_XMAX_COMMITTED))
1292 tp.t_data->t_infomask |= HEAP_XMAX_COMMITTED;
1293 SetBufferCommitInfoNeedsSave(buffer);
1295 /* if tuple was marked for update but not updated... */
1296 if (tp.t_data->t_infomask & HEAP_MARKED_FOR_UPDATE)
1297 result = HeapTupleMayBeUpdated;
1299 result = HeapTupleUpdated;
1301 if (result != HeapTupleMayBeUpdated)
1303 Assert(result == HeapTupleSelfUpdated || result == HeapTupleUpdated);
1304 *ctid = tp.t_data->t_ctid;
1305 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1306 ReleaseBuffer(buffer);
1310 START_CRIT_SECTION();
1311 /* store transaction information of xact deleting the tuple */
1312 TransactionIdStore(GetCurrentTransactionId(), &(tp.t_data->t_xmax));
1313 tp.t_data->t_cmax = cid;
1314 tp.t_data->t_infomask &= ~(HEAP_XMAX_COMMITTED |
1315 HEAP_XMAX_INVALID | HEAP_MARKED_FOR_UPDATE);
1318 xl_heap_delete xlrec;
1320 XLogRecData rdata[2];
1322 xlrec.target.node = relation->rd_node;
1323 xlrec.target.tid = tp.t_self;
1324 rdata[0].buffer = InvalidBuffer;
1325 rdata[0].data = (char *) &xlrec;
1326 rdata[0].len = SizeOfHeapDelete;
1327 rdata[0].next = &(rdata[1]);
1329 rdata[1].buffer = buffer;
1330 rdata[1].data = NULL;
1332 rdata[1].next = NULL;
1334 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE, rdata);
1336 PageSetLSN(dp, recptr);
1337 PageSetSUI(dp, ThisStartUpID);
1341 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1343 #ifdef TUPLE_TOASTER_ACTIVE
1346 * If the relation has toastable attributes, we need to delete no
1347 * longer needed items there too. We have to do this before
1348 * WriteBuffer because we need to look at the contents of the tuple,
1349 * but it's OK to release the context lock on the buffer first.
1351 if (HeapTupleHasExtended(&tp))
1352 heap_tuple_toast_attrs(relation, NULL, &(tp));
1355 pgstat_count_heap_delete(&relation->pgstat_info);
1358 * Mark tuple for invalidation from system caches at next command
1359 * boundary. We have to do this before WriteBuffer because we need to
1360 * look at the contents of the tuple, so we need to hold our refcount
1363 CacheInvalidateHeapTuple(relation, &tp);
1365 WriteBuffer(buffer);
1367 return HeapTupleMayBeUpdated;
1371 * simple_heap_delete - delete a tuple
1373 * This routine may be used to delete a tuple when concurrent updates of
1374 * the target tuple are not expected (for example, because we have a lock
1375 * on the relation associated with the tuple). Any failure is reported
1379 simple_heap_delete(Relation relation, ItemPointer tid)
1381 ItemPointerData ctid;
1384 result = heap_delete(relation, tid, &ctid, GetCurrentCommandId());
1387 case HeapTupleSelfUpdated:
1388 /* Tuple was already updated in current command? */
1389 elog(ERROR, "simple_heap_delete: tuple already updated by self");
1392 case HeapTupleMayBeUpdated:
1393 /* done successfully */
1396 case HeapTupleUpdated:
1397 elog(ERROR, "simple_heap_delete: tuple concurrently updated");
1401 elog(ERROR, "Unknown status %u from heap_delete", result);
1407 * heap_update - replace a tuple
1409 * NB: do not call this directly unless you are prepared to deal with
1410 * concurrent-update conditions. Use simple_heap_update instead.
1413 heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,
1414 ItemPointer ctid, CommandId cid)
1417 HeapTupleData oldtup;
1427 /* increment access statistics */
1428 IncrHeapAccessStat(local_replace);
1429 IncrHeapAccessStat(global_replace);
1431 Assert(ItemPointerIsValid(otid));
1433 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(otid));
1434 if (!BufferIsValid(buffer))
1435 elog(ERROR, "heap_update: failed ReadBuffer");
1436 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
1438 dp = (PageHeader) BufferGetPage(buffer);
1439 lp = PageGetItemId(dp, ItemPointerGetOffsetNumber(otid));
1441 oldtup.t_datamcxt = NULL;
1442 oldtup.t_data = (HeapTupleHeader) PageGetItem(dp, lp);
1443 oldtup.t_len = ItemIdGetLength(lp);
1444 oldtup.t_self = *otid;
1447 * Note: beyond this point, use oldtup not otid to refer to old tuple.
1448 * otid may very well point at newtup->t_self, which we will overwrite
1449 * with the new tuple's location, so there's great risk of confusion
1450 * if we use otid anymore.
1454 result = HeapTupleSatisfiesUpdate(&oldtup, cid);
1456 if (result == HeapTupleInvisible)
1458 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1459 ReleaseBuffer(buffer);
1460 elog(ERROR, "heap_update: (am)invalid tid");
1462 else if (result == HeapTupleBeingUpdated)
1464 TransactionId xwait = oldtup.t_data->t_xmax;
1466 /* sleep untill concurrent transaction ends */
1467 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1468 XactLockTableWait(xwait);
1470 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
1471 if (TransactionIdDidAbort(xwait))
1475 * xwait is committed but if xwait had just marked the tuple for
1476 * update then some other xaction could update this tuple before
1477 * we got to this point.
1479 if (!TransactionIdEquals(oldtup.t_data->t_xmax, xwait))
1481 if (!(oldtup.t_data->t_infomask & HEAP_XMAX_COMMITTED))
1483 oldtup.t_data->t_infomask |= HEAP_XMAX_COMMITTED;
1484 SetBufferCommitInfoNeedsSave(buffer);
1486 /* if tuple was marked for update but not updated... */
1487 if (oldtup.t_data->t_infomask & HEAP_MARKED_FOR_UPDATE)
1488 result = HeapTupleMayBeUpdated;
1490 result = HeapTupleUpdated;
1492 if (result != HeapTupleMayBeUpdated)
1494 Assert(result == HeapTupleSelfUpdated || result == HeapTupleUpdated);
1495 *ctid = oldtup.t_data->t_ctid;
1496 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1497 ReleaseBuffer(buffer);
1501 /* Fill in OID and transaction status data for newtup */
1502 newtup->t_data->t_oid = oldtup.t_data->t_oid;
1503 TransactionIdStore(GetCurrentTransactionId(), &(newtup->t_data->t_xmin));
1504 newtup->t_data->t_cmin = cid;
1505 StoreInvalidTransactionId(&(newtup->t_data->t_xmax));
1506 newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
1507 newtup->t_data->t_infomask |= (HEAP_XMAX_INVALID | HEAP_UPDATED);
1510 * If the toaster needs to be activated, OR if the new tuple will not
1511 * fit on the same page as the old, then we need to release the
1512 * context lock (but not the pin!) on the old tuple's buffer while we
1513 * are off doing TOAST and/or table-file-extension work. We must mark
1514 * the old tuple to show that it's already being updated, else other
1515 * processes may try to update it themselves. To avoid second XLOG log
1516 * record, we use xact mgr hook to unlock old tuple without reading
1517 * log if xact will abort before update is logged. In the event of
1518 * crash prio logging, TQUAL routines will see HEAP_XMAX_UNLOGGED
1521 * NOTE: this trick is useless currently but saved for future when we'll
1522 * implement UNDO and will re-use transaction IDs after postmaster
1525 * We need to invoke the toaster if there are already any toasted values
1526 * present, or if the new tuple is over-threshold.
1528 need_toast = (HeapTupleHasExtended(&oldtup) ||
1529 HeapTupleHasExtended(newtup) ||
1530 (MAXALIGN(newtup->t_len) > TOAST_TUPLE_THRESHOLD));
1532 newtupsize = MAXALIGN(newtup->t_len);
1533 pagefree = PageGetFreeSpace((Page) dp);
1535 if (need_toast || newtupsize > pagefree)
1537 _locked_tuple_.node = relation->rd_node;
1538 _locked_tuple_.tid = oldtup.t_self;
1539 XactPushRollback(_heap_unlock_tuple, (void *) &_locked_tuple_);
1541 TransactionIdStore(GetCurrentTransactionId(),
1542 &(oldtup.t_data->t_xmax));
1543 oldtup.t_data->t_cmax = cid;
1544 oldtup.t_data->t_infomask &= ~(HEAP_XMAX_COMMITTED |
1546 HEAP_MARKED_FOR_UPDATE);
1547 oldtup.t_data->t_infomask |= HEAP_XMAX_UNLOGGED;
1548 already_marked = true;
1549 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1551 /* Let the toaster do its thing */
1554 heap_tuple_toast_attrs(relation, newtup, &oldtup);
1555 newtupsize = MAXALIGN(newtup->t_len);
1559 * Now, do we need a new page for the tuple, or not? This is a
1560 * bit tricky since someone else could have added tuples to the
1561 * page while we weren't looking. We have to recheck the
1562 * available space after reacquiring the buffer lock. But don't
1563 * bother to do that if the former amount of free space is still
1564 * not enough; it's unlikely there's more free now than before.
1566 * What's more, if we need to get a new page, we will need to acquire
1567 * buffer locks on both old and new pages. To avoid deadlock
1568 * against some other backend trying to get the same two locks in
1569 * the other order, we must be consistent about the order we get
1570 * the locks in. We use the rule "lock the lower-numbered page of
1571 * the relation first". To implement this, we must do
1572 * RelationGetBufferForTuple while not holding the lock on the old
1573 * page, and we must rely on it to get the locks on both pages in
1574 * the correct order.
1576 if (newtupsize > pagefree)
1578 /* Assume there's no chance to put newtup on same page. */
1579 newbuf = RelationGetBufferForTuple(relation, newtup->t_len,
1584 /* Re-acquire the lock on the old tuple's page. */
1585 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
1586 /* Re-check using the up-to-date free space */
1587 pagefree = PageGetFreeSpace((Page) dp);
1588 if (newtupsize > pagefree)
1591 * Rats, it doesn't fit anymore. We must now unlock and
1592 * relock to avoid deadlock. Fortunately, this path
1593 * should seldom be taken.
1595 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1596 newbuf = RelationGetBufferForTuple(relation, newtup->t_len,
1601 /* OK, it fits here, so we're done. */
1608 /* No TOAST work needed, and it'll fit on same page */
1609 already_marked = false;
1613 pgstat_count_heap_update(&relation->pgstat_info);
1616 * At this point newbuf and buffer are both pinned and locked, and
1617 * newbuf has enough space for the new tuple. If they are the same
1618 * buffer, only one pin is held.
1621 /* NO ELOG(ERROR) from here till changes are logged */
1622 START_CRIT_SECTION();
1624 RelationPutHeapTuple(relation, newbuf, newtup); /* insert new tuple */
1628 oldtup.t_data->t_infomask &= ~HEAP_XMAX_UNLOGGED;
1633 TransactionIdStore(GetCurrentTransactionId(),
1634 &(oldtup.t_data->t_xmax));
1635 oldtup.t_data->t_cmax = cid;
1636 oldtup.t_data->t_infomask &= ~(HEAP_XMAX_COMMITTED |
1638 HEAP_MARKED_FOR_UPDATE);
1641 /* record address of new tuple in t_ctid of old one */
1642 oldtup.t_data->t_ctid = newtup->t_self;
1646 XLogRecPtr recptr = log_heap_update(relation, buffer, oldtup.t_self,
1647 newbuf, newtup, false);
1649 if (newbuf != buffer)
1651 PageSetLSN(BufferGetPage(newbuf), recptr);
1652 PageSetSUI(BufferGetPage(newbuf), ThisStartUpID);
1654 PageSetLSN(BufferGetPage(buffer), recptr);
1655 PageSetSUI(BufferGetPage(buffer), ThisStartUpID);
1660 if (newbuf != buffer)
1661 LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
1662 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1665 * Mark old tuple for invalidation from system caches at next command
1666 * boundary. We have to do this before WriteBuffer because we need to
1667 * look at the contents of the tuple, so we need to hold our refcount.
1669 CacheInvalidateHeapTuple(relation, &oldtup);
1671 if (newbuf != buffer)
1672 WriteBuffer(newbuf);
1673 WriteBuffer(buffer);
1676 * If new tuple is cachable, mark it for invalidation from the caches in
1677 * case we abort. Note it is OK to do this after WriteBuffer releases
1678 * the buffer, because the "newtup" data structure is all in local
1679 * memory, not in the shared buffer.
1681 CacheInvalidateHeapTuple(relation, newtup);
1683 return HeapTupleMayBeUpdated;
1687 * simple_heap_update - replace a tuple
1689 * This routine may be used to update a tuple when concurrent updates of
1690 * the target tuple are not expected (for example, because we have a lock
1691 * on the relation associated with the tuple). Any failure is reported
1695 simple_heap_update(Relation relation, ItemPointer otid, HeapTuple tup)
1697 ItemPointerData ctid;
1700 result = heap_update(relation, otid, tup, &ctid, GetCurrentCommandId());
1703 case HeapTupleSelfUpdated:
1704 /* Tuple was already updated in current command? */
1705 elog(ERROR, "simple_heap_update: tuple already updated by self");
1708 case HeapTupleMayBeUpdated:
1709 /* done successfully */
1712 case HeapTupleUpdated:
1713 elog(ERROR, "simple_heap_update: tuple concurrently updated");
1717 elog(ERROR, "Unknown status %u from heap_update", result);
1723 * heap_mark4update - mark a tuple for update
1726 heap_mark4update(Relation relation, HeapTuple tuple, Buffer *buffer,
1729 ItemPointer tid = &(tuple->t_self);
1734 /* increment access statistics */
1735 IncrHeapAccessStat(local_mark4update);
1736 IncrHeapAccessStat(global_mark4update);
1738 *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1740 if (!BufferIsValid(*buffer))
1741 elog(ERROR, "heap_mark4update: failed ReadBuffer");
1743 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
1745 dp = (PageHeader) BufferGetPage(*buffer);
1746 lp = PageGetItemId(dp, ItemPointerGetOffsetNumber(tid));
1747 tuple->t_datamcxt = NULL;
1748 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
1749 tuple->t_len = ItemIdGetLength(lp);
1752 result = HeapTupleSatisfiesUpdate(tuple, cid);
1754 if (result == HeapTupleInvisible)
1756 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
1757 ReleaseBuffer(*buffer);
1758 elog(ERROR, "heap_mark4update: (am)invalid tid");
1760 else if (result == HeapTupleBeingUpdated)
1762 TransactionId xwait = tuple->t_data->t_xmax;
1764 /* sleep untill concurrent transaction ends */
1765 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
1766 XactLockTableWait(xwait);
1768 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
1769 if (TransactionIdDidAbort(xwait))
1773 * xwait is committed but if xwait had just marked the tuple for
1774 * update then some other xaction could update this tuple before
1775 * we got to this point.
1777 if (!TransactionIdEquals(tuple->t_data->t_xmax, xwait))
1779 if (!(tuple->t_data->t_infomask & HEAP_XMAX_COMMITTED))
1781 tuple->t_data->t_infomask |= HEAP_XMAX_COMMITTED;
1782 SetBufferCommitInfoNeedsSave(*buffer);
1784 /* if tuple was marked for update but not updated... */
1785 if (tuple->t_data->t_infomask & HEAP_MARKED_FOR_UPDATE)
1786 result = HeapTupleMayBeUpdated;
1788 result = HeapTupleUpdated;
1790 if (result != HeapTupleMayBeUpdated)
1792 Assert(result == HeapTupleSelfUpdated || result == HeapTupleUpdated);
1793 tuple->t_self = tuple->t_data->t_ctid;
1794 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
1799 * XLOG stuff: no logging is required as long as we have no
1800 * savepoints. For savepoints private log could be used...
1802 ((PageHeader) BufferGetPage(*buffer))->pd_sui = ThisStartUpID;
1804 /* store transaction information of xact marking the tuple */
1805 TransactionIdStore(GetCurrentTransactionId(), &(tuple->t_data->t_xmax));
1806 tuple->t_data->t_cmax = cid;
1807 tuple->t_data->t_infomask &= ~(HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID);
1808 tuple->t_data->t_infomask |= HEAP_MARKED_FOR_UPDATE;
1810 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
1812 WriteNoReleaseBuffer(*buffer);
1814 return HeapTupleMayBeUpdated;
1818 * heap_markpos - mark scan position
1821 * Should only one mark be maintained per scan at one time.
1822 * Check if this can be done generally--say calls to get the
1823 * next/previous tuple and NEVER pass struct scandesc to the
1824 * user AM's. Now, the mark is sent to the executor for safekeeping.
1825 * Probably can store this info into a GENERAL scan structure.
1827 * May be best to change this call to store the marked position
1828 * (up to 2?) in the scan structure itself.
1829 * Fix to use the proper caching structure.
1833 heap_markpos(HeapScanDesc scan)
1836 * increment access statistics
1838 IncrHeapAccessStat(local_markpos);
1839 IncrHeapAccessStat(global_markpos);
1841 /* Note: no locking manipulations needed */
1843 if (scan->rs_ctup.t_data != NULL)
1844 scan->rs_mctid = scan->rs_ctup.t_self;
1846 ItemPointerSetInvalid(&scan->rs_mctid);
1850 * heap_restrpos - restore position to marked location
1852 * Note: there are bad side effects here. If we were past the end
1853 * of a relation when heapmarkpos is called, then if the relation is
1854 * extended via insert, then the next call to heaprestrpos will set
1855 * cause the added tuples to be visible when the scan continues.
1856 * Problems also arise if the TID's are rearranged!!!
1858 * XXX might be better to do direct access instead of
1859 * using the generality of heapgettup().
1861 * XXX It is very possible that when a scan is restored, that a tuple
1862 * XXX which previously qualified may fail for time range purposes, unless
1863 * XXX some form of locking exists (ie., portals currently can act funny.
1867 heap_restrpos(HeapScanDesc scan)
1870 * increment access statistics
1872 IncrHeapAccessStat(local_restrpos);
1873 IncrHeapAccessStat(global_restrpos);
1875 /* XXX no amrestrpos checking that ammarkpos called */
1877 /* Note: no locking manipulations needed */
1880 * unpin scan buffers
1882 if (BufferIsValid(scan->rs_cbuf))
1883 ReleaseBuffer(scan->rs_cbuf);
1884 scan->rs_cbuf = InvalidBuffer;
1886 if (!ItemPointerIsValid(&scan->rs_mctid))
1888 scan->rs_ctup.t_datamcxt = NULL;
1889 scan->rs_ctup.t_data = NULL;
1893 scan->rs_ctup.t_self = scan->rs_mctid;
1894 scan->rs_ctup.t_datamcxt = NULL;
1895 scan->rs_ctup.t_data = (HeapTupleHeader) 0x1; /* for heapgettup */
1896 heapgettup(scan->rs_rd,
1907 log_heap_clean(Relation reln, Buffer buffer, char *unused, int unlen)
1909 xl_heap_clean xlrec;
1911 XLogRecData rdata[3];
1913 xlrec.node = reln->rd_node;
1914 xlrec.block = BufferGetBlockNumber(buffer);
1915 rdata[0].buffer = InvalidBuffer;
1916 rdata[0].data = (char *) &xlrec;
1917 rdata[0].len = SizeOfHeapClean;
1918 rdata[0].next = &(rdata[1]);
1922 rdata[1].buffer = buffer;
1923 rdata[1].data = unused;
1924 rdata[1].len = unlen;
1925 rdata[1].next = &(rdata[2]);
1928 rdata[0].next = &(rdata[2]);
1930 rdata[2].buffer = buffer;
1931 rdata[2].data = NULL;
1933 rdata[2].next = NULL;
1935 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CLEAN, rdata);
1941 log_heap_update(Relation reln, Buffer oldbuf, ItemPointerData from,
1942 Buffer newbuf, HeapTuple newtup, bool move)
1945 * Note: xlhdr is declared to have adequate size and correct alignment
1946 * for an xl_heap_header. However the two tids, if present at all,
1947 * will be packed in with no wasted space after the xl_heap_header;
1948 * they aren't necessarily aligned as implied by this struct
1957 int hsize = SizeOfHeapHeader;
1958 xl_heap_update xlrec;
1960 XLogRecData rdata[4];
1961 Page page = BufferGetPage(newbuf);
1962 uint8 info = (move) ? XLOG_HEAP_MOVE : XLOG_HEAP_UPDATE;
1964 xlrec.target.node = reln->rd_node;
1965 xlrec.target.tid = from;
1966 xlrec.newtid = newtup->t_self;
1967 rdata[0].buffer = InvalidBuffer;
1968 rdata[0].data = (char *) &xlrec;
1969 rdata[0].len = SizeOfHeapUpdate;
1970 rdata[0].next = &(rdata[1]);
1972 rdata[1].buffer = oldbuf;
1973 rdata[1].data = NULL;
1975 rdata[1].next = &(rdata[2]);
1977 xlhdr.hdr.t_oid = newtup->t_data->t_oid;
1978 xlhdr.hdr.t_natts = newtup->t_data->t_natts;
1979 xlhdr.hdr.t_hoff = newtup->t_data->t_hoff;
1980 xlhdr.hdr.mask = newtup->t_data->t_infomask;
1981 if (move) /* remember xmin & xmax */
1985 if (newtup->t_data->t_infomask & HEAP_XMAX_INVALID ||
1986 newtup->t_data->t_infomask & HEAP_MARKED_FOR_UPDATE)
1987 xmax = InvalidTransactionId;
1989 xmax = newtup->t_data->t_xmax;
1990 memcpy((char *) &xlhdr + hsize, &xmax, sizeof(TransactionId));
1991 memcpy((char *) &xlhdr + hsize + sizeof(TransactionId),
1992 &(newtup->t_data->t_xmin), sizeof(TransactionId));
1993 hsize += 2 * sizeof(TransactionId);
1995 rdata[2].buffer = newbuf;
1996 rdata[2].data = (char *) &xlhdr;
1997 rdata[2].len = hsize;
1998 rdata[2].next = &(rdata[3]);
2000 rdata[3].buffer = newbuf;
2001 rdata[3].data = (char *) newtup->t_data + offsetof(HeapTupleHeaderData, t_bits);
2002 rdata[3].len = newtup->t_len - offsetof(HeapTupleHeaderData, t_bits);
2003 rdata[3].next = NULL;
2005 /* If new tuple is the single and first tuple on page... */
2006 if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
2007 PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
2009 info |= XLOG_HEAP_INIT_PAGE;
2010 rdata[2].buffer = rdata[3].buffer = InvalidBuffer;
2013 recptr = XLogInsert(RM_HEAP_ID, info, rdata);
2019 log_heap_move(Relation reln, Buffer oldbuf, ItemPointerData from,
2020 Buffer newbuf, HeapTuple newtup)
2022 return (log_heap_update(reln, oldbuf, from, newbuf, newtup, true));
2026 heap_xlog_clean(bool redo, XLogRecPtr lsn, XLogRecord *record)
2028 xl_heap_clean *xlrec = (xl_heap_clean *) XLogRecGetData(record);
2033 if (!redo || (record->xl_info & XLR_BKP_BLOCK_1))
2036 reln = XLogOpenRelation(redo, RM_HEAP_ID, xlrec->node);
2038 if (!RelationIsValid(reln))
2041 buffer = XLogReadBuffer(false, reln, xlrec->block);
2042 if (!BufferIsValid(buffer))
2043 elog(PANIC, "heap_clean_redo: no block");
2045 page = (Page) BufferGetPage(buffer);
2046 if (PageIsNew((PageHeader) page))
2047 elog(PANIC, "heap_clean_redo: uninitialized page");
2049 if (XLByteLE(lsn, PageGetLSN(page)))
2051 UnlockAndReleaseBuffer(buffer);
2055 if (record->xl_len > SizeOfHeapClean)
2057 OffsetNumber unbuf[BLCKSZ / sizeof(OffsetNumber)];
2058 OffsetNumber *unused = unbuf;
2062 Assert((record->xl_len - SizeOfHeapClean) <= BLCKSZ);
2063 memcpy((char *) unbuf,
2064 (char *) xlrec + SizeOfHeapClean,
2065 record->xl_len - SizeOfHeapClean);
2066 unend = (char *) unbuf + (record->xl_len - SizeOfHeapClean);
2068 while ((char *) unused < unend)
2070 lp = ((PageHeader) page)->pd_linp + *unused;
2071 lp->lp_flags &= ~LP_USED;
2076 PageRepairFragmentation(page, NULL);
2077 UnlockAndWriteBuffer(buffer);
2081 heap_xlog_delete(bool redo, XLogRecPtr lsn, XLogRecord *record)
2083 xl_heap_delete *xlrec = (xl_heap_delete *) XLogRecGetData(record);
2084 Relation reln = XLogOpenRelation(redo, RM_HEAP_ID, xlrec->target.node);
2087 OffsetNumber offnum;
2089 HeapTupleHeader htup;
2091 if (redo && (record->xl_info & XLR_BKP_BLOCK_1))
2094 if (!RelationIsValid(reln))
2097 buffer = XLogReadBuffer(false, reln,
2098 ItemPointerGetBlockNumber(&(xlrec->target.tid)));
2099 if (!BufferIsValid(buffer))
2100 elog(PANIC, "heap_delete_%sdo: no block", (redo) ? "re" : "un");
2102 page = (Page) BufferGetPage(buffer);
2103 if (PageIsNew((PageHeader) page))
2104 elog(PANIC, "heap_delete_%sdo: uninitialized page", (redo) ? "re" : "un");
2108 if (XLByteLE(lsn, PageGetLSN(page))) /* changes are applied */
2110 UnlockAndReleaseBuffer(buffer);
2114 else if (XLByteLT(PageGetLSN(page), lsn)) /* changes are not applied
2116 elog(PANIC, "heap_delete_undo: bad page LSN");
2118 offnum = ItemPointerGetOffsetNumber(&(xlrec->target.tid));
2119 if (PageGetMaxOffsetNumber(page) >= offnum)
2120 lp = PageGetItemId(page, offnum);
2122 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsUsed(lp))
2123 elog(PANIC, "heap_delete_%sdo: invalid lp", (redo) ? "re" : "un");
2125 htup = (HeapTupleHeader) PageGetItem(page, lp);
2129 htup->t_xmax = record->xl_xid;
2130 htup->t_cmax = FirstCommandId;
2131 htup->t_infomask &= ~(HEAP_XMAX_COMMITTED |
2132 HEAP_XMAX_INVALID | HEAP_MARKED_FOR_UPDATE);
2133 PageSetLSN(page, lsn);
2134 PageSetSUI(page, ThisStartUpID);
2135 UnlockAndWriteBuffer(buffer);
2139 elog(PANIC, "heap_delete_undo: unimplemented");
2143 heap_xlog_insert(bool redo, XLogRecPtr lsn, XLogRecord *record)
2145 xl_heap_insert *xlrec = (xl_heap_insert *) XLogRecGetData(record);
2146 Relation reln = XLogOpenRelation(redo, RM_HEAP_ID, xlrec->target.node);
2149 OffsetNumber offnum;
2151 if (redo && (record->xl_info & XLR_BKP_BLOCK_1))
2154 if (!RelationIsValid(reln))
2157 buffer = XLogReadBuffer((redo) ? true : false, reln,
2158 ItemPointerGetBlockNumber(&(xlrec->target.tid)));
2159 if (!BufferIsValid(buffer))
2162 page = (Page) BufferGetPage(buffer);
2163 if (PageIsNew((PageHeader) page) &&
2164 (!redo || !(record->xl_info & XLOG_HEAP_INIT_PAGE)))
2165 elog(PANIC, "heap_insert_%sdo: uninitialized page", (redo) ? "re" : "un");
2171 HeapTupleHeaderData hdr;
2172 char data[MaxTupleSize];
2174 HeapTupleHeader htup;
2175 xl_heap_header xlhdr;
2178 if (record->xl_info & XLOG_HEAP_INIT_PAGE)
2179 PageInit(page, BufferGetPageSize(buffer), 0);
2181 if (XLByteLE(lsn, PageGetLSN(page))) /* changes are applied */
2183 UnlockAndReleaseBuffer(buffer);
2187 offnum = ItemPointerGetOffsetNumber(&(xlrec->target.tid));
2188 if (PageGetMaxOffsetNumber(page) + 1 < offnum)
2189 elog(PANIC, "heap_insert_redo: invalid max offset number");
2191 newlen = record->xl_len - SizeOfHeapInsert - SizeOfHeapHeader;
2192 Assert(newlen <= MaxTupleSize);
2193 memcpy((char *) &xlhdr,
2194 (char *) xlrec + SizeOfHeapInsert,
2196 memcpy((char *) &tbuf + offsetof(HeapTupleHeaderData, t_bits),
2197 (char *) xlrec + SizeOfHeapInsert + SizeOfHeapHeader,
2199 newlen += offsetof(HeapTupleHeaderData, t_bits);
2201 htup->t_oid = xlhdr.t_oid;
2202 htup->t_natts = xlhdr.t_natts;
2203 htup->t_hoff = xlhdr.t_hoff;
2204 htup->t_xmin = record->xl_xid;
2205 htup->t_cmin = FirstCommandId;
2206 htup->t_xmax = InvalidTransactionId;
2207 htup->t_cmax = FirstCommandId;
2208 htup->t_infomask = HEAP_XMAX_INVALID | xlhdr.mask;
2210 offnum = PageAddItem(page, (Item) htup, newlen, offnum,
2211 LP_USED | OverwritePageMode);
2212 if (offnum == InvalidOffsetNumber)
2213 elog(PANIC, "heap_insert_redo: failed to add tuple");
2214 PageSetLSN(page, lsn);
2215 PageSetSUI(page, ThisStartUpID); /* prev sui */
2216 UnlockAndWriteBuffer(buffer);
2221 if (XLByteLT(PageGetLSN(page), lsn)) /* changes are not applied
2223 elog(PANIC, "heap_insert_undo: bad page LSN");
2225 elog(PANIC, "heap_insert_undo: unimplemented");
2229 * Handles UPDATE & MOVE
2232 heap_xlog_update(bool redo, XLogRecPtr lsn, XLogRecord *record, bool move)
2234 xl_heap_update *xlrec = (xl_heap_update *) XLogRecGetData(record);
2235 Relation reln = XLogOpenRelation(redo, RM_HEAP_ID, xlrec->target.node);
2238 (ItemPointerGetBlockNumber(&(xlrec->newtid)) ==
2239 ItemPointerGetBlockNumber(&(xlrec->target.tid)));
2241 OffsetNumber offnum;
2243 HeapTupleHeader htup;
2245 if (!RelationIsValid(reln))
2248 if (redo && (record->xl_info & XLR_BKP_BLOCK_1))
2251 /* Deal with old tuple version */
2253 buffer = XLogReadBuffer(false, reln,
2254 ItemPointerGetBlockNumber(&(xlrec->target.tid)));
2255 if (!BufferIsValid(buffer))
2256 elog(PANIC, "heap_update_%sdo: no block", (redo) ? "re" : "un");
2258 page = (Page) BufferGetPage(buffer);
2259 if (PageIsNew((PageHeader) page))
2260 elog(PANIC, "heap_update_%sdo: uninitialized old page", (redo) ? "re" : "un");
2264 if (XLByteLE(lsn, PageGetLSN(page))) /* changes are applied */
2266 UnlockAndReleaseBuffer(buffer);
2272 else if (XLByteLT(PageGetLSN(page), lsn)) /* changes are not applied
2274 elog(PANIC, "heap_update_undo: bad old tuple page LSN");
2276 offnum = ItemPointerGetOffsetNumber(&(xlrec->target.tid));
2277 if (PageGetMaxOffsetNumber(page) >= offnum)
2278 lp = PageGetItemId(page, offnum);
2280 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsUsed(lp))
2281 elog(PANIC, "heap_update_%sdo: invalid lp", (redo) ? "re" : "un");
2283 htup = (HeapTupleHeader) PageGetItem(page, lp);
2289 TransactionIdStore(record->xl_xid, (TransactionId *) &(htup->t_cmin));
2291 ~(HEAP_XMIN_COMMITTED | HEAP_XMIN_INVALID | HEAP_MOVED_IN);
2292 htup->t_infomask |= HEAP_MOVED_OFF;
2296 htup->t_xmax = record->xl_xid;
2297 htup->t_cmax = FirstCommandId;
2298 htup->t_infomask &= ~(HEAP_XMAX_COMMITTED |
2299 HEAP_XMAX_INVALID | HEAP_MARKED_FOR_UPDATE);
2303 PageSetLSN(page, lsn);
2304 PageSetSUI(page, ThisStartUpID);
2305 UnlockAndWriteBuffer(buffer);
2309 elog(PANIC, "heap_update_undo: unimplemented");
2311 /* Deal with new tuple */
2316 ((record->xl_info & XLR_BKP_BLOCK_2) ||
2317 ((record->xl_info & XLR_BKP_BLOCK_1) && samepage)))
2320 buffer = XLogReadBuffer((redo) ? true : false, reln,
2321 ItemPointerGetBlockNumber(&(xlrec->newtid)));
2322 if (!BufferIsValid(buffer))
2325 page = (Page) BufferGetPage(buffer);
2328 if (PageIsNew((PageHeader) page) &&
2329 (!redo || !(record->xl_info & XLOG_HEAP_INIT_PAGE)))
2330 elog(PANIC, "heap_update_%sdo: uninitialized page", (redo) ? "re" : "un");
2336 HeapTupleHeaderData hdr;
2337 char data[MaxTupleSize];
2339 xl_heap_header xlhdr;
2343 if (record->xl_info & XLOG_HEAP_INIT_PAGE)
2344 PageInit(page, BufferGetPageSize(buffer), 0);
2346 if (XLByteLE(lsn, PageGetLSN(page))) /* changes are applied */
2348 UnlockAndReleaseBuffer(buffer);
2352 offnum = ItemPointerGetOffsetNumber(&(xlrec->newtid));
2353 if (PageGetMaxOffsetNumber(page) + 1 < offnum)
2354 elog(PANIC, "heap_update_redo: invalid max offset number");
2356 hsize = SizeOfHeapUpdate + SizeOfHeapHeader;
2358 hsize += (2 * sizeof(TransactionId));
2360 newlen = record->xl_len - hsize;
2361 Assert(newlen <= MaxTupleSize);
2362 memcpy((char *) &xlhdr,
2363 (char *) xlrec + SizeOfHeapUpdate,
2365 memcpy((char *) &tbuf + offsetof(HeapTupleHeaderData, t_bits),
2366 (char *) xlrec + hsize,
2368 newlen += offsetof(HeapTupleHeaderData, t_bits);
2370 htup->t_oid = xlhdr.t_oid;
2371 htup->t_natts = xlhdr.t_natts;
2372 htup->t_hoff = xlhdr.t_hoff;
2375 hsize = SizeOfHeapUpdate + SizeOfHeapHeader;
2376 memcpy(&(htup->t_xmax),
2377 (char *) xlrec + hsize,
2378 sizeof(TransactionId));
2379 memcpy(&(htup->t_xmin),
2380 (char *) xlrec + hsize + sizeof(TransactionId),
2381 sizeof(TransactionId));
2382 TransactionIdStore(record->xl_xid, (TransactionId *) &(htup->t_cmin));
2383 htup->t_infomask = xlhdr.mask;
2384 htup->t_infomask &= ~(HEAP_XMIN_COMMITTED |
2385 HEAP_XMIN_INVALID | HEAP_MOVED_OFF);
2386 htup->t_infomask |= HEAP_MOVED_IN;
2390 htup->t_xmin = record->xl_xid;
2391 htup->t_cmin = FirstCommandId;
2392 htup->t_xmax = InvalidTransactionId;
2393 htup->t_cmax = FirstCommandId;
2394 htup->t_infomask = HEAP_XMAX_INVALID | xlhdr.mask;
2397 offnum = PageAddItem(page, (Item) htup, newlen, offnum,
2398 LP_USED | OverwritePageMode);
2399 if (offnum == InvalidOffsetNumber)
2400 elog(PANIC, "heap_update_redo: failed to add tuple");
2401 PageSetLSN(page, lsn);
2402 PageSetSUI(page, ThisStartUpID); /* prev sui */
2403 UnlockAndWriteBuffer(buffer);
2408 if (XLByteLT(PageGetLSN(page), lsn)) /* changes not applied?! */
2409 elog(PANIC, "heap_update_undo: bad new tuple page LSN");
2411 elog(PANIC, "heap_update_undo: unimplemented");
2416 _heap_unlock_tuple(void *data)
2418 xl_heaptid *xltid = (xl_heaptid *) data;
2419 Relation reln = XLogOpenRelation(false, RM_HEAP_ID, xltid->node);
2422 OffsetNumber offnum;
2424 HeapTupleHeader htup;
2426 if (!RelationIsValid(reln))
2427 elog(PANIC, "_heap_unlock_tuple: can't open relation");
2429 buffer = XLogReadBuffer(false, reln,
2430 ItemPointerGetBlockNumber(&(xltid->tid)));
2431 if (!BufferIsValid(buffer))
2432 elog(PANIC, "_heap_unlock_tuple: can't read buffer");
2434 page = (Page) BufferGetPage(buffer);
2435 if (PageIsNew((PageHeader) page))
2436 elog(PANIC, "_heap_unlock_tuple: uninitialized page");
2438 offnum = ItemPointerGetOffsetNumber(&(xltid->tid));
2439 if (offnum > PageGetMaxOffsetNumber(page))
2440 elog(PANIC, "_heap_unlock_tuple: invalid itemid");
2441 lp = PageGetItemId(page, offnum);
2443 if (!ItemIdIsUsed(lp) || ItemIdDeleted(lp))
2444 elog(PANIC, "_heap_unlock_tuple: unused/deleted tuple in rollback");
2446 htup = (HeapTupleHeader) PageGetItem(page, lp);
2448 if (!TransactionIdEquals(htup->t_xmax, GetCurrentTransactionId()))
2449 elog(PANIC, "_heap_unlock_tuple: invalid xmax in rollback");
2450 htup->t_infomask &= ~HEAP_XMAX_UNLOGGED;
2451 htup->t_infomask |= HEAP_XMAX_INVALID;
2452 UnlockAndWriteBuffer(buffer);
2457 heap_redo(XLogRecPtr lsn, XLogRecord *record)
2459 uint8 info = record->xl_info & ~XLR_INFO_MASK;
2461 info &= XLOG_HEAP_OPMASK;
2462 if (info == XLOG_HEAP_INSERT)
2463 heap_xlog_insert(true, lsn, record);
2464 else if (info == XLOG_HEAP_DELETE)
2465 heap_xlog_delete(true, lsn, record);
2466 else if (info == XLOG_HEAP_UPDATE)
2467 heap_xlog_update(true, lsn, record, false);
2468 else if (info == XLOG_HEAP_MOVE)
2469 heap_xlog_update(true, lsn, record, true);
2470 else if (info == XLOG_HEAP_CLEAN)
2471 heap_xlog_clean(true, lsn, record);
2473 elog(PANIC, "heap_redo: unknown op code %u", info);
2477 heap_undo(XLogRecPtr lsn, XLogRecord *record)
2479 uint8 info = record->xl_info & ~XLR_INFO_MASK;
2481 info &= XLOG_HEAP_OPMASK;
2482 if (info == XLOG_HEAP_INSERT)
2483 heap_xlog_insert(false, lsn, record);
2484 else if (info == XLOG_HEAP_DELETE)
2485 heap_xlog_delete(false, lsn, record);
2486 else if (info == XLOG_HEAP_UPDATE)
2487 heap_xlog_update(false, lsn, record, false);
2488 else if (info == XLOG_HEAP_MOVE)
2489 heap_xlog_update(false, lsn, record, true);
2490 else if (info == XLOG_HEAP_CLEAN)
2491 heap_xlog_clean(false, lsn, record);
2493 elog(PANIC, "heap_undo: unknown op code %u", info);
2497 out_target(char *buf, xl_heaptid *target)
2499 sprintf(buf + strlen(buf), "node %u/%u; tid %u/%u",
2500 target->node.tblNode, target->node.relNode,
2501 ItemPointerGetBlockNumber(&(target->tid)),
2502 ItemPointerGetOffsetNumber(&(target->tid)));
2506 heap_desc(char *buf, uint8 xl_info, char *rec)
2508 uint8 info = xl_info & ~XLR_INFO_MASK;
2510 info &= XLOG_HEAP_OPMASK;
2511 if (info == XLOG_HEAP_INSERT)
2513 xl_heap_insert *xlrec = (xl_heap_insert *) rec;
2515 strcat(buf, "insert: ");
2516 out_target(buf, &(xlrec->target));
2518 else if (info == XLOG_HEAP_DELETE)
2520 xl_heap_delete *xlrec = (xl_heap_delete *) rec;
2522 strcat(buf, "delete: ");
2523 out_target(buf, &(xlrec->target));
2525 else if (info == XLOG_HEAP_UPDATE || info == XLOG_HEAP_MOVE)
2527 xl_heap_update *xlrec = (xl_heap_update *) rec;
2529 if (info == XLOG_HEAP_UPDATE)
2530 strcat(buf, "update: ");
2532 strcat(buf, "move: ");
2533 out_target(buf, &(xlrec->target));
2534 sprintf(buf + strlen(buf), "; new %u/%u",
2535 ItemPointerGetBlockNumber(&(xlrec->newtid)),
2536 ItemPointerGetOffsetNumber(&(xlrec->newtid)));
2538 else if (info == XLOG_HEAP_CLEAN)
2540 xl_heap_clean *xlrec = (xl_heap_clean *) rec;
2542 sprintf(buf + strlen(buf), "clean: node %u/%u; blk %u",
2543 xlrec->node.tblNode, xlrec->node.relNode, xlrec->block);
2546 strcat(buf, "UNKNOWN");