1 /*-------------------------------------------------------------------------
4 * PostgreSQL logical replay/reorder buffer management
7 * Copyright (c) 2012-2016, PostgreSQL Global Development Group
11 * src/backend/replication/reorderbuffer.c
14 * This module gets handed individual pieces of transactions in the order
15 * they are written to the WAL and is responsible to reassemble them into
16 * toplevel transaction sized pieces. When a transaction is completely
17 * reassembled - signalled by reading the transaction commit record - it
18 * will then call the output plugin (c.f. ReorderBufferCommit()) with the
19 * individual changes. The output plugins rely on snapshots built by
20 * snapbuild.c which hands them to us.
22 * Transactions and subtransactions/savepoints in postgres are not
23 * immediately linked to each other from outside the performing
24 * backend. Only at commit/abort (or special xact_assignment records) they
25 * are linked together. Which means that we will have to splice together a
26 * toplevel transaction from its subtransactions. To do that efficiently we
27 * build a binary heap indexed by the smallest current lsn of the individual
28 * subtransactions' changestreams. As the individual streams are inherently
29 * ordered by LSN - since that is where we build them from - the transaction
30 * can easily be reassembled by always using the subtransaction with the
31 * smallest current LSN from the heap.
33 * In order to cope with large transactions - which can be several times as
34 * big as the available memory - this module supports spooling the contents
35 * of a large transactions to disk. When the transaction is replayed the
36 * contents of individual (sub-)transactions will be read from disk in
39 * This module also has to deal with reassembling toast records from the
40 * individual chunks stored in WAL. When a new (or initial) version of a
41 * tuple is stored in WAL it will always be preceded by the toast chunks
42 * emitted for the columns stored out of line. Within a single toplevel
43 * transaction there will be no other data carrying records between a row's
44 * toast chunks and the row data itself. See ReorderBufferToast* for
46 * -------------------------------------------------------------------------
53 #include "access/rewriteheap.h"
54 #include "access/transam.h"
55 #include "access/tuptoaster.h"
56 #include "access/xact.h"
57 #include "access/xlog_internal.h"
58 #include "catalog/catalog.h"
59 #include "lib/binaryheap.h"
60 #include "miscadmin.h"
61 #include "replication/logical.h"
62 #include "replication/reorderbuffer.h"
63 #include "replication/slot.h"
64 #include "replication/snapbuild.h" /* just for SnapBuildSnapDecRefcount */
65 #include "storage/bufmgr.h"
66 #include "storage/fd.h"
67 #include "storage/sinval.h"
68 #include "utils/builtins.h"
69 #include "utils/combocid.h"
70 #include "utils/memdebug.h"
71 #include "utils/memutils.h"
72 #include "utils/rel.h"
73 #include "utils/relfilenodemap.h"
74 #include "utils/tqual.h"
77 /* entry for a hash table we use to map from xid to our transaction state */
78 typedef struct ReorderBufferTXNByIdEnt
81 ReorderBufferTXN *txn;
82 } ReorderBufferTXNByIdEnt;
84 /* data structures for (relfilenode, ctid) => (cmin, cmax) mapping */
85 typedef struct ReorderBufferTupleCidKey
89 } ReorderBufferTupleCidKey;
91 typedef struct ReorderBufferTupleCidEnt
93 ReorderBufferTupleCidKey key;
96 CommandId combocid; /* just for debugging */
97 } ReorderBufferTupleCidEnt;
99 /* k-way in-order change iteration support structures */
100 typedef struct ReorderBufferIterTXNEntry
103 ReorderBufferChange *change;
104 ReorderBufferTXN *txn;
107 } ReorderBufferIterTXNEntry;
109 typedef struct ReorderBufferIterTXNState
113 dlist_head old_change;
114 ReorderBufferIterTXNEntry entries[FLEXIBLE_ARRAY_MEMBER];
115 } ReorderBufferIterTXNState;
117 /* toast datastructures */
118 typedef struct ReorderBufferToastEnt
120 Oid chunk_id; /* toast_table.chunk_id */
121 int32 last_chunk_seq; /* toast_table.chunk_seq of the last chunk we
123 Size num_chunks; /* number of chunks we've already seen */
124 Size size; /* combined size of chunks seen */
125 dlist_head chunks; /* linked list of chunks */
126 struct varlena *reconstructed; /* reconstructed varlena now pointed
128 } ReorderBufferToastEnt;
130 /* Disk serialization support datastructures */
131 typedef struct ReorderBufferDiskChange
134 ReorderBufferChange change;
136 } ReorderBufferDiskChange;
139 * Maximum number of changes kept in memory, per transaction. After that,
140 * changes are spooled to disk.
142 * The current value should be sufficient to decode the entire transaction
143 * without hitting disk in OLTP workloads, while starting to spool to disk in
144 * other workloads reasonably fast.
146 * At some point in the future it probably makes sense to have a more elaborate
147 * resource management here, but it's not entirely clear what that would look
150 static const Size max_changes_in_memory = 4096;
153 * We use a very simple form of a slab allocator for frequently allocated
154 * objects, simply keeping a fixed number in a linked list when unused,
155 * instead pfree()ing them. Without that in many workloads aset.c becomes a
156 * major bottleneck, especially when spilling to disk while decoding batch
159 static const Size max_cached_changes = 4096 * 2;
160 static const Size max_cached_tuplebufs = 4096 * 2; /* ~8MB */
161 static const Size max_cached_transactions = 512;
164 /* ---------------------------------------
165 * primary reorderbuffer support routines
166 * ---------------------------------------
168 static ReorderBufferTXN *ReorderBufferGetTXN(ReorderBuffer *rb);
169 static void ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
170 static ReorderBufferTXN *ReorderBufferTXNByXid(ReorderBuffer *rb,
171 TransactionId xid, bool create, bool *is_new,
172 XLogRecPtr lsn, bool create_as_top);
174 static void AssertTXNLsnOrder(ReorderBuffer *rb);
176 /* ---------------------------------------
177 * support functions for lsn-order iterating over the ->changes of a
178 * transaction and its subtransactions
180 * used for iteration over the k-way heap merge of a transaction and its
182 * ---------------------------------------
184 static ReorderBufferIterTXNState *ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn);
185 static ReorderBufferChange *
186 ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state);
187 static void ReorderBufferIterTXNFinish(ReorderBuffer *rb,
188 ReorderBufferIterTXNState *state);
189 static void ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn);
192 * ---------------------------------------
193 * Disk serialization support functions
194 * ---------------------------------------
196 static void ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
197 static void ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
198 static void ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
199 int fd, ReorderBufferChange *change);
200 static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
201 int *fd, XLogSegNo *segno);
202 static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
204 static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn);
206 static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap);
207 static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
208 ReorderBufferTXN *txn, CommandId cid);
210 /* ---------------------------------------
211 * toast reassembly support
212 * ---------------------------------------
214 static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn);
215 static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn);
216 static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
217 Relation relation, ReorderBufferChange *change);
218 static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
219 Relation relation, ReorderBufferChange *change);
223 * Allocate a new ReorderBuffer
226 ReorderBufferAllocate(void)
228 ReorderBuffer *buffer;
230 MemoryContext new_ctx;
232 /* allocate memory in own context, to have better accountability */
233 new_ctx = AllocSetContextCreate(CurrentMemoryContext,
235 ALLOCSET_DEFAULT_MINSIZE,
236 ALLOCSET_DEFAULT_INITSIZE,
237 ALLOCSET_DEFAULT_MAXSIZE);
240 (ReorderBuffer *) MemoryContextAlloc(new_ctx, sizeof(ReorderBuffer));
242 memset(&hash_ctl, 0, sizeof(hash_ctl));
244 buffer->context = new_ctx;
246 hash_ctl.keysize = sizeof(TransactionId);
247 hash_ctl.entrysize = sizeof(ReorderBufferTXNByIdEnt);
248 hash_ctl.hcxt = buffer->context;
250 buffer->by_txn = hash_create("ReorderBufferByXid", 1000, &hash_ctl,
251 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
253 buffer->by_txn_last_xid = InvalidTransactionId;
254 buffer->by_txn_last_txn = NULL;
256 buffer->nr_cached_transactions = 0;
257 buffer->nr_cached_changes = 0;
258 buffer->nr_cached_tuplebufs = 0;
260 buffer->outbuf = NULL;
261 buffer->outbufsize = 0;
263 buffer->current_restart_decoding_lsn = InvalidXLogRecPtr;
265 dlist_init(&buffer->toplevel_by_lsn);
266 dlist_init(&buffer->cached_transactions);
267 dlist_init(&buffer->cached_changes);
268 slist_init(&buffer->cached_tuplebufs);
274 * Free a ReorderBuffer
277 ReorderBufferFree(ReorderBuffer *rb)
279 MemoryContext context = rb->context;
282 * We free separately allocated data by entirely scrapping reorderbuffer's
285 MemoryContextDelete(context);
289 * Get an unused, possibly preallocated, ReorderBufferTXN.
291 static ReorderBufferTXN *
292 ReorderBufferGetTXN(ReorderBuffer *rb)
294 ReorderBufferTXN *txn;
296 /* check the slab cache */
297 if (rb->nr_cached_transactions > 0)
299 rb->nr_cached_transactions--;
300 txn = (ReorderBufferTXN *)
301 dlist_container(ReorderBufferTXN, node,
302 dlist_pop_head_node(&rb->cached_transactions));
306 txn = (ReorderBufferTXN *)
307 MemoryContextAlloc(rb->context, sizeof(ReorderBufferTXN));
310 memset(txn, 0, sizeof(ReorderBufferTXN));
312 dlist_init(&txn->changes);
313 dlist_init(&txn->tuplecids);
314 dlist_init(&txn->subtxns);
320 * Free a ReorderBufferTXN.
322 * Deallocation might be delayed for efficiency purposes, for details check
323 * the comments above max_cached_changes's definition.
326 ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
328 /* clean the lookup cache if we were cached (quite likely) */
329 if (rb->by_txn_last_xid == txn->xid)
331 rb->by_txn_last_xid = InvalidTransactionId;
332 rb->by_txn_last_txn = NULL;
335 /* free data that's contained */
337 if (txn->tuplecid_hash != NULL)
339 hash_destroy(txn->tuplecid_hash);
340 txn->tuplecid_hash = NULL;
343 if (txn->invalidations)
345 pfree(txn->invalidations);
346 txn->invalidations = NULL;
349 /* check whether to put into the slab cache */
350 if (rb->nr_cached_transactions < max_cached_transactions)
352 rb->nr_cached_transactions++;
353 dlist_push_head(&rb->cached_transactions, &txn->node);
354 VALGRIND_MAKE_MEM_UNDEFINED(txn, sizeof(ReorderBufferTXN));
355 VALGRIND_MAKE_MEM_DEFINED(&txn->node, sizeof(txn->node));
364 * Get an unused, possibly preallocated, ReorderBufferChange.
366 ReorderBufferChange *
367 ReorderBufferGetChange(ReorderBuffer *rb)
369 ReorderBufferChange *change;
371 /* check the slab cache */
372 if (rb->nr_cached_changes)
374 rb->nr_cached_changes--;
375 change = (ReorderBufferChange *)
376 dlist_container(ReorderBufferChange, node,
377 dlist_pop_head_node(&rb->cached_changes));
381 change = (ReorderBufferChange *)
382 MemoryContextAlloc(rb->context, sizeof(ReorderBufferChange));
385 memset(change, 0, sizeof(ReorderBufferChange));
390 * Free an ReorderBufferChange.
392 * Deallocation might be delayed for efficiency purposes, for details check
393 * the comments above max_cached_changes's definition.
396 ReorderBufferReturnChange(ReorderBuffer *rb, ReorderBufferChange *change)
398 /* free contained data */
399 switch (change->action)
401 case REORDER_BUFFER_CHANGE_INSERT:
402 case REORDER_BUFFER_CHANGE_UPDATE:
403 case REORDER_BUFFER_CHANGE_DELETE:
404 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
405 if (change->data.tp.newtuple)
407 ReorderBufferReturnTupleBuf(rb, change->data.tp.newtuple);
408 change->data.tp.newtuple = NULL;
411 if (change->data.tp.oldtuple)
413 ReorderBufferReturnTupleBuf(rb, change->data.tp.oldtuple);
414 change->data.tp.oldtuple = NULL;
417 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
418 if (change->data.snapshot)
420 ReorderBufferFreeSnap(rb, change->data.snapshot);
421 change->data.snapshot = NULL;
424 /* no data in addition to the struct itself */
425 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
426 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
427 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
431 /* check whether to put into the slab cache */
432 if (rb->nr_cached_changes < max_cached_changes)
434 rb->nr_cached_changes++;
435 dlist_push_head(&rb->cached_changes, &change->node);
436 VALGRIND_MAKE_MEM_UNDEFINED(change, sizeof(ReorderBufferChange));
437 VALGRIND_MAKE_MEM_DEFINED(&change->node, sizeof(change->node));
447 * Get an unused, possibly preallocated, ReorderBufferTupleBuf
449 ReorderBufferTupleBuf *
450 ReorderBufferGetTupleBuf(ReorderBuffer *rb)
452 ReorderBufferTupleBuf *tuple;
454 /* check the slab cache */
455 if (rb->nr_cached_tuplebufs)
457 rb->nr_cached_tuplebufs--;
458 tuple = slist_container(ReorderBufferTupleBuf, node,
459 slist_pop_head_node(&rb->cached_tuplebufs));
460 #ifdef USE_ASSERT_CHECKING
461 memset(tuple, 0xa9, sizeof(ReorderBufferTupleBuf));
466 tuple = (ReorderBufferTupleBuf *)
467 MemoryContextAlloc(rb->context, sizeof(ReorderBufferTupleBuf));
474 * Free an ReorderBufferTupleBuf.
476 * Deallocation might be delayed for efficiency purposes, for details check
477 * the comments above max_cached_changes's definition.
480 ReorderBufferReturnTupleBuf(ReorderBuffer *rb, ReorderBufferTupleBuf *tuple)
482 /* check whether to put into the slab cache */
483 if (rb->nr_cached_tuplebufs < max_cached_tuplebufs)
485 rb->nr_cached_tuplebufs++;
486 slist_push_head(&rb->cached_tuplebufs, &tuple->node);
487 VALGRIND_MAKE_MEM_UNDEFINED(tuple, sizeof(ReorderBufferTupleBuf));
488 VALGRIND_MAKE_MEM_DEFINED(&tuple->node, sizeof(tuple->node));
497 * Return the ReorderBufferTXN from the given buffer, specified by Xid.
498 * If create is true, and a transaction doesn't already exist, create it
499 * (with the given LSN, and as top transaction if that's specified);
500 * when this happens, is_new is set to true.
502 static ReorderBufferTXN *
503 ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create,
504 bool *is_new, XLogRecPtr lsn, bool create_as_top)
506 ReorderBufferTXN *txn;
507 ReorderBufferTXNByIdEnt *ent;
510 Assert(TransactionIdIsValid(xid));
511 Assert(!create || lsn != InvalidXLogRecPtr);
514 * Check the one-entry lookup cache first
516 if (TransactionIdIsValid(rb->by_txn_last_xid) &&
517 rb->by_txn_last_xid == xid)
519 txn = rb->by_txn_last_txn;
523 /* found it, and it's valid */
530 * cached as non-existant, and asked not to create? Then nothing else
535 /* otherwise fall through to create it */
539 * If the cache wasn't hit or it yielded an "does-not-exist" and we want
540 * to create an entry.
543 /* search the lookup table */
544 ent = (ReorderBufferTXNByIdEnt *)
545 hash_search(rb->by_txn,
547 create ? HASH_ENTER : HASH_FIND,
553 /* initialize the new entry, if creation was requested */
556 ent->txn = ReorderBufferGetTXN(rb);
559 txn->first_lsn = lsn;
560 txn->restart_decoding_lsn = rb->current_restart_decoding_lsn;
564 dlist_push_tail(&rb->toplevel_by_lsn, &txn->node);
565 AssertTXNLsnOrder(rb);
569 txn = NULL; /* not found and not asked to create */
572 rb->by_txn_last_xid = xid;
573 rb->by_txn_last_txn = txn;
578 Assert(!create || !!txn);
583 * Queue a change into a transaction so it can be replayed upon commit.
586 ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
587 ReorderBufferChange *change)
589 ReorderBufferTXN *txn;
591 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
594 Assert(InvalidXLogRecPtr != lsn);
595 dlist_push_tail(&txn->changes, &change->node);
599 ReorderBufferCheckSerializeTXN(rb, txn);
603 AssertTXNLsnOrder(ReorderBuffer *rb)
605 #ifdef USE_ASSERT_CHECKING
607 XLogRecPtr prev_first_lsn = InvalidXLogRecPtr;
609 dlist_foreach(iter, &rb->toplevel_by_lsn)
611 ReorderBufferTXN *cur_txn;
613 cur_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
614 Assert(cur_txn->first_lsn != InvalidXLogRecPtr);
616 if (cur_txn->end_lsn != InvalidXLogRecPtr)
617 Assert(cur_txn->first_lsn <= cur_txn->end_lsn);
619 if (prev_first_lsn != InvalidXLogRecPtr)
620 Assert(prev_first_lsn < cur_txn->first_lsn);
622 Assert(!cur_txn->is_known_as_subxact);
623 prev_first_lsn = cur_txn->first_lsn;
629 ReorderBufferGetOldestTXN(ReorderBuffer *rb)
631 ReorderBufferTXN *txn;
633 if (dlist_is_empty(&rb->toplevel_by_lsn))
636 AssertTXNLsnOrder(rb);
638 txn = dlist_head_element(ReorderBufferTXN, node, &rb->toplevel_by_lsn);
640 Assert(!txn->is_known_as_subxact);
641 Assert(txn->first_lsn != InvalidXLogRecPtr);
646 ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr)
648 rb->current_restart_decoding_lsn = ptr;
652 ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid,
653 TransactionId subxid, XLogRecPtr lsn)
655 ReorderBufferTXN *txn;
656 ReorderBufferTXN *subtxn;
660 txn = ReorderBufferTXNByXid(rb, xid, true, &new_top, lsn, true);
661 subtxn = ReorderBufferTXNByXid(rb, subxid, true, &new_sub, lsn, false);
666 * we assign subtransactions to top level transaction even if we don't
667 * have data for it yet, assignment records frequently reference xids
668 * that have not yet produced any records. Knowing those aren't top
669 * level xids allows us to make processing cheaper in some places.
671 dlist_push_tail(&txn->subtxns, &subtxn->node);
674 else if (!subtxn->is_known_as_subxact)
676 subtxn->is_known_as_subxact = true;
677 Assert(subtxn->nsubtxns == 0);
679 /* remove from lsn order list of top-level transactions */
680 dlist_delete(&subtxn->node);
682 /* add to toplevel transaction */
683 dlist_push_tail(&txn->subtxns, &subtxn->node);
688 elog(ERROR, "existing subxact assigned to unknown toplevel xact");
693 * Associate a subtransaction with its toplevel transaction at commit
694 * time. There may be no further changes added after this.
697 ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
698 TransactionId subxid, XLogRecPtr commit_lsn,
701 ReorderBufferTXN *txn;
702 ReorderBufferTXN *subtxn;
704 subtxn = ReorderBufferTXNByXid(rb, subxid, false, NULL,
705 InvalidXLogRecPtr, false);
708 * No need to do anything if that subtxn didn't contain any changes
713 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, commit_lsn, true);
716 elog(ERROR, "subxact logged without previous toplevel record");
719 * Pass the our base snapshot to the parent transaction if it doesn't have
720 * one, or ours is older. That can happen if there are no changes in the
721 * toplevel transaction but in one of the child transactions. This allows
722 * the parent to simply use it's base snapshot initially.
724 if (txn->base_snapshot == NULL ||
725 txn->base_snapshot_lsn > subtxn->base_snapshot_lsn)
727 txn->base_snapshot = subtxn->base_snapshot;
728 txn->base_snapshot_lsn = subtxn->base_snapshot_lsn;
729 subtxn->base_snapshot = NULL;
730 subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
733 subtxn->final_lsn = commit_lsn;
734 subtxn->end_lsn = end_lsn;
736 if (!subtxn->is_known_as_subxact)
738 subtxn->is_known_as_subxact = true;
739 Assert(subtxn->nsubtxns == 0);
741 /* remove from lsn order list of top-level transactions */
742 dlist_delete(&subtxn->node);
744 /* add to subtransaction list */
745 dlist_push_tail(&txn->subtxns, &subtxn->node);
752 * Support for efficiently iterating over a transaction's and its
753 * subtransactions' changes.
755 * We do by doing a k-way merge between transactions/subtransactions. For that
756 * we model the current heads of the different transactions as a binary heap
757 * so we easily know which (sub-)transaction has the change with the smallest
760 * We assume the changes in individual transactions are already sorted by LSN.
764 * Binary heap comparison function.
767 ReorderBufferIterCompare(Datum a, Datum b, void *arg)
769 ReorderBufferIterTXNState *state = (ReorderBufferIterTXNState *) arg;
770 XLogRecPtr pos_a = state->entries[DatumGetInt32(a)].lsn;
771 XLogRecPtr pos_b = state->entries[DatumGetInt32(b)].lsn;
775 else if (pos_a == pos_b)
781 * Allocate & initialize an iterator which iterates in lsn order over a
782 * transaction and all its subtransactions.
784 static ReorderBufferIterTXNState *
785 ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn)
788 ReorderBufferIterTXNState *state;
789 dlist_iter cur_txn_i;
793 * Calculate the size of our heap: one element for every transaction that
794 * contains changes. (Besides the transactions already in the reorder
795 * buffer, we count the one we were directly passed.)
797 if (txn->nentries > 0)
800 dlist_foreach(cur_txn_i, &txn->subtxns)
802 ReorderBufferTXN *cur_txn;
804 cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
806 if (cur_txn->nentries > 0)
811 * TODO: Consider adding fastpath for the rather common nr_txns=1 case, no
812 * need to allocate/build a heap then.
815 /* allocate iteration state */
816 state = (ReorderBufferIterTXNState *)
817 MemoryContextAllocZero(rb->context,
818 sizeof(ReorderBufferIterTXNState) +
819 sizeof(ReorderBufferIterTXNEntry) * nr_txns);
821 state->nr_txns = nr_txns;
822 dlist_init(&state->old_change);
824 for (off = 0; off < state->nr_txns; off++)
826 state->entries[off].fd = -1;
827 state->entries[off].segno = 0;
831 state->heap = binaryheap_allocate(state->nr_txns,
832 ReorderBufferIterCompare,
836 * Now insert items into the binary heap, in an unordered fashion. (We
837 * will run a heap assembly step at the end; this is more efficient.)
842 /* add toplevel transaction if it contains changes */
843 if (txn->nentries > 0)
845 ReorderBufferChange *cur_change;
847 if (txn->nentries != txn->nentries_mem)
848 ReorderBufferRestoreChanges(rb, txn, &state->entries[off].fd,
849 &state->entries[off].segno);
851 cur_change = dlist_head_element(ReorderBufferChange, node,
854 state->entries[off].lsn = cur_change->lsn;
855 state->entries[off].change = cur_change;
856 state->entries[off].txn = txn;
858 binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
861 /* add subtransactions if they contain changes */
862 dlist_foreach(cur_txn_i, &txn->subtxns)
864 ReorderBufferTXN *cur_txn;
866 cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
868 if (cur_txn->nentries > 0)
870 ReorderBufferChange *cur_change;
872 if (txn->nentries != txn->nentries_mem)
873 ReorderBufferRestoreChanges(rb, cur_txn,
874 &state->entries[off].fd,
875 &state->entries[off].segno);
877 cur_change = dlist_head_element(ReorderBufferChange, node,
880 state->entries[off].lsn = cur_change->lsn;
881 state->entries[off].change = cur_change;
882 state->entries[off].txn = cur_txn;
884 binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
888 /* assemble a valid binary heap */
889 binaryheap_build(state->heap);
895 * Return the next change when iterating over a transaction and its
898 * Returns NULL when no further changes exist.
900 static ReorderBufferChange *
901 ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state)
903 ReorderBufferChange *change;
904 ReorderBufferIterTXNEntry *entry;
907 /* nothing there anymore */
908 if (state->heap->bh_size == 0)
911 off = DatumGetInt32(binaryheap_first(state->heap));
912 entry = &state->entries[off];
914 /* free memory we might have "leaked" in the previous *Next call */
915 if (!dlist_is_empty(&state->old_change))
917 change = dlist_container(ReorderBufferChange, node,
918 dlist_pop_head_node(&state->old_change));
919 ReorderBufferReturnChange(rb, change);
920 Assert(dlist_is_empty(&state->old_change));
923 change = entry->change;
926 * update heap with information about which transaction has the next
927 * relevant change in LSN order
930 /* there are in-memory changes */
931 if (dlist_has_next(&entry->txn->changes, &entry->change->node))
933 dlist_node *next = dlist_next_node(&entry->txn->changes, &change->node);
934 ReorderBufferChange *next_change =
935 dlist_container(ReorderBufferChange, node, next);
937 /* txn stays the same */
938 state->entries[off].lsn = next_change->lsn;
939 state->entries[off].change = next_change;
941 binaryheap_replace_first(state->heap, Int32GetDatum(off));
945 /* try to load changes from disk */
946 if (entry->txn->nentries != entry->txn->nentries_mem)
949 * Ugly: restoring changes will reuse *Change records, thus delete the
950 * current one from the per-tx list and only free in the next call.
952 dlist_delete(&change->node);
953 dlist_push_tail(&state->old_change, &change->node);
955 if (ReorderBufferRestoreChanges(rb, entry->txn, &entry->fd,
956 &state->entries[off].segno))
958 /* successfully restored changes from disk */
959 ReorderBufferChange *next_change =
960 dlist_head_element(ReorderBufferChange, node,
961 &entry->txn->changes);
963 elog(DEBUG2, "restored %u/%u changes from disk",
964 (uint32) entry->txn->nentries_mem,
965 (uint32) entry->txn->nentries);
967 Assert(entry->txn->nentries_mem);
968 /* txn stays the same */
969 state->entries[off].lsn = next_change->lsn;
970 state->entries[off].change = next_change;
971 binaryheap_replace_first(state->heap, Int32GetDatum(off));
977 /* ok, no changes there anymore, remove */
978 binaryheap_remove_first(state->heap);
984 * Deallocate the iterator
987 ReorderBufferIterTXNFinish(ReorderBuffer *rb,
988 ReorderBufferIterTXNState *state)
992 for (off = 0; off < state->nr_txns; off++)
994 if (state->entries[off].fd != -1)
995 CloseTransientFile(state->entries[off].fd);
998 /* free memory we might have "leaked" in the last *Next call */
999 if (!dlist_is_empty(&state->old_change))
1001 ReorderBufferChange *change;
1003 change = dlist_container(ReorderBufferChange, node,
1004 dlist_pop_head_node(&state->old_change));
1005 ReorderBufferReturnChange(rb, change);
1006 Assert(dlist_is_empty(&state->old_change));
1009 binaryheap_free(state->heap);
1014 * Cleanup the contents of a transaction, usually after the transaction
1015 * committed or aborted.
1018 ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1021 dlist_mutable_iter iter;
1023 /* cleanup subtransactions & their changes */
1024 dlist_foreach_modify(iter, &txn->subtxns)
1026 ReorderBufferTXN *subtxn;
1028 subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
1031 * Subtransactions are always associated to the toplevel TXN, even if
1032 * they originally were happening inside another subtxn, so we won't
1033 * ever recurse more than one level deep here.
1035 Assert(subtxn->is_known_as_subxact);
1036 Assert(subtxn->nsubtxns == 0);
1038 ReorderBufferCleanupTXN(rb, subtxn);
1041 /* cleanup changes in the toplevel txn */
1042 dlist_foreach_modify(iter, &txn->changes)
1044 ReorderBufferChange *change;
1046 change = dlist_container(ReorderBufferChange, node, iter.cur);
1048 ReorderBufferReturnChange(rb, change);
1052 * Cleanup the tuplecids we stored for decoding catalog snapshot access.
1053 * They are always stored in the toplevel transaction.
1055 dlist_foreach_modify(iter, &txn->tuplecids)
1057 ReorderBufferChange *change;
1059 change = dlist_container(ReorderBufferChange, node, iter.cur);
1060 Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1061 ReorderBufferReturnChange(rb, change);
1064 if (txn->base_snapshot != NULL)
1066 SnapBuildSnapDecRefcount(txn->base_snapshot);
1067 txn->base_snapshot = NULL;
1068 txn->base_snapshot_lsn = InvalidXLogRecPtr;
1071 /* delete from list of known subxacts */
1072 if (txn->is_known_as_subxact)
1074 /* NB: nsubxacts count of parent will be too high now */
1075 dlist_delete(&txn->node);
1077 /* delete from LSN ordered list of toplevel TXNs */
1080 dlist_delete(&txn->node);
1083 /* now remove reference from buffer */
1084 hash_search(rb->by_txn,
1090 /* remove entries spilled to disk */
1091 if (txn->nentries != txn->nentries_mem)
1092 ReorderBufferRestoreCleanup(rb, txn);
1095 ReorderBufferReturnTXN(rb, txn);
1099 * Build a hash with a (relfilenode, ctid) -> (cmin, cmax) mapping for use by
1100 * tqual.c's HeapTupleSatisfiesHistoricMVCC.
1103 ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
1108 if (!txn->has_catalog_changes || dlist_is_empty(&txn->tuplecids))
1111 memset(&hash_ctl, 0, sizeof(hash_ctl));
1113 hash_ctl.keysize = sizeof(ReorderBufferTupleCidKey);
1114 hash_ctl.entrysize = sizeof(ReorderBufferTupleCidEnt);
1115 hash_ctl.hcxt = rb->context;
1118 * create the hash with the exact number of to-be-stored tuplecids from
1121 txn->tuplecid_hash =
1122 hash_create("ReorderBufferTupleCid", txn->ntuplecids, &hash_ctl,
1123 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
1125 dlist_foreach(iter, &txn->tuplecids)
1127 ReorderBufferTupleCidKey key;
1128 ReorderBufferTupleCidEnt *ent;
1130 ReorderBufferChange *change;
1132 change = dlist_container(ReorderBufferChange, node, iter.cur);
1134 Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1136 /* be careful about padding */
1137 memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
1139 key.relnode = change->data.tuplecid.node;
1141 ItemPointerCopy(&change->data.tuplecid.tid,
1144 ent = (ReorderBufferTupleCidEnt *)
1145 hash_search(txn->tuplecid_hash,
1147 HASH_ENTER | HASH_FIND,
1151 ent->cmin = change->data.tuplecid.cmin;
1152 ent->cmax = change->data.tuplecid.cmax;
1153 ent->combocid = change->data.tuplecid.combocid;
1157 Assert(ent->cmin == change->data.tuplecid.cmin);
1158 Assert(ent->cmax == InvalidCommandId ||
1159 ent->cmax == change->data.tuplecid.cmax);
1162 * if the tuple got valid in this transaction and now got deleted
1163 * we already have a valid cmin stored. The cmax will be
1164 * InvalidCommandId though.
1166 ent->cmax = change->data.tuplecid.cmax;
1172 * Copy a provided snapshot so we can modify it privately. This is needed so
1173 * that catalog modifying transactions can look into intermediate catalog
1177 ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
1178 ReorderBufferTXN *txn, CommandId cid)
1185 size = sizeof(SnapshotData) +
1186 sizeof(TransactionId) * orig_snap->xcnt +
1187 sizeof(TransactionId) * (txn->nsubtxns + 1);
1189 snap = MemoryContextAllocZero(rb->context, size);
1190 memcpy(snap, orig_snap, sizeof(SnapshotData));
1192 snap->copied = true;
1193 snap->active_count = 1; /* mark as active so nobody frees it */
1194 snap->regd_count = 0;
1195 snap->xip = (TransactionId *) (snap + 1);
1197 memcpy(snap->xip, orig_snap->xip, sizeof(TransactionId) * snap->xcnt);
1200 * snap->subxip contains all txids that belong to our transaction which we
1201 * need to check via cmin/cmax. Thats why we store the toplevel
1202 * transaction in there as well.
1204 snap->subxip = snap->xip + snap->xcnt;
1205 snap->subxip[i++] = txn->xid;
1208 * nsubxcnt isn't decreased when subtransactions abort, so count manually.
1209 * Since it's an upper boundary it is safe to use it for the allocation
1214 dlist_foreach(iter, &txn->subtxns)
1216 ReorderBufferTXN *sub_txn;
1218 sub_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
1219 snap->subxip[i++] = sub_txn->xid;
1223 /* sort so we can bsearch() later */
1224 qsort(snap->subxip, snap->subxcnt, sizeof(TransactionId), xidComparator);
1226 /* store the specified current CommandId */
1233 * Free a previously ReorderBufferCopySnap'ed snapshot
1236 ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap)
1241 SnapBuildSnapDecRefcount(snap);
1245 * Perform the replay of a transaction and it's non-aborted subtransactions.
1247 * Subtransactions previously have to be processed by
1248 * ReorderBufferCommitChild(), even if previously assigned to the toplevel
1249 * transaction with ReorderBufferAssignChild.
1251 * We currently can only decode a transaction's contents in when their commit
1252 * record is read because that's currently the only place where we know about
1253 * cache invalidations. Thus, once a toplevel commit is read, we iterate over
1254 * the top and subtransactions (using a k-way merge) and replay the changes in
1258 ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
1259 XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
1260 TimestampTz commit_time,
1261 RepOriginId origin_id, XLogRecPtr origin_lsn)
1263 ReorderBufferTXN *txn;
1264 volatile Snapshot snapshot_now;
1265 volatile CommandId command_id = FirstCommandId;
1267 ReorderBufferIterTXNState *volatile iterstate = NULL;
1269 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1272 /* unknown transaction, nothing to replay */
1276 txn->final_lsn = commit_lsn;
1277 txn->end_lsn = end_lsn;
1278 txn->commit_time = commit_time;
1279 txn->origin_id = origin_id;
1280 txn->origin_lsn = origin_lsn;
1282 /* serialize the last bunch of changes if we need start earlier anyway */
1283 if (txn->nentries_mem != txn->nentries)
1284 ReorderBufferSerializeTXN(rb, txn);
1287 * If this transaction didn't have any real changes in our database, it's
1288 * OK not to have a snapshot. Note that ReorderBufferCommitChild will have
1289 * transferred its snapshot to this transaction if it had one and the
1290 * toplevel tx didn't.
1292 if (txn->base_snapshot == NULL)
1294 Assert(txn->ninvalidations == 0);
1295 ReorderBufferCleanupTXN(rb, txn);
1299 snapshot_now = txn->base_snapshot;
1301 /* build data to be able to lookup the CommandIds of catalog tuples */
1302 ReorderBufferBuildTupleCidHash(rb, txn);
1304 /* setup the initial snapshot */
1305 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1308 * Decoding needs access to syscaches et al., which in turn use
1309 * heavyweight locks and such. Thus we need to have enough state around to
1310 * keep track of those. The easiest way is to simply use a transaction
1311 * internally. That also allows us to easily enforce that nothing writes
1312 * to the database by checking for xid assignments.
1314 * When we're called via the SQL SRF there's already a transaction
1315 * started, so start an explicit subtransaction there.
1317 using_subtxn = IsTransactionOrTransactionBlock();
1321 ReorderBufferChange *change;
1322 ReorderBufferChange *specinsert = NULL;
1325 BeginInternalSubTransaction("replay");
1327 StartTransactionCommand();
1331 iterstate = ReorderBufferIterTXNInit(rb, txn);
1332 while ((change = ReorderBufferIterTXNNext(rb, iterstate)) != NULL)
1334 Relation relation = NULL;
1337 switch (change->action)
1339 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
1342 * Confirmation for speculative insertion arrived. Simply
1343 * use as a normal record. It'll be cleaned up at the end
1344 * of INSERT processing.
1346 Assert(specinsert->data.tp.oldtuple == NULL);
1347 change = specinsert;
1348 change->action = REORDER_BUFFER_CHANGE_INSERT;
1350 /* intentionally fall through */
1351 case REORDER_BUFFER_CHANGE_INSERT:
1352 case REORDER_BUFFER_CHANGE_UPDATE:
1353 case REORDER_BUFFER_CHANGE_DELETE:
1354 Assert(snapshot_now);
1356 reloid = RelidByRelfilenode(change->data.tp.relnode.spcNode,
1357 change->data.tp.relnode.relNode);
1360 * Catalog tuple without data, emitted while catalog was
1361 * in the process of being rewritten.
1363 if (reloid == InvalidOid &&
1364 change->data.tp.newtuple == NULL &&
1365 change->data.tp.oldtuple == NULL)
1367 else if (reloid == InvalidOid)
1368 elog(ERROR, "could not map filenode \"%s\" to relation OID",
1369 relpathperm(change->data.tp.relnode,
1372 relation = RelationIdGetRelation(reloid);
1374 if (relation == NULL)
1375 elog(ERROR, "could not open relation with OID %u (for filenode \"%s\")",
1377 relpathperm(change->data.tp.relnode,
1380 if (!RelationIsLogicallyLogged(relation))
1384 * For now ignore sequence changes entirely. Most of the
1385 * time they don't log changes using records we
1386 * understand, so it doesn't make sense to handle the few
1389 if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
1392 /* user-triggered change */
1393 if (!IsToastRelation(relation))
1395 ReorderBufferToastReplace(rb, txn, relation, change);
1396 rb->apply_change(rb, txn, relation, change);
1399 * Only clear reassembled toast chunks if we're sure
1400 * they're not required anymore. The creator of the
1403 if (change->data.tp.clear_toast_afterwards)
1404 ReorderBufferToastReset(rb, txn);
1406 /* we're not interested in toast deletions */
1407 else if (change->action == REORDER_BUFFER_CHANGE_INSERT)
1410 * Need to reassemble the full toasted Datum in
1411 * memory, to ensure the chunks don't get reused till
1412 * we're done remove it from the list of this
1413 * transaction's changes. Otherwise it will get
1414 * freed/reused while restoring spooled data from
1417 dlist_delete(&change->node);
1418 ReorderBufferToastAppendChunk(rb, txn, relation,
1425 * Either speculative insertion was confirmed, or it was
1426 * unsuccessful and the record isn't needed anymore.
1428 if (specinsert != NULL)
1430 ReorderBufferReturnChange(rb, specinsert);
1434 if (relation != NULL)
1436 RelationClose(relation);
1441 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
1444 * Speculative insertions are dealt with by delaying the
1445 * processing of the insert until the confirmation record
1446 * arrives. For that we simply unlink the record from the
1447 * chain, so it does not get freed/reused while restoring
1448 * spooled data from disk.
1450 * This is safe in the face of concurrent catalog changes
1451 * because the relevant relation can't be changed between
1452 * speculative insertion and confirmation due to
1453 * CheckTableNotInUse() and locking.
1456 /* clear out a pending (and thus failed) speculation */
1457 if (specinsert != NULL)
1459 ReorderBufferReturnChange(rb, specinsert);
1463 /* and memorize the pending insertion */
1464 dlist_delete(&change->node);
1465 specinsert = change;
1468 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
1469 /* get rid of the old */
1470 TeardownHistoricSnapshot(false);
1472 if (snapshot_now->copied)
1474 ReorderBufferFreeSnap(rb, snapshot_now);
1476 ReorderBufferCopySnap(rb, change->data.snapshot,
1481 * Restored from disk, need to be careful not to double
1482 * free. We could introduce refcounting for that, but for
1483 * now this seems infrequent enough not to care.
1485 else if (change->data.snapshot->copied)
1488 ReorderBufferCopySnap(rb, change->data.snapshot,
1493 snapshot_now = change->data.snapshot;
1497 /* and continue with the new one */
1498 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1501 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
1502 Assert(change->data.command_id != InvalidCommandId);
1504 if (command_id < change->data.command_id)
1506 command_id = change->data.command_id;
1508 if (!snapshot_now->copied)
1510 /* we don't use the global one anymore */
1511 snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
1515 snapshot_now->curcid = command_id;
1517 TeardownHistoricSnapshot(false);
1518 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1521 * Every time the CommandId is incremented, we could
1522 * see new catalog contents, so execute all
1525 ReorderBufferExecuteInvalidations(rb, txn);
1530 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
1531 elog(ERROR, "tuplecid value in changequeue");
1537 * There's a speculative insertion remaining, just clean in up, it
1538 * can't have been successful, otherwise we'd gotten a confirmation
1543 ReorderBufferReturnChange(rb, specinsert);
1547 /* clean up the iterator */
1548 ReorderBufferIterTXNFinish(rb, iterstate);
1551 /* call commit callback */
1552 rb->commit(rb, txn, commit_lsn);
1554 /* this is just a sanity check against bad output plugin behaviour */
1555 if (GetCurrentTransactionIdIfAny() != InvalidTransactionId)
1556 elog(ERROR, "output plugin used XID %u",
1557 GetCurrentTransactionId());
1560 TeardownHistoricSnapshot(false);
1563 * Aborting the current (sub-)transaction as a whole has the right
1564 * semantics. We want all locks acquired in here to be released, not
1565 * reassigned to the parent and we do not want any database access
1566 * have persistent effects.
1568 AbortCurrentTransaction();
1570 /* make sure there's no cache pollution */
1571 ReorderBufferExecuteInvalidations(rb, txn);
1574 RollbackAndReleaseCurrentSubTransaction();
1576 if (snapshot_now->copied)
1577 ReorderBufferFreeSnap(rb, snapshot_now);
1579 /* remove potential on-disk data, and deallocate */
1580 ReorderBufferCleanupTXN(rb, txn);
1584 /* TODO: Encapsulate cleanup from the PG_TRY and PG_CATCH blocks */
1586 ReorderBufferIterTXNFinish(rb, iterstate);
1588 TeardownHistoricSnapshot(true);
1591 * Force cache invalidation to happen outside of a valid transaction
1592 * to prevent catalog access as we just caught an error.
1594 AbortCurrentTransaction();
1596 /* make sure there's no cache pollution */
1597 ReorderBufferExecuteInvalidations(rb, txn);
1600 RollbackAndReleaseCurrentSubTransaction();
1602 if (snapshot_now->copied)
1603 ReorderBufferFreeSnap(rb, snapshot_now);
1605 /* remove potential on-disk data, and deallocate */
1606 ReorderBufferCleanupTXN(rb, txn);
1614 * Abort a transaction that possibly has previous changes. Needs to be first
1615 * called for subtransactions and then for the toplevel xid.
1617 * NB: Transactions handled here have to have actively aborted (i.e. have
1618 * produced an abort record). Implicitly aborted transactions are handled via
1619 * ReorderBufferAbortOld(); transactions we're just not interesteded in, but
1620 * which have committed are handled in ReorderBufferForget().
1622 * This function purges this transaction and its contents from memory and
1626 ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1628 ReorderBufferTXN *txn;
1630 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1633 /* unknown, nothing to remove */
1638 txn->final_lsn = lsn;
1640 /* remove potential on-disk data, and deallocate */
1641 ReorderBufferCleanupTXN(rb, txn);
1645 * Abort all transactions that aren't actually running anymore because the
1648 * NB: These really have to be transactions that have aborted due to a server
1649 * crash/immediate restart, as we don't deal with invalidations here.
1652 ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid)
1654 dlist_mutable_iter it;
1657 * Iterate through all (potential) toplevel TXNs and abort all that are
1658 * older than what possibly can be running. Once we've found the first
1659 * that is alive we stop, there might be some that acquired an xid earlier
1660 * but started writing later, but it's unlikely and they will cleaned up
1661 * in a later call to ReorderBufferAbortOld().
1663 dlist_foreach_modify(it, &rb->toplevel_by_lsn)
1665 ReorderBufferTXN *txn;
1667 txn = dlist_container(ReorderBufferTXN, node, it.cur);
1669 if (TransactionIdPrecedes(txn->xid, oldestRunningXid))
1671 elog(DEBUG1, "aborting old transaction %u", txn->xid);
1673 /* remove potential on-disk data, and deallocate this tx */
1674 ReorderBufferCleanupTXN(rb, txn);
1682 * Forget the contents of a transaction if we aren't interested in it's
1683 * contents. Needs to be first called for subtransactions and then for the
1686 * This is significantly different to ReorderBufferAbort() because
1687 * transactions that have committed need to be treated differenly from aborted
1688 * ones since they may have modified the catalog.
1690 * Note that this is only allowed to be called in the moment a transaction
1691 * commit has just been read, not earlier; otherwise later records referring
1692 * to this xid might re-create the transaction incompletely.
1695 ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1697 ReorderBufferTXN *txn;
1699 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1702 /* unknown, nothing to forget */
1707 txn->final_lsn = lsn;
1710 * Process cache invalidation messages if there are any. Even if we're not
1711 * interested in the transaction's contents, it could have manipulated the
1712 * catalog and we need to update the caches according to that.
1714 if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
1716 bool use_subtxn = IsTransactionOrTransactionBlock();
1719 BeginInternalSubTransaction("replay");
1722 * Force invalidations to happen outside of a valid transaction - that
1723 * way entries will just be marked as invalid without accessing the
1724 * catalog. That's advantageous because we don't need to setup the
1725 * full state necessary for catalog access.
1728 AbortCurrentTransaction();
1730 ReorderBufferExecuteInvalidations(rb, txn);
1733 RollbackAndReleaseCurrentSubTransaction();
1736 Assert(txn->ninvalidations == 0);
1738 /* remove potential on-disk data, and deallocate */
1739 ReorderBufferCleanupTXN(rb, txn);
1744 * Tell reorderbuffer about an xid seen in the WAL stream. Has to be called at
1745 * least once for every xid in XLogRecord->xl_xid (other places in records
1746 * may, but do not have to be passed through here).
1748 * Reorderbuffer keeps some datastructures about transactions in LSN order,
1749 * for efficiency. To do that it has to know about when transactions are seen
1750 * first in the WAL. As many types of records are not actually interesting for
1751 * logical decoding, they do not necessarily pass though here.
1754 ReorderBufferProcessXid(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1756 /* many records won't have an xid assigned, centralize check here */
1757 if (xid != InvalidTransactionId)
1758 ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1762 * Add a new snapshot to this transaction that may only used after lsn 'lsn'
1763 * because the previous snapshot doesn't describe the catalog correctly for
1767 ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid,
1768 XLogRecPtr lsn, Snapshot snap)
1770 ReorderBufferChange *change = ReorderBufferGetChange(rb);
1772 change->data.snapshot = snap;
1773 change->action = REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT;
1775 ReorderBufferQueueChange(rb, xid, lsn, change);
1779 * Setup the base snapshot of a transaction. The base snapshot is the snapshot
1780 * that is used to decode all changes until either this transaction modifies
1781 * the catalog or another catalog modifying transaction commits.
1783 * Needs to be called before any changes are added with
1784 * ReorderBufferQueueChange().
1787 ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid,
1788 XLogRecPtr lsn, Snapshot snap)
1790 ReorderBufferTXN *txn;
1793 txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true);
1794 Assert(txn->base_snapshot == NULL);
1795 Assert(snap != NULL);
1797 txn->base_snapshot = snap;
1798 txn->base_snapshot_lsn = lsn;
1802 * Access the catalog with this CommandId at this point in the changestream.
1804 * May only be called for command ids > 1
1807 ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
1808 XLogRecPtr lsn, CommandId cid)
1810 ReorderBufferChange *change = ReorderBufferGetChange(rb);
1812 change->data.command_id = cid;
1813 change->action = REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID;
1815 ReorderBufferQueueChange(rb, xid, lsn, change);
1820 * Add new (relfilenode, tid) -> (cmin, cmax) mappings.
1823 ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
1824 XLogRecPtr lsn, RelFileNode node,
1825 ItemPointerData tid, CommandId cmin,
1826 CommandId cmax, CommandId combocid)
1828 ReorderBufferChange *change = ReorderBufferGetChange(rb);
1829 ReorderBufferTXN *txn;
1831 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1833 change->data.tuplecid.node = node;
1834 change->data.tuplecid.tid = tid;
1835 change->data.tuplecid.cmin = cmin;
1836 change->data.tuplecid.cmax = cmax;
1837 change->data.tuplecid.combocid = combocid;
1839 change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
1841 dlist_push_tail(&txn->tuplecids, &change->node);
1846 * Setup the invalidation of the toplevel transaction.
1848 * This needs to be done before ReorderBufferCommit is called!
1851 ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid,
1852 XLogRecPtr lsn, Size nmsgs,
1853 SharedInvalidationMessage *msgs)
1855 ReorderBufferTXN *txn;
1857 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1859 if (txn->ninvalidations != 0)
1860 elog(ERROR, "only ever add one set of invalidations");
1864 txn->ninvalidations = nmsgs;
1865 txn->invalidations = (SharedInvalidationMessage *)
1866 MemoryContextAlloc(rb->context,
1867 sizeof(SharedInvalidationMessage) * nmsgs);
1868 memcpy(txn->invalidations, msgs,
1869 sizeof(SharedInvalidationMessage) * nmsgs);
1873 * Apply all invalidations we know. Possibly we only need parts at this point
1874 * in the changestream but we don't know which those are.
1877 ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn)
1881 for (i = 0; i < txn->ninvalidations; i++)
1882 LocalExecuteInvalidationMessage(&txn->invalidations[i]);
1886 * Mark a transaction as containing catalog changes
1889 ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid,
1892 ReorderBufferTXN *txn;
1894 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1896 txn->has_catalog_changes = true;
1900 * Query whether a transaction is already *known* to contain catalog
1901 * changes. This can be wrong until directly before the commit!
1904 ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
1906 ReorderBufferTXN *txn;
1908 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1913 return txn->has_catalog_changes;
1917 * Have we already added the first snapshot?
1920 ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
1922 ReorderBufferTXN *txn;
1924 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1927 /* transaction isn't known yet, ergo no snapshot */
1932 * TODO: It would be a nice improvement if we would check the toplevel
1933 * transaction in subtransactions, but we'd need to keep track of a bit
1936 return txn->base_snapshot != NULL;
1941 * ---------------------------------------
1942 * Disk serialization support
1943 * ---------------------------------------
1947 * Ensure the IO buffer is >= sz.
1950 ReorderBufferSerializeReserve(ReorderBuffer *rb, Size sz)
1952 if (!rb->outbufsize)
1954 rb->outbuf = MemoryContextAlloc(rb->context, sz);
1955 rb->outbufsize = sz;
1957 else if (rb->outbufsize < sz)
1959 rb->outbuf = repalloc(rb->outbuf, sz);
1960 rb->outbufsize = sz;
1965 * Check whether the transaction tx should spill its data to disk.
1968 ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1971 * TODO: improve accounting so we cheaply can take subtransactions into
1974 if (txn->nentries_mem >= max_changes_in_memory)
1976 ReorderBufferSerializeTXN(rb, txn);
1977 Assert(txn->nentries_mem == 0);
1982 * Spill data of a large transaction (and its subtransactions) to disk.
1985 ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1987 dlist_iter subtxn_i;
1988 dlist_mutable_iter change_i;
1990 XLogSegNo curOpenSegNo = 0;
1992 char path[MAXPGPATH];
1994 elog(DEBUG2, "spill %u changes in XID %u to disk",
1995 (uint32) txn->nentries_mem, txn->xid);
1997 /* do the same to all child TXs */
1998 dlist_foreach(subtxn_i, &txn->subtxns)
2000 ReorderBufferTXN *subtxn;
2002 subtxn = dlist_container(ReorderBufferTXN, node, subtxn_i.cur);
2003 ReorderBufferSerializeTXN(rb, subtxn);
2006 /* serialize changestream */
2007 dlist_foreach_modify(change_i, &txn->changes)
2009 ReorderBufferChange *change;
2011 change = dlist_container(ReorderBufferChange, node, change_i.cur);
2014 * store in segment in which it belongs by start lsn, don't split over
2015 * multiple segments tho
2017 if (fd == -1 || !XLByteInSeg(change->lsn, curOpenSegNo))
2022 CloseTransientFile(fd);
2024 XLByteToSeg(change->lsn, curOpenSegNo);
2025 XLogSegNoOffsetToRecPtr(curOpenSegNo, 0, recptr);
2028 * No need to care about TLIs here, only used during a single run,
2029 * so each LSN only maps to a specific WAL record.
2031 sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2032 NameStr(MyReplicationSlot->data.name), txn->xid,
2033 (uint32) (recptr >> 32), (uint32) recptr);
2035 /* open segment, create it if necessary */
2036 fd = OpenTransientFile(path,
2037 O_CREAT | O_WRONLY | O_APPEND | PG_BINARY,
2042 (errcode_for_file_access(),
2043 errmsg("could not open file \"%s\": %m",
2047 ReorderBufferSerializeChange(rb, txn, fd, change);
2048 dlist_delete(&change->node);
2049 ReorderBufferReturnChange(rb, change);
2054 Assert(spilled == txn->nentries_mem);
2055 Assert(dlist_is_empty(&txn->changes));
2056 txn->nentries_mem = 0;
2059 CloseTransientFile(fd);
2063 * Serialize individual change to disk.
2066 ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2067 int fd, ReorderBufferChange *change)
2069 ReorderBufferDiskChange *ondisk;
2070 Size sz = sizeof(ReorderBufferDiskChange);
2072 ReorderBufferSerializeReserve(rb, sz);
2074 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2075 memcpy(&ondisk->change, change, sizeof(ReorderBufferChange));
2077 switch (change->action)
2079 /* fall through these, they're all similar enough */
2080 case REORDER_BUFFER_CHANGE_INSERT:
2081 case REORDER_BUFFER_CHANGE_UPDATE:
2082 case REORDER_BUFFER_CHANGE_DELETE:
2083 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2086 ReorderBufferTupleBuf *oldtup,
2091 oldtup = change->data.tp.oldtuple;
2092 newtup = change->data.tp.newtuple;
2095 oldlen = offsetof(ReorderBufferTupleBuf, t_data) +
2096 oldtup->tuple.t_len;
2099 newlen = offsetof(ReorderBufferTupleBuf, t_data) +
2100 newtup->tuple.t_len;
2105 /* make sure we have enough space */
2106 ReorderBufferSerializeReserve(rb, sz);
2108 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2109 /* might have been reallocated above */
2110 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2114 memcpy(data, oldtup, oldlen);
2120 memcpy(data, newtup, newlen);
2125 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2130 snap = change->data.snapshot;
2132 sz += sizeof(SnapshotData) +
2133 sizeof(TransactionId) * snap->xcnt +
2134 sizeof(TransactionId) * snap->subxcnt
2137 /* make sure we have enough space */
2138 ReorderBufferSerializeReserve(rb, sz);
2139 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2140 /* might have been reallocated above */
2141 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2143 memcpy(data, snap, sizeof(SnapshotData));
2144 data += sizeof(SnapshotData);
2148 memcpy(data, snap->xip,
2149 sizeof(TransactionId) * snap->xcnt);
2150 data += sizeof(TransactionId) * snap->xcnt;
2155 memcpy(data, snap->subxip,
2156 sizeof(TransactionId) * snap->subxcnt);
2157 data += sizeof(TransactionId) * snap->subxcnt;
2161 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2162 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2163 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2164 /* ReorderBufferChange contains everything important */
2170 if (write(fd, rb->outbuf, ondisk->size) != ondisk->size)
2172 CloseTransientFile(fd);
2174 (errcode_for_file_access(),
2175 errmsg("could not write to data file for XID %u: %m",
2179 Assert(ondisk->change.action == change->action);
2183 * Restore a number of changes spilled to disk back into memory.
2186 ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
2187 int *fd, XLogSegNo *segno)
2190 XLogSegNo last_segno;
2191 dlist_mutable_iter cleanup_iter;
2193 Assert(txn->first_lsn != InvalidXLogRecPtr);
2194 Assert(txn->final_lsn != InvalidXLogRecPtr);
2196 /* free current entries, so we have memory for more */
2197 dlist_foreach_modify(cleanup_iter, &txn->changes)
2199 ReorderBufferChange *cleanup =
2200 dlist_container(ReorderBufferChange, node, cleanup_iter.cur);
2202 dlist_delete(&cleanup->node);
2203 ReorderBufferReturnChange(rb, cleanup);
2205 txn->nentries_mem = 0;
2206 Assert(dlist_is_empty(&txn->changes));
2208 XLByteToSeg(txn->final_lsn, last_segno);
2210 while (restored < max_changes_in_memory && *segno <= last_segno)
2213 ReorderBufferDiskChange *ondisk;
2218 char path[MAXPGPATH];
2223 XLByteToSeg(txn->first_lsn, *segno);
2226 Assert(*segno != 0 || dlist_is_empty(&txn->changes));
2227 XLogSegNoOffsetToRecPtr(*segno, 0, recptr);
2230 * No need to care about TLIs here, only used during a single run,
2231 * so each LSN only maps to a specific WAL record.
2233 sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2234 NameStr(MyReplicationSlot->data.name), txn->xid,
2235 (uint32) (recptr >> 32), (uint32) recptr);
2237 *fd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
2238 if (*fd < 0 && errno == ENOENT)
2246 (errcode_for_file_access(),
2247 errmsg("could not open file \"%s\": %m",
2253 * Read the statically sized part of a change which has information
2254 * about the total size. If we couldn't read a record, we're at the
2257 ReorderBufferSerializeReserve(rb, sizeof(ReorderBufferDiskChange));
2258 readBytes = read(*fd, rb->outbuf, sizeof(ReorderBufferDiskChange));
2263 CloseTransientFile(*fd);
2268 else if (readBytes < 0)
2270 (errcode_for_file_access(),
2271 errmsg("could not read from reorderbuffer spill file: %m")));
2272 else if (readBytes != sizeof(ReorderBufferDiskChange))
2274 (errcode_for_file_access(),
2275 errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2277 (uint32) sizeof(ReorderBufferDiskChange))));
2279 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2281 ReorderBufferSerializeReserve(rb,
2282 sizeof(ReorderBufferDiskChange) + ondisk->size);
2283 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2285 readBytes = read(*fd, rb->outbuf + sizeof(ReorderBufferDiskChange),
2286 ondisk->size - sizeof(ReorderBufferDiskChange));
2290 (errcode_for_file_access(),
2291 errmsg("could not read from reorderbuffer spill file: %m")));
2292 else if (readBytes != ondisk->size - sizeof(ReorderBufferDiskChange))
2294 (errcode_for_file_access(),
2295 errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2297 (uint32) (ondisk->size - sizeof(ReorderBufferDiskChange)))));
2300 * ok, read a full change from disk, now restore it into proper
2303 ReorderBufferRestoreChange(rb, txn, rb->outbuf);
2311 * Convert change from its on-disk format to in-memory format and queue it onto
2312 * the TXN's ->changes list.
2315 ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2318 ReorderBufferDiskChange *ondisk;
2319 ReorderBufferChange *change;
2321 ondisk = (ReorderBufferDiskChange *) data;
2323 change = ReorderBufferGetChange(rb);
2325 /* copy static part */
2326 memcpy(change, &ondisk->change, sizeof(ReorderBufferChange));
2328 data += sizeof(ReorderBufferDiskChange);
2330 /* restore individual stuff */
2331 switch (change->action)
2333 /* fall through these, they're all similar enough */
2334 case REORDER_BUFFER_CHANGE_INSERT:
2335 case REORDER_BUFFER_CHANGE_UPDATE:
2336 case REORDER_BUFFER_CHANGE_DELETE:
2337 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2338 if (change->data.tp.newtuple)
2340 Size len = offsetof(ReorderBufferTupleBuf, t_data) +
2341 ((ReorderBufferTupleBuf *) data)->tuple.t_len;
2343 change->data.tp.newtuple = ReorderBufferGetTupleBuf(rb);
2344 memcpy(change->data.tp.newtuple, data, len);
2345 change->data.tp.newtuple->tuple.t_data =
2346 &change->data.tp.newtuple->t_data.header;
2350 if (change->data.tp.oldtuple)
2352 Size len = offsetof(ReorderBufferTupleBuf, t_data) +
2353 ((ReorderBufferTupleBuf *) data)->tuple.t_len;
2355 change->data.tp.oldtuple = ReorderBufferGetTupleBuf(rb);
2356 memcpy(change->data.tp.oldtuple, data, len);
2357 change->data.tp.oldtuple->tuple.t_data =
2358 &change->data.tp.oldtuple->t_data.header;
2362 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2368 oldsnap = (Snapshot) data;
2370 size = sizeof(SnapshotData) +
2371 sizeof(TransactionId) * oldsnap->xcnt +
2372 sizeof(TransactionId) * (oldsnap->subxcnt + 0);
2374 change->data.snapshot = MemoryContextAllocZero(rb->context, size);
2376 newsnap = change->data.snapshot;
2378 memcpy(newsnap, data, size);
2379 newsnap->xip = (TransactionId *)
2380 (((char *) newsnap) + sizeof(SnapshotData));
2381 newsnap->subxip = newsnap->xip + newsnap->xcnt;
2382 newsnap->copied = true;
2385 /* the base struct contains all the data, easy peasy */
2386 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2387 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2388 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2392 dlist_push_tail(&txn->changes, &change->node);
2393 txn->nentries_mem++;
2397 * Remove all on-disk stored for the passed in transaction.
2400 ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
2406 Assert(txn->first_lsn != InvalidXLogRecPtr);
2407 Assert(txn->final_lsn != InvalidXLogRecPtr);
2409 XLByteToSeg(txn->first_lsn, first);
2410 XLByteToSeg(txn->final_lsn, last);
2412 /* iterate over all possible filenames, and delete them */
2413 for (cur = first; cur <= last; cur++)
2415 char path[MAXPGPATH];
2418 XLogSegNoOffsetToRecPtr(cur, 0, recptr);
2420 sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2421 NameStr(MyReplicationSlot->data.name), txn->xid,
2422 (uint32) (recptr >> 32), (uint32) recptr);
2423 if (unlink(path) != 0 && errno != ENOENT)
2425 (errcode_for_file_access(),
2426 errmsg("could not remove file \"%s\": %m", path)));
2431 * Delete all data spilled to disk after we've restarted/crashed. It will be
2432 * recreated when the respective slots are reused.
2435 StartupReorderBuffer(void)
2438 struct dirent *logical_de;
2441 struct dirent *spill_de;
2443 logical_dir = AllocateDir("pg_replslot");
2444 while ((logical_de = ReadDir(logical_dir, "pg_replslot")) != NULL)
2446 struct stat statbuf;
2447 char path[MAXPGPATH];
2449 if (strcmp(logical_de->d_name, ".") == 0 ||
2450 strcmp(logical_de->d_name, "..") == 0)
2453 /* if it cannot be a slot, skip the directory */
2454 if (!ReplicationSlotValidateName(logical_de->d_name, DEBUG2))
2458 * ok, has to be a surviving logical slot, iterate and delete
2459 * everythign starting with xid-*
2461 sprintf(path, "pg_replslot/%s", logical_de->d_name);
2463 /* we're only creating directories here, skip if it's not our's */
2464 if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
2467 spill_dir = AllocateDir(path);
2468 while ((spill_de = ReadDir(spill_dir, path)) != NULL)
2470 if (strcmp(spill_de->d_name, ".") == 0 ||
2471 strcmp(spill_de->d_name, "..") == 0)
2474 /* only look at names that can be ours */
2475 if (strncmp(spill_de->d_name, "xid", 3) == 0)
2477 sprintf(path, "pg_replslot/%s/%s", logical_de->d_name,
2480 if (unlink(path) != 0)
2482 (errcode_for_file_access(),
2483 errmsg("could not remove file \"%s\": %m",
2489 FreeDir(logical_dir);
2492 /* ---------------------------------------
2493 * toast reassembly support
2494 * ---------------------------------------
2498 * Initialize per tuple toast reconstruction support.
2501 ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
2505 Assert(txn->toast_hash == NULL);
2507 memset(&hash_ctl, 0, sizeof(hash_ctl));
2508 hash_ctl.keysize = sizeof(Oid);
2509 hash_ctl.entrysize = sizeof(ReorderBufferToastEnt);
2510 hash_ctl.hcxt = rb->context;
2511 txn->toast_hash = hash_create("ReorderBufferToastHash", 5, &hash_ctl,
2512 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
2516 * Per toast-chunk handling for toast reconstruction
2518 * Appends a toast chunk so we can reconstruct it when the tuple "owning" the
2519 * toasted Datum comes along.
2522 ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
2523 Relation relation, ReorderBufferChange *change)
2525 ReorderBufferToastEnt *ent;
2526 ReorderBufferTupleBuf *newtup;
2531 TupleDesc desc = RelationGetDescr(relation);
2535 if (txn->toast_hash == NULL)
2536 ReorderBufferToastInitHash(rb, txn);
2538 Assert(IsToastRelation(relation));
2540 newtup = change->data.tp.newtuple;
2541 chunk_id = DatumGetObjectId(fastgetattr(&newtup->tuple, 1, desc, &isnull));
2543 chunk_seq = DatumGetInt32(fastgetattr(&newtup->tuple, 2, desc, &isnull));
2546 ent = (ReorderBufferToastEnt *)
2547 hash_search(txn->toast_hash,
2554 Assert(ent->chunk_id == chunk_id);
2555 ent->num_chunks = 0;
2556 ent->last_chunk_seq = 0;
2558 ent->reconstructed = NULL;
2559 dlist_init(&ent->chunks);
2562 elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq 0",
2563 chunk_seq, chunk_id);
2565 else if (found && chunk_seq != ent->last_chunk_seq + 1)
2566 elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq %d",
2567 chunk_seq, chunk_id, ent->last_chunk_seq + 1);
2569 chunk = DatumGetPointer(fastgetattr(&newtup->tuple, 3, desc, &isnull));
2572 /* calculate size so we can allocate the right size at once later */
2573 if (!VARATT_IS_EXTENDED(chunk))
2574 chunksize = VARSIZE(chunk) - VARHDRSZ;
2575 else if (VARATT_IS_SHORT(chunk))
2576 /* could happen due to heap_form_tuple doing its thing */
2577 chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT;
2579 elog(ERROR, "unexpected type of toast chunk");
2581 ent->size += chunksize;
2582 ent->last_chunk_seq = chunk_seq;
2584 dlist_push_tail(&ent->chunks, &change->node);
2588 * Rejigger change->newtuple to point to in-memory toast tuples instead to
2589 * on-disk toast tuples that may not longer exist (think DROP TABLE or VACUUM).
2591 * We cannot replace unchanged toast tuples though, so those will still point
2592 * to on-disk toast data.
2595 ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
2596 Relation relation, ReorderBufferChange *change)
2605 TupleDesc toast_desc;
2606 MemoryContext oldcontext;
2607 ReorderBufferTupleBuf *newtup;
2609 /* no toast tuples changed */
2610 if (txn->toast_hash == NULL)
2613 oldcontext = MemoryContextSwitchTo(rb->context);
2615 /* we should only have toast tuples in an INSERT or UPDATE */
2616 Assert(change->data.tp.newtuple);
2618 desc = RelationGetDescr(relation);
2620 toast_rel = RelationIdGetRelation(relation->rd_rel->reltoastrelid);
2621 toast_desc = RelationGetDescr(toast_rel);
2623 /* should we allocate from stack instead? */
2624 attrs = palloc0(sizeof(Datum) * desc->natts);
2625 isnull = palloc0(sizeof(bool) * desc->natts);
2626 free = palloc0(sizeof(bool) * desc->natts);
2628 newtup = change->data.tp.newtuple;
2630 heap_deform_tuple(&newtup->tuple, desc, attrs, isnull);
2632 for (natt = 0; natt < desc->natts; natt++)
2634 Form_pg_attribute attr = desc->attrs[natt];
2635 ReorderBufferToastEnt *ent;
2636 struct varlena *varlena;
2638 /* va_rawsize is the size of the original datum -- including header */
2639 struct varatt_external toast_pointer;
2640 struct varatt_indirect redirect_pointer;
2641 struct varlena *new_datum = NULL;
2642 struct varlena *reconstructed;
2646 /* system columns aren't toasted */
2647 if (attr->attnum < 0)
2650 if (attr->attisdropped)
2653 /* not a varlena datatype */
2654 if (attr->attlen != -1)
2661 /* ok, we know we have a toast datum */
2662 varlena = (struct varlena *) DatumGetPointer(attrs[natt]);
2664 /* no need to do anything if the tuple isn't external */
2665 if (!VARATT_IS_EXTERNAL(varlena))
2668 VARATT_EXTERNAL_GET_POINTER(toast_pointer, varlena);
2671 * Check whether the toast tuple changed, replace if so.
2673 ent = (ReorderBufferToastEnt *)
2674 hash_search(txn->toast_hash,
2675 (void *) &toast_pointer.va_valueid,
2682 (struct varlena *) palloc0(INDIRECT_POINTER_SIZE);
2686 reconstructed = palloc0(toast_pointer.va_rawsize);
2688 ent->reconstructed = reconstructed;
2690 /* stitch toast tuple back together from its parts */
2691 dlist_foreach(it, &ent->chunks)
2694 ReorderBufferChange *cchange;
2695 ReorderBufferTupleBuf *ctup;
2698 cchange = dlist_container(ReorderBufferChange, node, it.cur);
2699 ctup = cchange->data.tp.newtuple;
2700 chunk = DatumGetPointer(
2701 fastgetattr(&ctup->tuple, 3, toast_desc, &isnull));
2704 Assert(!VARATT_IS_EXTERNAL(chunk));
2705 Assert(!VARATT_IS_SHORT(chunk));
2707 memcpy(VARDATA(reconstructed) + data_done,
2709 VARSIZE(chunk) - VARHDRSZ);
2710 data_done += VARSIZE(chunk) - VARHDRSZ;
2712 Assert(data_done == toast_pointer.va_extsize);
2714 /* make sure its marked as compressed or not */
2715 if (VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer))
2716 SET_VARSIZE_COMPRESSED(reconstructed, data_done + VARHDRSZ);
2718 SET_VARSIZE(reconstructed, data_done + VARHDRSZ);
2720 memset(&redirect_pointer, 0, sizeof(redirect_pointer));
2721 redirect_pointer.pointer = reconstructed;
2723 SET_VARTAG_EXTERNAL(new_datum, VARTAG_INDIRECT);
2724 memcpy(VARDATA_EXTERNAL(new_datum), &redirect_pointer,
2725 sizeof(redirect_pointer));
2727 attrs[natt] = PointerGetDatum(new_datum);
2731 * Build tuple in separate memory & copy tuple back into the tuplebuf
2732 * passed to the output plugin. We can't directly heap_fill_tuple() into
2733 * the tuplebuf because attrs[] will point back into the current content.
2735 tmphtup = heap_form_tuple(desc, attrs, isnull);
2736 Assert(newtup->tuple.t_len <= MaxHeapTupleSize);
2737 Assert(&newtup->t_data.header == newtup->tuple.t_data);
2739 memcpy(newtup->tuple.t_data, tmphtup->t_data, tmphtup->t_len);
2740 newtup->tuple.t_len = tmphtup->t_len;
2743 * free resources we won't further need, more persistent stuff will be
2744 * free'd in ReorderBufferToastReset().
2746 RelationClose(toast_rel);
2748 for (natt = 0; natt < desc->natts; natt++)
2751 pfree(DatumGetPointer(attrs[natt]));
2757 MemoryContextSwitchTo(oldcontext);
2761 * Free all resources allocated for toast reconstruction.
2764 ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn)
2766 HASH_SEQ_STATUS hstat;
2767 ReorderBufferToastEnt *ent;
2769 if (txn->toast_hash == NULL)
2772 /* sequentially walk over the hash and free everything */
2773 hash_seq_init(&hstat, txn->toast_hash);
2774 while ((ent = (ReorderBufferToastEnt *) hash_seq_search(&hstat)) != NULL)
2776 dlist_mutable_iter it;
2778 if (ent->reconstructed != NULL)
2779 pfree(ent->reconstructed);
2781 dlist_foreach_modify(it, &ent->chunks)
2783 ReorderBufferChange *change =
2784 dlist_container(ReorderBufferChange, node, it.cur);
2786 dlist_delete(&change->node);
2787 ReorderBufferReturnChange(rb, change);
2791 hash_destroy(txn->toast_hash);
2792 txn->toast_hash = NULL;
2796 /* ---------------------------------------
2797 * Visibility support for logical decoding
2800 * Lookup actual cmin/cmax values when using decoding snapshot. We can't
2801 * always rely on stored cmin/cmax values because of two scenarios:
2803 * * A tuple got changed multiple times during a single transaction and thus
2804 * has got a combocid. Combocid's are only valid for the duration of a
2805 * single transaction.
2806 * * A tuple with a cmin but no cmax (and thus no combocid) got
2807 * deleted/updated in another transaction than the one which created it
2808 * which we are looking at right now. As only one of cmin, cmax or combocid
2809 * is actually stored in the heap we don't have access to the value we
2812 * To resolve those problems we have a per-transaction hash of (cmin,
2813 * cmax) tuples keyed by (relfilenode, ctid) which contains the actual
2814 * (cmin, cmax) values. That also takes care of combocids by simply
2815 * not caring about them at all. As we have the real cmin/cmax values
2816 * combocids aren't interesting.
2818 * As we only care about catalog tuples here the overhead of this
2819 * hashtable should be acceptable.
2821 * Heap rewrites complicate this a bit, check rewriteheap.c for
2823 * -------------------------------------------------------------------------
2826 /* struct for qsort()ing mapping files by lsn somewhat efficiently */
2827 typedef struct RewriteMappingFile
2830 char fname[MAXPGPATH];
2831 } RewriteMappingFile;
2835 DisplayMapping(HTAB *tuplecid_data)
2837 HASH_SEQ_STATUS hstat;
2838 ReorderBufferTupleCidEnt *ent;
2840 hash_seq_init(&hstat, tuplecid_data);
2841 while ((ent = (ReorderBufferTupleCidEnt *) hash_seq_search(&hstat)) != NULL)
2843 elog(DEBUG3, "mapping: node: %u/%u/%u tid: %u/%u cmin: %u, cmax: %u",
2844 ent->key.relnode.dbNode,
2845 ent->key.relnode.spcNode,
2846 ent->key.relnode.relNode,
2847 BlockIdGetBlockNumber(&ent->key.tid.ip_blkid),
2848 ent->key.tid.ip_posid,
2857 * Apply a single mapping file to tuplecid_data.
2859 * The mapping file has to have been verified to be a) committed b) for our
2860 * transaction c) applied in LSN order.
2863 ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname)
2865 char path[MAXPGPATH];
2868 LogicalRewriteMappingData map;
2870 sprintf(path, "pg_logical/mappings/%s", fname);
2871 fd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
2874 (errmsg("could not open file \"%s\": %m", path)));
2878 ReorderBufferTupleCidKey key;
2879 ReorderBufferTupleCidEnt *ent;
2880 ReorderBufferTupleCidEnt *new_ent;
2883 /* be careful about padding */
2884 memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
2886 /* read all mappings till the end of the file */
2887 readBytes = read(fd, &map, sizeof(LogicalRewriteMappingData));
2891 (errcode_for_file_access(),
2892 errmsg("could not read file \"%s\": %m",
2894 else if (readBytes == 0) /* EOF */
2896 else if (readBytes != sizeof(LogicalRewriteMappingData))
2898 (errcode_for_file_access(),
2899 errmsg("could not read from file \"%s\": read %d instead of %d bytes",
2901 (int32) sizeof(LogicalRewriteMappingData))));
2903 key.relnode = map.old_node;
2904 ItemPointerCopy(&map.old_tid,
2908 ent = (ReorderBufferTupleCidEnt *)
2909 hash_search(tuplecid_data,
2914 /* no existing mapping, no need to update */
2918 key.relnode = map.new_node;
2919 ItemPointerCopy(&map.new_tid,
2922 new_ent = (ReorderBufferTupleCidEnt *)
2923 hash_search(tuplecid_data,
2931 * Make sure the existing mapping makes sense. We sometime update
2932 * old records that did not yet have a cmax (e.g. pg_class' own
2933 * entry while rewriting it) during rewrites, so allow that.
2935 Assert(ent->cmin == InvalidCommandId || ent->cmin == new_ent->cmin);
2936 Assert(ent->cmax == InvalidCommandId || ent->cmax == new_ent->cmax);
2940 /* update mapping */
2941 new_ent->cmin = ent->cmin;
2942 new_ent->cmax = ent->cmax;
2943 new_ent->combocid = ent->combocid;
2950 * Check whether the TransactionOId 'xid' is in the pre-sorted array 'xip'.
2953 TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num)
2955 return bsearch(&xid, xip, num,
2956 sizeof(TransactionId), xidComparator) != NULL;
2960 * qsort() comparator for sorting RewriteMappingFiles in LSN order.
2963 file_sort_by_lsn(const void *a_p, const void *b_p)
2965 RewriteMappingFile *a = *(RewriteMappingFile **) a_p;
2966 RewriteMappingFile *b = *(RewriteMappingFile **) b_p;
2968 if (a->lsn < b->lsn)
2970 else if (a->lsn > b->lsn)
2976 * Apply any existing logical remapping files if there are any targeted at our
2977 * transaction for relid.
2980 UpdateLogicalMappings(HTAB *tuplecid_data, Oid relid, Snapshot snapshot)
2983 struct dirent *mapping_de;
2986 RewriteMappingFile **files_a;
2988 Oid dboid = IsSharedRelation(relid) ? InvalidOid : MyDatabaseId;
2990 mapping_dir = AllocateDir("pg_logical/mappings");
2991 while ((mapping_de = ReadDir(mapping_dir, "pg_logical/mappings")) != NULL)
2995 TransactionId f_mapped_xid;
2996 TransactionId f_create_xid;
3000 RewriteMappingFile *f;
3002 if (strcmp(mapping_de->d_name, ".") == 0 ||
3003 strcmp(mapping_de->d_name, "..") == 0)
3006 /* Ignore files that aren't ours */
3007 if (strncmp(mapping_de->d_name, "map-", 4) != 0)
3010 if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
3011 &f_dboid, &f_relid, &f_hi, &f_lo,
3012 &f_mapped_xid, &f_create_xid) != 6)
3013 elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
3015 f_lsn = ((uint64) f_hi) << 32 | f_lo;
3017 /* mapping for another database */
3018 if (f_dboid != dboid)
3021 /* mapping for another relation */
3022 if (f_relid != relid)
3025 /* did the creating transaction abort? */
3026 if (!TransactionIdDidCommit(f_create_xid))
3029 /* not for our transaction */
3030 if (!TransactionIdInArray(f_mapped_xid, snapshot->subxip, snapshot->subxcnt))
3033 /* ok, relevant, queue for apply */
3034 f = palloc(sizeof(RewriteMappingFile));
3036 strcpy(f->fname, mapping_de->d_name);
3037 files = lappend(files, f);
3039 FreeDir(mapping_dir);
3041 /* build array we can easily sort */
3042 files_a = palloc(list_length(files) * sizeof(RewriteMappingFile *));
3044 foreach(file, files)
3046 files_a[off++] = lfirst(file);
3049 /* sort files so we apply them in LSN order */
3050 qsort(files_a, list_length(files), sizeof(RewriteMappingFile *),
3053 for (off = 0; off < list_length(files); off++)
3055 RewriteMappingFile *f = files_a[off];
3057 elog(DEBUG1, "applying mapping: \"%s\" in %u", f->fname,
3058 snapshot->subxip[0]);
3059 ApplyLogicalMappingFile(tuplecid_data, relid, f->fname);
3065 * Lookup cmin/cmax of a tuple, during logical decoding where we can't rely on
3069 ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data,
3071 HeapTuple htup, Buffer buffer,
3072 CommandId *cmin, CommandId *cmax)
3074 ReorderBufferTupleCidKey key;
3075 ReorderBufferTupleCidEnt *ent;
3077 BlockNumber blockno;
3078 bool updated_mapping = false;
3080 /* be careful about padding */
3081 memset(&key, 0, sizeof(key));
3083 Assert(!BufferIsLocal(buffer));
3086 * get relfilenode from the buffer, no convenient way to access it other
3089 BufferGetTag(buffer, &key.relnode, &forkno, &blockno);
3091 /* tuples can only be in the main fork */
3092 Assert(forkno == MAIN_FORKNUM);
3093 Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self));
3095 ItemPointerCopy(&htup->t_self,
3099 ent = (ReorderBufferTupleCidEnt *)
3100 hash_search(tuplecid_data,
3106 * failed to find a mapping, check whether the table was rewritten and
3107 * apply mapping if so, but only do that once - there can be no new
3108 * mappings while we are in here since we have to hold a lock on the
3111 if (ent == NULL && !updated_mapping)
3113 UpdateLogicalMappings(tuplecid_data, htup->t_tableOid, snapshot);
3114 /* now check but don't update for a mapping again */
3115 updated_mapping = true;
3118 else if (ent == NULL)