1 /*-------------------------------------------------------------------------
4 * PostgreSQL logical replay/reorder buffer management
7 * Copyright (c) 2012-2018, 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
47 * ReorderBuffer uses two special memory context types - SlabContext for
48 * allocations of fixed-length structures (changes and transactions), and
49 * GenerationContext for the variable-length transaction data (allocated
50 * and freed in groups with similar lifespan).
52 * -------------------------------------------------------------------------
59 #include "access/rewriteheap.h"
60 #include "access/transam.h"
61 #include "access/tuptoaster.h"
62 #include "access/xact.h"
63 #include "access/xlog_internal.h"
64 #include "catalog/catalog.h"
65 #include "lib/binaryheap.h"
66 #include "miscadmin.h"
68 #include "replication/logical.h"
69 #include "replication/reorderbuffer.h"
70 #include "replication/slot.h"
71 #include "replication/snapbuild.h" /* just for SnapBuildSnapDecRefcount */
72 #include "storage/bufmgr.h"
73 #include "storage/fd.h"
74 #include "storage/sinval.h"
75 #include "utils/builtins.h"
76 #include "utils/combocid.h"
77 #include "utils/memdebug.h"
78 #include "utils/memutils.h"
79 #include "utils/rel.h"
80 #include "utils/relfilenodemap.h"
81 #include "utils/tqual.h"
84 /* entry for a hash table we use to map from xid to our transaction state */
85 typedef struct ReorderBufferTXNByIdEnt
88 ReorderBufferTXN *txn;
89 } ReorderBufferTXNByIdEnt;
91 /* data structures for (relfilenode, ctid) => (cmin, cmax) mapping */
92 typedef struct ReorderBufferTupleCidKey
96 } ReorderBufferTupleCidKey;
98 typedef struct ReorderBufferTupleCidEnt
100 ReorderBufferTupleCidKey key;
103 CommandId combocid; /* just for debugging */
104 } ReorderBufferTupleCidEnt;
106 /* k-way in-order change iteration support structures */
107 typedef struct ReorderBufferIterTXNEntry
110 ReorderBufferChange *change;
111 ReorderBufferTXN *txn;
114 } ReorderBufferIterTXNEntry;
116 typedef struct ReorderBufferIterTXNState
120 dlist_head old_change;
121 ReorderBufferIterTXNEntry entries[FLEXIBLE_ARRAY_MEMBER];
122 } ReorderBufferIterTXNState;
124 /* toast datastructures */
125 typedef struct ReorderBufferToastEnt
127 Oid chunk_id; /* toast_table.chunk_id */
128 int32 last_chunk_seq; /* toast_table.chunk_seq of the last chunk we
130 Size num_chunks; /* number of chunks we've already seen */
131 Size size; /* combined size of chunks seen */
132 dlist_head chunks; /* linked list of chunks */
133 struct varlena *reconstructed; /* reconstructed varlena now pointed to in
135 } ReorderBufferToastEnt;
137 /* Disk serialization support datastructures */
138 typedef struct ReorderBufferDiskChange
141 ReorderBufferChange change;
143 } ReorderBufferDiskChange;
146 * Maximum number of changes kept in memory, per transaction. After that,
147 * changes are spooled to disk.
149 * The current value should be sufficient to decode the entire transaction
150 * without hitting disk in OLTP workloads, while starting to spool to disk in
151 * other workloads reasonably fast.
153 * At some point in the future it probably makes sense to have a more elaborate
154 * resource management here, but it's not entirely clear what that would look
157 static const Size max_changes_in_memory = 4096;
159 /* ---------------------------------------
160 * primary reorderbuffer support routines
161 * ---------------------------------------
163 static ReorderBufferTXN *ReorderBufferGetTXN(ReorderBuffer *rb);
164 static void ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
165 static ReorderBufferTXN *ReorderBufferTXNByXid(ReorderBuffer *rb,
166 TransactionId xid, bool create, bool *is_new,
167 XLogRecPtr lsn, bool create_as_top);
169 static void AssertTXNLsnOrder(ReorderBuffer *rb);
171 /* ---------------------------------------
172 * support functions for lsn-order iterating over the ->changes of a
173 * transaction and its subtransactions
175 * used for iteration over the k-way heap merge of a transaction and its
177 * ---------------------------------------
179 static ReorderBufferIterTXNState *ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn);
180 static ReorderBufferChange *ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state);
181 static void ReorderBufferIterTXNFinish(ReorderBuffer *rb,
182 ReorderBufferIterTXNState *state);
183 static void ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn);
186 * ---------------------------------------
187 * Disk serialization support functions
188 * ---------------------------------------
190 static void ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
191 static void ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
192 static void ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
193 int fd, ReorderBufferChange *change);
194 static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
195 int *fd, XLogSegNo *segno);
196 static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
198 static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn);
200 static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap);
201 static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
202 ReorderBufferTXN *txn, CommandId cid);
204 /* ---------------------------------------
205 * toast reassembly support
206 * ---------------------------------------
208 static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn);
209 static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn);
210 static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
211 Relation relation, ReorderBufferChange *change);
212 static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
213 Relation relation, ReorderBufferChange *change);
217 * Allocate a new ReorderBuffer
220 ReorderBufferAllocate(void)
222 ReorderBuffer *buffer;
224 MemoryContext new_ctx;
226 /* allocate memory in own context, to have better accountability */
227 new_ctx = AllocSetContextCreate(CurrentMemoryContext,
229 ALLOCSET_DEFAULT_SIZES);
232 (ReorderBuffer *) MemoryContextAlloc(new_ctx, sizeof(ReorderBuffer));
234 memset(&hash_ctl, 0, sizeof(hash_ctl));
236 buffer->context = new_ctx;
238 buffer->change_context = SlabContextCreate(new_ctx,
241 SLAB_DEFAULT_BLOCK_SIZE,
242 sizeof(ReorderBufferChange));
244 buffer->txn_context = SlabContextCreate(new_ctx,
247 SLAB_DEFAULT_BLOCK_SIZE,
248 sizeof(ReorderBufferTXN));
250 buffer->tup_context = GenerationContextCreate(new_ctx,
253 SLAB_LARGE_BLOCK_SIZE);
255 hash_ctl.keysize = sizeof(TransactionId);
256 hash_ctl.entrysize = sizeof(ReorderBufferTXNByIdEnt);
257 hash_ctl.hcxt = buffer->context;
259 buffer->by_txn = hash_create("ReorderBufferByXid", 1000, &hash_ctl,
260 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
262 buffer->by_txn_last_xid = InvalidTransactionId;
263 buffer->by_txn_last_txn = NULL;
265 buffer->outbuf = NULL;
266 buffer->outbufsize = 0;
268 buffer->current_restart_decoding_lsn = InvalidXLogRecPtr;
270 dlist_init(&buffer->toplevel_by_lsn);
276 * Free a ReorderBuffer
279 ReorderBufferFree(ReorderBuffer *rb)
281 MemoryContext context = rb->context;
284 * We free separately allocated data by entirely scrapping reorderbuffer's
287 MemoryContextDelete(context);
291 * Get an unused, possibly preallocated, ReorderBufferTXN.
293 static ReorderBufferTXN *
294 ReorderBufferGetTXN(ReorderBuffer *rb)
296 ReorderBufferTXN *txn;
298 txn = (ReorderBufferTXN *)
299 MemoryContextAlloc(rb->txn_context, sizeof(ReorderBufferTXN));
301 memset(txn, 0, sizeof(ReorderBufferTXN));
303 dlist_init(&txn->changes);
304 dlist_init(&txn->tuplecids);
305 dlist_init(&txn->subtxns);
311 * Free a ReorderBufferTXN.
313 * Deallocation might be delayed for efficiency purposes, for details check
314 * the comments above max_cached_changes's definition.
317 ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
319 /* clean the lookup cache if we were cached (quite likely) */
320 if (rb->by_txn_last_xid == txn->xid)
322 rb->by_txn_last_xid = InvalidTransactionId;
323 rb->by_txn_last_txn = NULL;
326 /* free data that's contained */
328 if (txn->tuplecid_hash != NULL)
330 hash_destroy(txn->tuplecid_hash);
331 txn->tuplecid_hash = NULL;
334 if (txn->invalidations)
336 pfree(txn->invalidations);
337 txn->invalidations = NULL;
344 * Get an unused, possibly preallocated, ReorderBufferChange.
346 ReorderBufferChange *
347 ReorderBufferGetChange(ReorderBuffer *rb)
349 ReorderBufferChange *change;
351 change = (ReorderBufferChange *)
352 MemoryContextAlloc(rb->change_context, sizeof(ReorderBufferChange));
354 memset(change, 0, sizeof(ReorderBufferChange));
359 * Free an ReorderBufferChange.
361 * Deallocation might be delayed for efficiency purposes, for details check
362 * the comments above max_cached_changes's definition.
365 ReorderBufferReturnChange(ReorderBuffer *rb, ReorderBufferChange *change)
367 /* free contained data */
368 switch (change->action)
370 case REORDER_BUFFER_CHANGE_INSERT:
371 case REORDER_BUFFER_CHANGE_UPDATE:
372 case REORDER_BUFFER_CHANGE_DELETE:
373 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
374 if (change->data.tp.newtuple)
376 ReorderBufferReturnTupleBuf(rb, change->data.tp.newtuple);
377 change->data.tp.newtuple = NULL;
380 if (change->data.tp.oldtuple)
382 ReorderBufferReturnTupleBuf(rb, change->data.tp.oldtuple);
383 change->data.tp.oldtuple = NULL;
386 case REORDER_BUFFER_CHANGE_MESSAGE:
387 if (change->data.msg.prefix != NULL)
388 pfree(change->data.msg.prefix);
389 change->data.msg.prefix = NULL;
390 if (change->data.msg.message != NULL)
391 pfree(change->data.msg.message);
392 change->data.msg.message = NULL;
394 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
395 if (change->data.snapshot)
397 ReorderBufferFreeSnap(rb, change->data.snapshot);
398 change->data.snapshot = NULL;
401 /* no data in addition to the struct itself */
402 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
403 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
404 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
412 * Get an unused, possibly preallocated, ReorderBufferTupleBuf fitting at
413 * least a tuple of size tuple_len (excluding header overhead).
415 ReorderBufferTupleBuf *
416 ReorderBufferGetTupleBuf(ReorderBuffer *rb, Size tuple_len)
418 ReorderBufferTupleBuf *tuple;
421 alloc_len = tuple_len + SizeofHeapTupleHeader;
423 tuple = (ReorderBufferTupleBuf *)
424 MemoryContextAlloc(rb->tup_context,
425 sizeof(ReorderBufferTupleBuf) +
426 MAXIMUM_ALIGNOF + alloc_len);
427 tuple->alloc_tuple_size = alloc_len;
428 tuple->tuple.t_data = ReorderBufferTupleBufData(tuple);
434 * Free an ReorderBufferTupleBuf.
436 * Deallocation might be delayed for efficiency purposes, for details check
437 * the comments above max_cached_changes's definition.
440 ReorderBufferReturnTupleBuf(ReorderBuffer *rb, ReorderBufferTupleBuf *tuple)
446 * Return the ReorderBufferTXN from the given buffer, specified by Xid.
447 * If create is true, and a transaction doesn't already exist, create it
448 * (with the given LSN, and as top transaction if that's specified);
449 * when this happens, is_new is set to true.
451 static ReorderBufferTXN *
452 ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create,
453 bool *is_new, XLogRecPtr lsn, bool create_as_top)
455 ReorderBufferTXN *txn;
456 ReorderBufferTXNByIdEnt *ent;
459 Assert(TransactionIdIsValid(xid));
460 Assert(!create || lsn != InvalidXLogRecPtr);
463 * Check the one-entry lookup cache first
465 if (TransactionIdIsValid(rb->by_txn_last_xid) &&
466 rb->by_txn_last_xid == xid)
468 txn = rb->by_txn_last_txn;
472 /* found it, and it's valid */
479 * cached as non-existent, and asked not to create? Then nothing else
484 /* otherwise fall through to create it */
488 * If the cache wasn't hit or it yielded an "does-not-exist" and we want
489 * to create an entry.
492 /* search the lookup table */
493 ent = (ReorderBufferTXNByIdEnt *)
494 hash_search(rb->by_txn,
496 create ? HASH_ENTER : HASH_FIND,
502 /* initialize the new entry, if creation was requested */
505 ent->txn = ReorderBufferGetTXN(rb);
508 txn->first_lsn = lsn;
509 txn->restart_decoding_lsn = rb->current_restart_decoding_lsn;
513 dlist_push_tail(&rb->toplevel_by_lsn, &txn->node);
514 AssertTXNLsnOrder(rb);
518 txn = NULL; /* not found and not asked to create */
521 rb->by_txn_last_xid = xid;
522 rb->by_txn_last_txn = txn;
527 Assert(!create || txn != NULL);
532 * Queue a change into a transaction so it can be replayed upon commit.
535 ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
536 ReorderBufferChange *change)
538 ReorderBufferTXN *txn;
540 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
543 Assert(InvalidXLogRecPtr != lsn);
544 dlist_push_tail(&txn->changes, &change->node);
548 ReorderBufferCheckSerializeTXN(rb, txn);
552 * Queue message into a transaction so it can be processed upon commit.
555 ReorderBufferQueueMessage(ReorderBuffer *rb, TransactionId xid,
556 Snapshot snapshot, XLogRecPtr lsn,
557 bool transactional, const char *prefix,
558 Size message_size, const char *message)
562 MemoryContext oldcontext;
563 ReorderBufferChange *change;
565 Assert(xid != InvalidTransactionId);
567 oldcontext = MemoryContextSwitchTo(rb->context);
569 change = ReorderBufferGetChange(rb);
570 change->action = REORDER_BUFFER_CHANGE_MESSAGE;
571 change->data.msg.prefix = pstrdup(prefix);
572 change->data.msg.message_size = message_size;
573 change->data.msg.message = palloc(message_size);
574 memcpy(change->data.msg.message, message, message_size);
576 ReorderBufferQueueChange(rb, xid, lsn, change);
578 MemoryContextSwitchTo(oldcontext);
582 ReorderBufferTXN *txn = NULL;
583 volatile Snapshot snapshot_now = snapshot;
585 if (xid != InvalidTransactionId)
586 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
588 /* setup snapshot to allow catalog access */
589 SetupHistoricSnapshot(snapshot_now, NULL);
592 rb->message(rb, txn, lsn, false, prefix, message_size, message);
594 TeardownHistoricSnapshot(false);
598 TeardownHistoricSnapshot(true);
607 AssertTXNLsnOrder(ReorderBuffer *rb)
609 #ifdef USE_ASSERT_CHECKING
611 XLogRecPtr prev_first_lsn = InvalidXLogRecPtr;
613 dlist_foreach(iter, &rb->toplevel_by_lsn)
615 ReorderBufferTXN *cur_txn;
617 cur_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
618 Assert(cur_txn->first_lsn != InvalidXLogRecPtr);
620 if (cur_txn->end_lsn != InvalidXLogRecPtr)
621 Assert(cur_txn->first_lsn <= cur_txn->end_lsn);
623 if (prev_first_lsn != InvalidXLogRecPtr)
624 Assert(prev_first_lsn < cur_txn->first_lsn);
626 Assert(!cur_txn->is_known_as_subxact);
627 prev_first_lsn = cur_txn->first_lsn;
633 ReorderBufferGetOldestTXN(ReorderBuffer *rb)
635 ReorderBufferTXN *txn;
637 if (dlist_is_empty(&rb->toplevel_by_lsn))
640 AssertTXNLsnOrder(rb);
642 txn = dlist_head_element(ReorderBufferTXN, node, &rb->toplevel_by_lsn);
644 Assert(!txn->is_known_as_subxact);
645 Assert(txn->first_lsn != InvalidXLogRecPtr);
650 ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr)
652 rb->current_restart_decoding_lsn = ptr;
656 ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid,
657 TransactionId subxid, XLogRecPtr lsn)
659 ReorderBufferTXN *txn;
660 ReorderBufferTXN *subtxn;
664 txn = ReorderBufferTXNByXid(rb, xid, true, &new_top, lsn, true);
665 subtxn = ReorderBufferTXNByXid(rb, subxid, true, &new_sub, lsn, false);
670 * we assign subtransactions to top level transaction even if we don't
671 * have data for it yet, assignment records frequently reference xids
672 * that have not yet produced any records. Knowing those aren't top
673 * level xids allows us to make processing cheaper in some places.
675 dlist_push_tail(&txn->subtxns, &subtxn->node);
678 else if (!subtxn->is_known_as_subxact)
680 subtxn->is_known_as_subxact = true;
681 Assert(subtxn->nsubtxns == 0);
683 /* remove from lsn order list of top-level transactions */
684 dlist_delete(&subtxn->node);
686 /* add to toplevel transaction */
687 dlist_push_tail(&txn->subtxns, &subtxn->node);
692 elog(ERROR, "existing subxact assigned to unknown toplevel xact");
697 * Associate a subtransaction with its toplevel transaction at commit
698 * time. There may be no further changes added after this.
701 ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
702 TransactionId subxid, XLogRecPtr commit_lsn,
705 ReorderBufferTXN *txn;
706 ReorderBufferTXN *subtxn;
708 subtxn = ReorderBufferTXNByXid(rb, subxid, false, NULL,
709 InvalidXLogRecPtr, false);
712 * No need to do anything if that subtxn didn't contain any changes
717 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, commit_lsn, true);
720 elog(ERROR, "subxact logged without previous toplevel record");
723 * Pass our base snapshot to the parent transaction if it doesn't have
724 * one, or ours is older. That can happen if there are no changes in the
725 * toplevel transaction but in one of the child transactions. This allows
726 * the parent to simply use its base snapshot initially.
728 if (subtxn->base_snapshot != NULL &&
729 (txn->base_snapshot == NULL ||
730 txn->base_snapshot_lsn > subtxn->base_snapshot_lsn))
732 txn->base_snapshot = subtxn->base_snapshot;
733 txn->base_snapshot_lsn = subtxn->base_snapshot_lsn;
734 subtxn->base_snapshot = NULL;
735 subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
738 subtxn->final_lsn = commit_lsn;
739 subtxn->end_lsn = end_lsn;
741 if (!subtxn->is_known_as_subxact)
743 subtxn->is_known_as_subxact = true;
744 Assert(subtxn->nsubtxns == 0);
746 /* remove from lsn order list of top-level transactions */
747 dlist_delete(&subtxn->node);
749 /* add to subtransaction list */
750 dlist_push_tail(&txn->subtxns, &subtxn->node);
757 * Support for efficiently iterating over a transaction's and its
758 * subtransactions' changes.
760 * We do by doing a k-way merge between transactions/subtransactions. For that
761 * we model the current heads of the different transactions as a binary heap
762 * so we easily know which (sub-)transaction has the change with the smallest
765 * We assume the changes in individual transactions are already sorted by LSN.
769 * Binary heap comparison function.
772 ReorderBufferIterCompare(Datum a, Datum b, void *arg)
774 ReorderBufferIterTXNState *state = (ReorderBufferIterTXNState *) arg;
775 XLogRecPtr pos_a = state->entries[DatumGetInt32(a)].lsn;
776 XLogRecPtr pos_b = state->entries[DatumGetInt32(b)].lsn;
780 else if (pos_a == pos_b)
786 * Allocate & initialize an iterator which iterates in lsn order over a
787 * transaction and all its subtransactions.
789 static ReorderBufferIterTXNState *
790 ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn)
793 ReorderBufferIterTXNState *state;
794 dlist_iter cur_txn_i;
798 * Calculate the size of our heap: one element for every transaction that
799 * contains changes. (Besides the transactions already in the reorder
800 * buffer, we count the one we were directly passed.)
802 if (txn->nentries > 0)
805 dlist_foreach(cur_txn_i, &txn->subtxns)
807 ReorderBufferTXN *cur_txn;
809 cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
811 if (cur_txn->nentries > 0)
816 * TODO: Consider adding fastpath for the rather common nr_txns=1 case, no
817 * need to allocate/build a heap then.
820 /* allocate iteration state */
821 state = (ReorderBufferIterTXNState *)
822 MemoryContextAllocZero(rb->context,
823 sizeof(ReorderBufferIterTXNState) +
824 sizeof(ReorderBufferIterTXNEntry) * nr_txns);
826 state->nr_txns = nr_txns;
827 dlist_init(&state->old_change);
829 for (off = 0; off < state->nr_txns; off++)
831 state->entries[off].fd = -1;
832 state->entries[off].segno = 0;
836 state->heap = binaryheap_allocate(state->nr_txns,
837 ReorderBufferIterCompare,
841 * Now insert items into the binary heap, in an unordered fashion. (We
842 * will run a heap assembly step at the end; this is more efficient.)
847 /* add toplevel transaction if it contains changes */
848 if (txn->nentries > 0)
850 ReorderBufferChange *cur_change;
854 /* serialize remaining changes */
855 ReorderBufferSerializeTXN(rb, txn);
856 ReorderBufferRestoreChanges(rb, txn, &state->entries[off].fd,
857 &state->entries[off].segno);
860 cur_change = dlist_head_element(ReorderBufferChange, node,
863 state->entries[off].lsn = cur_change->lsn;
864 state->entries[off].change = cur_change;
865 state->entries[off].txn = txn;
867 binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
870 /* add subtransactions if they contain changes */
871 dlist_foreach(cur_txn_i, &txn->subtxns)
873 ReorderBufferTXN *cur_txn;
875 cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
877 if (cur_txn->nentries > 0)
879 ReorderBufferChange *cur_change;
881 if (cur_txn->serialized)
883 /* serialize remaining changes */
884 ReorderBufferSerializeTXN(rb, cur_txn);
885 ReorderBufferRestoreChanges(rb, cur_txn,
886 &state->entries[off].fd,
887 &state->entries[off].segno);
889 cur_change = dlist_head_element(ReorderBufferChange, node,
892 state->entries[off].lsn = cur_change->lsn;
893 state->entries[off].change = cur_change;
894 state->entries[off].txn = cur_txn;
896 binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
900 /* assemble a valid binary heap */
901 binaryheap_build(state->heap);
907 * Return the next change when iterating over a transaction and its
910 * Returns NULL when no further changes exist.
912 static ReorderBufferChange *
913 ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state)
915 ReorderBufferChange *change;
916 ReorderBufferIterTXNEntry *entry;
919 /* nothing there anymore */
920 if (state->heap->bh_size == 0)
923 off = DatumGetInt32(binaryheap_first(state->heap));
924 entry = &state->entries[off];
926 /* free memory we might have "leaked" in the previous *Next call */
927 if (!dlist_is_empty(&state->old_change))
929 change = dlist_container(ReorderBufferChange, node,
930 dlist_pop_head_node(&state->old_change));
931 ReorderBufferReturnChange(rb, change);
932 Assert(dlist_is_empty(&state->old_change));
935 change = entry->change;
938 * update heap with information about which transaction has the next
939 * relevant change in LSN order
942 /* there are in-memory changes */
943 if (dlist_has_next(&entry->txn->changes, &entry->change->node))
945 dlist_node *next = dlist_next_node(&entry->txn->changes, &change->node);
946 ReorderBufferChange *next_change =
947 dlist_container(ReorderBufferChange, node, next);
949 /* txn stays the same */
950 state->entries[off].lsn = next_change->lsn;
951 state->entries[off].change = next_change;
953 binaryheap_replace_first(state->heap, Int32GetDatum(off));
957 /* try to load changes from disk */
958 if (entry->txn->nentries != entry->txn->nentries_mem)
961 * Ugly: restoring changes will reuse *Change records, thus delete the
962 * current one from the per-tx list and only free in the next call.
964 dlist_delete(&change->node);
965 dlist_push_tail(&state->old_change, &change->node);
967 if (ReorderBufferRestoreChanges(rb, entry->txn, &entry->fd,
968 &state->entries[off].segno))
970 /* successfully restored changes from disk */
971 ReorderBufferChange *next_change =
972 dlist_head_element(ReorderBufferChange, node,
973 &entry->txn->changes);
975 elog(DEBUG2, "restored %u/%u changes from disk",
976 (uint32) entry->txn->nentries_mem,
977 (uint32) entry->txn->nentries);
979 Assert(entry->txn->nentries_mem);
980 /* txn stays the same */
981 state->entries[off].lsn = next_change->lsn;
982 state->entries[off].change = next_change;
983 binaryheap_replace_first(state->heap, Int32GetDatum(off));
989 /* ok, no changes there anymore, remove */
990 binaryheap_remove_first(state->heap);
996 * Deallocate the iterator
999 ReorderBufferIterTXNFinish(ReorderBuffer *rb,
1000 ReorderBufferIterTXNState *state)
1004 for (off = 0; off < state->nr_txns; off++)
1006 if (state->entries[off].fd != -1)
1007 CloseTransientFile(state->entries[off].fd);
1010 /* free memory we might have "leaked" in the last *Next call */
1011 if (!dlist_is_empty(&state->old_change))
1013 ReorderBufferChange *change;
1015 change = dlist_container(ReorderBufferChange, node,
1016 dlist_pop_head_node(&state->old_change));
1017 ReorderBufferReturnChange(rb, change);
1018 Assert(dlist_is_empty(&state->old_change));
1021 binaryheap_free(state->heap);
1026 * Cleanup the contents of a transaction, usually after the transaction
1027 * committed or aborted.
1030 ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1033 dlist_mutable_iter iter;
1035 /* cleanup subtransactions & their changes */
1036 dlist_foreach_modify(iter, &txn->subtxns)
1038 ReorderBufferTXN *subtxn;
1040 subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
1043 * Subtransactions are always associated to the toplevel TXN, even if
1044 * they originally were happening inside another subtxn, so we won't
1045 * ever recurse more than one level deep here.
1047 Assert(subtxn->is_known_as_subxact);
1048 Assert(subtxn->nsubtxns == 0);
1050 ReorderBufferCleanupTXN(rb, subtxn);
1053 /* cleanup changes in the toplevel txn */
1054 dlist_foreach_modify(iter, &txn->changes)
1056 ReorderBufferChange *change;
1058 change = dlist_container(ReorderBufferChange, node, iter.cur);
1060 ReorderBufferReturnChange(rb, change);
1064 * Cleanup the tuplecids we stored for decoding catalog snapshot access.
1065 * They are always stored in the toplevel transaction.
1067 dlist_foreach_modify(iter, &txn->tuplecids)
1069 ReorderBufferChange *change;
1071 change = dlist_container(ReorderBufferChange, node, iter.cur);
1072 Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1073 ReorderBufferReturnChange(rb, change);
1076 if (txn->base_snapshot != NULL)
1078 SnapBuildSnapDecRefcount(txn->base_snapshot);
1079 txn->base_snapshot = NULL;
1080 txn->base_snapshot_lsn = InvalidXLogRecPtr;
1084 * Remove TXN from its containing list.
1086 * Note: if txn->is_known_as_subxact, we are deleting the TXN from its
1087 * parent's list of known subxacts; this leaves the parent's nsubxacts
1088 * count too high, but we don't care. Otherwise, we are deleting the TXN
1089 * from the LSN-ordered list of toplevel TXNs.
1091 dlist_delete(&txn->node);
1093 /* now remove reference from buffer */
1094 hash_search(rb->by_txn,
1100 /* remove entries spilled to disk */
1101 if (txn->serialized)
1102 ReorderBufferRestoreCleanup(rb, txn);
1105 ReorderBufferReturnTXN(rb, txn);
1109 * Build a hash with a (relfilenode, ctid) -> (cmin, cmax) mapping for use by
1110 * tqual.c's HeapTupleSatisfiesHistoricMVCC.
1113 ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
1118 if (!txn->has_catalog_changes || dlist_is_empty(&txn->tuplecids))
1121 memset(&hash_ctl, 0, sizeof(hash_ctl));
1123 hash_ctl.keysize = sizeof(ReorderBufferTupleCidKey);
1124 hash_ctl.entrysize = sizeof(ReorderBufferTupleCidEnt);
1125 hash_ctl.hcxt = rb->context;
1128 * create the hash with the exact number of to-be-stored tuplecids from
1131 txn->tuplecid_hash =
1132 hash_create("ReorderBufferTupleCid", txn->ntuplecids, &hash_ctl,
1133 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
1135 dlist_foreach(iter, &txn->tuplecids)
1137 ReorderBufferTupleCidKey key;
1138 ReorderBufferTupleCidEnt *ent;
1140 ReorderBufferChange *change;
1142 change = dlist_container(ReorderBufferChange, node, iter.cur);
1144 Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1146 /* be careful about padding */
1147 memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
1149 key.relnode = change->data.tuplecid.node;
1151 ItemPointerCopy(&change->data.tuplecid.tid,
1154 ent = (ReorderBufferTupleCidEnt *)
1155 hash_search(txn->tuplecid_hash,
1157 HASH_ENTER | HASH_FIND,
1161 ent->cmin = change->data.tuplecid.cmin;
1162 ent->cmax = change->data.tuplecid.cmax;
1163 ent->combocid = change->data.tuplecid.combocid;
1167 Assert(ent->cmin == change->data.tuplecid.cmin);
1168 Assert(ent->cmax == InvalidCommandId ||
1169 ent->cmax == change->data.tuplecid.cmax);
1172 * if the tuple got valid in this transaction and now got deleted
1173 * we already have a valid cmin stored. The cmax will be
1174 * InvalidCommandId though.
1176 ent->cmax = change->data.tuplecid.cmax;
1182 * Copy a provided snapshot so we can modify it privately. This is needed so
1183 * that catalog modifying transactions can look into intermediate catalog
1187 ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
1188 ReorderBufferTXN *txn, CommandId cid)
1195 size = sizeof(SnapshotData) +
1196 sizeof(TransactionId) * orig_snap->xcnt +
1197 sizeof(TransactionId) * (txn->nsubtxns + 1);
1199 snap = MemoryContextAllocZero(rb->context, size);
1200 memcpy(snap, orig_snap, sizeof(SnapshotData));
1202 snap->copied = true;
1203 snap->active_count = 1; /* mark as active so nobody frees it */
1204 snap->regd_count = 0;
1205 snap->xip = (TransactionId *) (snap + 1);
1207 memcpy(snap->xip, orig_snap->xip, sizeof(TransactionId) * snap->xcnt);
1210 * snap->subxip contains all txids that belong to our transaction which we
1211 * need to check via cmin/cmax. That's why we store the toplevel
1212 * transaction in there as well.
1214 snap->subxip = snap->xip + snap->xcnt;
1215 snap->subxip[i++] = txn->xid;
1218 * nsubxcnt isn't decreased when subtransactions abort, so count manually.
1219 * Since it's an upper boundary it is safe to use it for the allocation
1224 dlist_foreach(iter, &txn->subtxns)
1226 ReorderBufferTXN *sub_txn;
1228 sub_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
1229 snap->subxip[i++] = sub_txn->xid;
1233 /* sort so we can bsearch() later */
1234 qsort(snap->subxip, snap->subxcnt, sizeof(TransactionId), xidComparator);
1236 /* store the specified current CommandId */
1243 * Free a previously ReorderBufferCopySnap'ed snapshot
1246 ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap)
1251 SnapBuildSnapDecRefcount(snap);
1255 * Perform the replay of a transaction and it's non-aborted subtransactions.
1257 * Subtransactions previously have to be processed by
1258 * ReorderBufferCommitChild(), even if previously assigned to the toplevel
1259 * transaction with ReorderBufferAssignChild.
1261 * We currently can only decode a transaction's contents in when their commit
1262 * record is read because that's currently the only place where we know about
1263 * cache invalidations. Thus, once a toplevel commit is read, we iterate over
1264 * the top and subtransactions (using a k-way merge) and replay the changes in
1268 ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
1269 XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
1270 TimestampTz commit_time,
1271 RepOriginId origin_id, XLogRecPtr origin_lsn)
1273 ReorderBufferTXN *txn;
1274 volatile Snapshot snapshot_now;
1275 volatile CommandId command_id = FirstCommandId;
1277 ReorderBufferIterTXNState *volatile iterstate = NULL;
1279 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1282 /* unknown transaction, nothing to replay */
1286 txn->final_lsn = commit_lsn;
1287 txn->end_lsn = end_lsn;
1288 txn->commit_time = commit_time;
1289 txn->origin_id = origin_id;
1290 txn->origin_lsn = origin_lsn;
1293 * If this transaction didn't have any real changes in our database, it's
1294 * OK not to have a snapshot. Note that ReorderBufferCommitChild will have
1295 * transferred its snapshot to this transaction if it had one and the
1296 * toplevel tx didn't.
1298 if (txn->base_snapshot == NULL)
1300 Assert(txn->ninvalidations == 0);
1301 ReorderBufferCleanupTXN(rb, txn);
1305 snapshot_now = txn->base_snapshot;
1307 /* build data to be able to lookup the CommandIds of catalog tuples */
1308 ReorderBufferBuildTupleCidHash(rb, txn);
1310 /* setup the initial snapshot */
1311 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1314 * Decoding needs access to syscaches et al., which in turn use
1315 * heavyweight locks and such. Thus we need to have enough state around to
1316 * keep track of those. The easiest way is to simply use a transaction
1317 * internally. That also allows us to easily enforce that nothing writes
1318 * to the database by checking for xid assignments.
1320 * When we're called via the SQL SRF there's already a transaction
1321 * started, so start an explicit subtransaction there.
1323 using_subtxn = IsTransactionOrTransactionBlock();
1327 ReorderBufferChange *change;
1328 ReorderBufferChange *specinsert = NULL;
1331 BeginInternalSubTransaction("replay");
1333 StartTransactionCommand();
1337 iterstate = ReorderBufferIterTXNInit(rb, txn);
1338 while ((change = ReorderBufferIterTXNNext(rb, iterstate)) != NULL)
1340 Relation relation = NULL;
1343 switch (change->action)
1345 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
1348 * Confirmation for speculative insertion arrived. Simply
1349 * use as a normal record. It'll be cleaned up at the end
1350 * of INSERT processing.
1352 Assert(specinsert->data.tp.oldtuple == NULL);
1353 change = specinsert;
1354 change->action = REORDER_BUFFER_CHANGE_INSERT;
1356 /* intentionally fall through */
1357 case REORDER_BUFFER_CHANGE_INSERT:
1358 case REORDER_BUFFER_CHANGE_UPDATE:
1359 case REORDER_BUFFER_CHANGE_DELETE:
1360 Assert(snapshot_now);
1362 reloid = RelidByRelfilenode(change->data.tp.relnode.spcNode,
1363 change->data.tp.relnode.relNode);
1366 * Catalog tuple without data, emitted while catalog was
1367 * in the process of being rewritten.
1369 if (reloid == InvalidOid &&
1370 change->data.tp.newtuple == NULL &&
1371 change->data.tp.oldtuple == NULL)
1373 else if (reloid == InvalidOid)
1374 elog(ERROR, "could not map filenode \"%s\" to relation OID",
1375 relpathperm(change->data.tp.relnode,
1378 relation = RelationIdGetRelation(reloid);
1380 if (relation == NULL)
1381 elog(ERROR, "could not open relation with OID %u (for filenode \"%s\")",
1383 relpathperm(change->data.tp.relnode,
1386 if (!RelationIsLogicallyLogged(relation))
1390 * For now ignore sequence changes entirely. Most of the
1391 * time they don't log changes using records we
1392 * understand, so it doesn't make sense to handle the few
1395 if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
1398 /* user-triggered change */
1399 if (!IsToastRelation(relation))
1401 ReorderBufferToastReplace(rb, txn, relation, change);
1402 rb->apply_change(rb, txn, relation, change);
1405 * Only clear reassembled toast chunks if we're sure
1406 * they're not required anymore. The creator of the
1409 if (change->data.tp.clear_toast_afterwards)
1410 ReorderBufferToastReset(rb, txn);
1412 /* we're not interested in toast deletions */
1413 else if (change->action == REORDER_BUFFER_CHANGE_INSERT)
1416 * Need to reassemble the full toasted Datum in
1417 * memory, to ensure the chunks don't get reused till
1418 * we're done remove it from the list of this
1419 * transaction's changes. Otherwise it will get
1420 * freed/reused while restoring spooled data from
1423 dlist_delete(&change->node);
1424 ReorderBufferToastAppendChunk(rb, txn, relation,
1431 * Either speculative insertion was confirmed, or it was
1432 * unsuccessful and the record isn't needed anymore.
1434 if (specinsert != NULL)
1436 ReorderBufferReturnChange(rb, specinsert);
1440 if (relation != NULL)
1442 RelationClose(relation);
1447 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
1450 * Speculative insertions are dealt with by delaying the
1451 * processing of the insert until the confirmation record
1452 * arrives. For that we simply unlink the record from the
1453 * chain, so it does not get freed/reused while restoring
1454 * spooled data from disk.
1456 * This is safe in the face of concurrent catalog changes
1457 * because the relevant relation can't be changed between
1458 * speculative insertion and confirmation due to
1459 * CheckTableNotInUse() and locking.
1462 /* clear out a pending (and thus failed) speculation */
1463 if (specinsert != NULL)
1465 ReorderBufferReturnChange(rb, specinsert);
1469 /* and memorize the pending insertion */
1470 dlist_delete(&change->node);
1471 specinsert = change;
1474 case REORDER_BUFFER_CHANGE_MESSAGE:
1475 rb->message(rb, txn, change->lsn, true,
1476 change->data.msg.prefix,
1477 change->data.msg.message_size,
1478 change->data.msg.message);
1481 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
1482 /* get rid of the old */
1483 TeardownHistoricSnapshot(false);
1485 if (snapshot_now->copied)
1487 ReorderBufferFreeSnap(rb, snapshot_now);
1489 ReorderBufferCopySnap(rb, change->data.snapshot,
1494 * Restored from disk, need to be careful not to double
1495 * free. We could introduce refcounting for that, but for
1496 * now this seems infrequent enough not to care.
1498 else if (change->data.snapshot->copied)
1501 ReorderBufferCopySnap(rb, change->data.snapshot,
1506 snapshot_now = change->data.snapshot;
1510 /* and continue with the new one */
1511 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1514 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
1515 Assert(change->data.command_id != InvalidCommandId);
1517 if (command_id < change->data.command_id)
1519 command_id = change->data.command_id;
1521 if (!snapshot_now->copied)
1523 /* we don't use the global one anymore */
1524 snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
1528 snapshot_now->curcid = command_id;
1530 TeardownHistoricSnapshot(false);
1531 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1534 * Every time the CommandId is incremented, we could
1535 * see new catalog contents, so execute all
1538 ReorderBufferExecuteInvalidations(rb, txn);
1543 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
1544 elog(ERROR, "tuplecid value in changequeue");
1550 * There's a speculative insertion remaining, just clean in up, it
1551 * can't have been successful, otherwise we'd gotten a confirmation
1556 ReorderBufferReturnChange(rb, specinsert);
1560 /* clean up the iterator */
1561 ReorderBufferIterTXNFinish(rb, iterstate);
1564 /* call commit callback */
1565 rb->commit(rb, txn, commit_lsn);
1567 /* this is just a sanity check against bad output plugin behaviour */
1568 if (GetCurrentTransactionIdIfAny() != InvalidTransactionId)
1569 elog(ERROR, "output plugin used XID %u",
1570 GetCurrentTransactionId());
1573 TeardownHistoricSnapshot(false);
1576 * Aborting the current (sub-)transaction as a whole has the right
1577 * semantics. We want all locks acquired in here to be released, not
1578 * reassigned to the parent and we do not want any database access
1579 * have persistent effects.
1581 AbortCurrentTransaction();
1583 /* make sure there's no cache pollution */
1584 ReorderBufferExecuteInvalidations(rb, txn);
1587 RollbackAndReleaseCurrentSubTransaction();
1589 if (snapshot_now->copied)
1590 ReorderBufferFreeSnap(rb, snapshot_now);
1592 /* remove potential on-disk data, and deallocate */
1593 ReorderBufferCleanupTXN(rb, txn);
1597 /* TODO: Encapsulate cleanup from the PG_TRY and PG_CATCH blocks */
1599 ReorderBufferIterTXNFinish(rb, iterstate);
1601 TeardownHistoricSnapshot(true);
1604 * Force cache invalidation to happen outside of a valid transaction
1605 * to prevent catalog access as we just caught an error.
1607 AbortCurrentTransaction();
1609 /* make sure there's no cache pollution */
1610 ReorderBufferExecuteInvalidations(rb, txn);
1613 RollbackAndReleaseCurrentSubTransaction();
1615 if (snapshot_now->copied)
1616 ReorderBufferFreeSnap(rb, snapshot_now);
1618 /* remove potential on-disk data, and deallocate */
1619 ReorderBufferCleanupTXN(rb, txn);
1627 * Abort a transaction that possibly has previous changes. Needs to be first
1628 * called for subtransactions and then for the toplevel xid.
1630 * NB: Transactions handled here have to have actively aborted (i.e. have
1631 * produced an abort record). Implicitly aborted transactions are handled via
1632 * ReorderBufferAbortOld(); transactions we're just not interested in, but
1633 * which have committed are handled in ReorderBufferForget().
1635 * This function purges this transaction and its contents from memory and
1639 ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1641 ReorderBufferTXN *txn;
1643 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1646 /* unknown, nothing to remove */
1651 txn->final_lsn = lsn;
1653 /* remove potential on-disk data, and deallocate */
1654 ReorderBufferCleanupTXN(rb, txn);
1658 * Abort all transactions that aren't actually running anymore because the
1661 * NB: These really have to be transactions that have aborted due to a server
1662 * crash/immediate restart, as we don't deal with invalidations here.
1665 ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid)
1667 dlist_mutable_iter it;
1670 * Iterate through all (potential) toplevel TXNs and abort all that are
1671 * older than what possibly can be running. Once we've found the first
1672 * that is alive we stop, there might be some that acquired an xid earlier
1673 * but started writing later, but it's unlikely and they will be cleaned
1674 * up in a later call to this function.
1676 dlist_foreach_modify(it, &rb->toplevel_by_lsn)
1678 ReorderBufferTXN *txn;
1680 txn = dlist_container(ReorderBufferTXN, node, it.cur);
1682 if (TransactionIdPrecedes(txn->xid, oldestRunningXid))
1685 * We set final_lsn on a transaction when we decode its commit or
1686 * abort record, but we never see those records for crashed
1687 * transactions. To ensure cleanup of these transactions, set
1688 * final_lsn to that of their last change; this causes
1689 * ReorderBufferRestoreCleanup to do the right thing.
1691 if (txn->serialized && txn->final_lsn == 0)
1693 ReorderBufferChange *last =
1694 dlist_tail_element(ReorderBufferChange, node, &txn->changes);
1696 txn->final_lsn = last->lsn;
1699 elog(DEBUG2, "aborting old transaction %u", txn->xid);
1701 /* remove potential on-disk data, and deallocate this tx */
1702 ReorderBufferCleanupTXN(rb, txn);
1710 * Forget the contents of a transaction if we aren't interested in it's
1711 * contents. Needs to be first called for subtransactions and then for the
1714 * This is significantly different to ReorderBufferAbort() because
1715 * transactions that have committed need to be treated differently from aborted
1716 * ones since they may have modified the catalog.
1718 * Note that this is only allowed to be called in the moment a transaction
1719 * commit has just been read, not earlier; otherwise later records referring
1720 * to this xid might re-create the transaction incompletely.
1723 ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1725 ReorderBufferTXN *txn;
1727 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1730 /* unknown, nothing to forget */
1735 txn->final_lsn = lsn;
1738 * Process cache invalidation messages if there are any. Even if we're not
1739 * interested in the transaction's contents, it could have manipulated the
1740 * catalog and we need to update the caches according to that.
1742 if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
1743 ReorderBufferImmediateInvalidation(rb, txn->ninvalidations,
1744 txn->invalidations);
1746 Assert(txn->ninvalidations == 0);
1748 /* remove potential on-disk data, and deallocate */
1749 ReorderBufferCleanupTXN(rb, txn);
1753 * Execute invalidations happening outside the context of a decoded
1754 * transaction. That currently happens either for xid-less commits
1755 * (c.f. RecordTransactionCommit()) or for invalidations in uninteresting
1756 * transactions (via ReorderBufferForget()).
1759 ReorderBufferImmediateInvalidation(ReorderBuffer *rb, uint32 ninvalidations,
1760 SharedInvalidationMessage *invalidations)
1762 bool use_subtxn = IsTransactionOrTransactionBlock();
1766 BeginInternalSubTransaction("replay");
1769 * Force invalidations to happen outside of a valid transaction - that way
1770 * entries will just be marked as invalid without accessing the catalog.
1771 * That's advantageous because we don't need to setup the full state
1772 * necessary for catalog access.
1775 AbortCurrentTransaction();
1777 for (i = 0; i < ninvalidations; i++)
1778 LocalExecuteInvalidationMessage(&invalidations[i]);
1781 RollbackAndReleaseCurrentSubTransaction();
1785 * Tell reorderbuffer about an xid seen in the WAL stream. Has to be called at
1786 * least once for every xid in XLogRecord->xl_xid (other places in records
1787 * may, but do not have to be passed through here).
1789 * Reorderbuffer keeps some datastructures about transactions in LSN order,
1790 * for efficiency. To do that it has to know about when transactions are seen
1791 * first in the WAL. As many types of records are not actually interesting for
1792 * logical decoding, they do not necessarily pass though here.
1795 ReorderBufferProcessXid(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1797 /* many records won't have an xid assigned, centralize check here */
1798 if (xid != InvalidTransactionId)
1799 ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1803 * Add a new snapshot to this transaction that may only used after lsn 'lsn'
1804 * because the previous snapshot doesn't describe the catalog correctly for
1808 ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid,
1809 XLogRecPtr lsn, Snapshot snap)
1811 ReorderBufferChange *change = ReorderBufferGetChange(rb);
1813 change->data.snapshot = snap;
1814 change->action = REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT;
1816 ReorderBufferQueueChange(rb, xid, lsn, change);
1820 * Setup the base snapshot of a transaction. The base snapshot is the snapshot
1821 * that is used to decode all changes until either this transaction modifies
1822 * the catalog or another catalog modifying transaction commits.
1824 * Needs to be called before any changes are added with
1825 * ReorderBufferQueueChange().
1828 ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid,
1829 XLogRecPtr lsn, Snapshot snap)
1831 ReorderBufferTXN *txn;
1834 txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true);
1835 Assert(txn->base_snapshot == NULL);
1836 Assert(snap != NULL);
1838 txn->base_snapshot = snap;
1839 txn->base_snapshot_lsn = lsn;
1843 * Access the catalog with this CommandId at this point in the changestream.
1845 * May only be called for command ids > 1
1848 ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
1849 XLogRecPtr lsn, CommandId cid)
1851 ReorderBufferChange *change = ReorderBufferGetChange(rb);
1853 change->data.command_id = cid;
1854 change->action = REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID;
1856 ReorderBufferQueueChange(rb, xid, lsn, change);
1861 * Add new (relfilenode, tid) -> (cmin, cmax) mappings.
1864 ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
1865 XLogRecPtr lsn, RelFileNode node,
1866 ItemPointerData tid, CommandId cmin,
1867 CommandId cmax, CommandId combocid)
1869 ReorderBufferChange *change = ReorderBufferGetChange(rb);
1870 ReorderBufferTXN *txn;
1872 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1874 change->data.tuplecid.node = node;
1875 change->data.tuplecid.tid = tid;
1876 change->data.tuplecid.cmin = cmin;
1877 change->data.tuplecid.cmax = cmax;
1878 change->data.tuplecid.combocid = combocid;
1880 change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
1882 dlist_push_tail(&txn->tuplecids, &change->node);
1887 * Setup the invalidation of the toplevel transaction.
1889 * This needs to be done before ReorderBufferCommit is called!
1892 ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid,
1893 XLogRecPtr lsn, Size nmsgs,
1894 SharedInvalidationMessage *msgs)
1896 ReorderBufferTXN *txn;
1898 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1900 if (txn->ninvalidations != 0)
1901 elog(ERROR, "only ever add one set of invalidations");
1905 txn->ninvalidations = nmsgs;
1906 txn->invalidations = (SharedInvalidationMessage *)
1907 MemoryContextAlloc(rb->context,
1908 sizeof(SharedInvalidationMessage) * nmsgs);
1909 memcpy(txn->invalidations, msgs,
1910 sizeof(SharedInvalidationMessage) * nmsgs);
1914 * Apply all invalidations we know. Possibly we only need parts at this point
1915 * in the changestream but we don't know which those are.
1918 ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn)
1922 for (i = 0; i < txn->ninvalidations; i++)
1923 LocalExecuteInvalidationMessage(&txn->invalidations[i]);
1927 * Mark a transaction as containing catalog changes
1930 ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid,
1933 ReorderBufferTXN *txn;
1935 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1937 txn->has_catalog_changes = true;
1941 * Query whether a transaction is already *known* to contain catalog
1942 * changes. This can be wrong until directly before the commit!
1945 ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
1947 ReorderBufferTXN *txn;
1949 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1954 return txn->has_catalog_changes;
1958 * Have we already added the first snapshot?
1961 ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
1963 ReorderBufferTXN *txn;
1965 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1968 /* transaction isn't known yet, ergo no snapshot */
1973 * TODO: It would be a nice improvement if we would check the toplevel
1974 * transaction in subtransactions, but we'd need to keep track of a bit
1977 return txn->base_snapshot != NULL;
1982 * ---------------------------------------
1983 * Disk serialization support
1984 * ---------------------------------------
1988 * Ensure the IO buffer is >= sz.
1991 ReorderBufferSerializeReserve(ReorderBuffer *rb, Size sz)
1993 if (!rb->outbufsize)
1995 rb->outbuf = MemoryContextAlloc(rb->context, sz);
1996 rb->outbufsize = sz;
1998 else if (rb->outbufsize < sz)
2000 rb->outbuf = repalloc(rb->outbuf, sz);
2001 rb->outbufsize = sz;
2006 * Check whether the transaction tx should spill its data to disk.
2009 ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
2012 * TODO: improve accounting so we cheaply can take subtransactions into
2015 if (txn->nentries_mem >= max_changes_in_memory)
2017 ReorderBufferSerializeTXN(rb, txn);
2018 Assert(txn->nentries_mem == 0);
2023 * Spill data of a large transaction (and its subtransactions) to disk.
2026 ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
2028 dlist_iter subtxn_i;
2029 dlist_mutable_iter change_i;
2031 XLogSegNo curOpenSegNo = 0;
2033 char path[MAXPGPATH];
2035 elog(DEBUG2, "spill %u changes in XID %u to disk",
2036 (uint32) txn->nentries_mem, txn->xid);
2038 /* do the same to all child TXs */
2039 dlist_foreach(subtxn_i, &txn->subtxns)
2041 ReorderBufferTXN *subtxn;
2043 subtxn = dlist_container(ReorderBufferTXN, node, subtxn_i.cur);
2044 ReorderBufferSerializeTXN(rb, subtxn);
2047 /* serialize changestream */
2048 dlist_foreach_modify(change_i, &txn->changes)
2050 ReorderBufferChange *change;
2052 change = dlist_container(ReorderBufferChange, node, change_i.cur);
2055 * store in segment in which it belongs by start lsn, don't split over
2056 * multiple segments tho
2059 !XLByteInSeg(change->lsn, curOpenSegNo, wal_segment_size))
2064 CloseTransientFile(fd);
2066 XLByteToSeg(change->lsn, curOpenSegNo, wal_segment_size);
2067 XLogSegNoOffsetToRecPtr(curOpenSegNo, 0, recptr, wal_segment_size);
2070 * No need to care about TLIs here, only used during a single run,
2071 * so each LSN only maps to a specific WAL record.
2073 sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2074 NameStr(MyReplicationSlot->data.name), txn->xid,
2075 (uint32) (recptr >> 32), (uint32) recptr);
2077 /* open segment, create it if necessary */
2078 fd = OpenTransientFile(path,
2079 O_CREAT | O_WRONLY | O_APPEND | PG_BINARY);
2083 (errcode_for_file_access(),
2084 errmsg("could not open file \"%s\": %m",
2088 ReorderBufferSerializeChange(rb, txn, fd, change);
2089 dlist_delete(&change->node);
2090 ReorderBufferReturnChange(rb, change);
2095 Assert(spilled == txn->nentries_mem);
2096 Assert(dlist_is_empty(&txn->changes));
2097 txn->nentries_mem = 0;
2098 txn->serialized = true;
2101 CloseTransientFile(fd);
2105 * Serialize individual change to disk.
2108 ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2109 int fd, ReorderBufferChange *change)
2111 ReorderBufferDiskChange *ondisk;
2112 Size sz = sizeof(ReorderBufferDiskChange);
2114 ReorderBufferSerializeReserve(rb, sz);
2116 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2117 memcpy(&ondisk->change, change, sizeof(ReorderBufferChange));
2119 switch (change->action)
2121 /* fall through these, they're all similar enough */
2122 case REORDER_BUFFER_CHANGE_INSERT:
2123 case REORDER_BUFFER_CHANGE_UPDATE:
2124 case REORDER_BUFFER_CHANGE_DELETE:
2125 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2128 ReorderBufferTupleBuf *oldtup,
2133 oldtup = change->data.tp.oldtuple;
2134 newtup = change->data.tp.newtuple;
2138 sz += sizeof(HeapTupleData);
2139 oldlen = oldtup->tuple.t_len;
2145 sz += sizeof(HeapTupleData);
2146 newlen = newtup->tuple.t_len;
2150 /* make sure we have enough space */
2151 ReorderBufferSerializeReserve(rb, sz);
2153 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2154 /* might have been reallocated above */
2155 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2159 memcpy(data, &oldtup->tuple, sizeof(HeapTupleData));
2160 data += sizeof(HeapTupleData);
2162 memcpy(data, oldtup->tuple.t_data, oldlen);
2168 memcpy(data, &newtup->tuple, sizeof(HeapTupleData));
2169 data += sizeof(HeapTupleData);
2171 memcpy(data, newtup->tuple.t_data, newlen);
2176 case REORDER_BUFFER_CHANGE_MESSAGE:
2179 Size prefix_size = strlen(change->data.msg.prefix) + 1;
2181 sz += prefix_size + change->data.msg.message_size +
2182 sizeof(Size) + sizeof(Size);
2183 ReorderBufferSerializeReserve(rb, sz);
2185 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2187 /* might have been reallocated above */
2188 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2190 /* write the prefix including the size */
2191 memcpy(data, &prefix_size, sizeof(Size));
2192 data += sizeof(Size);
2193 memcpy(data, change->data.msg.prefix,
2195 data += prefix_size;
2197 /* write the message including the size */
2198 memcpy(data, &change->data.msg.message_size, sizeof(Size));
2199 data += sizeof(Size);
2200 memcpy(data, change->data.msg.message,
2201 change->data.msg.message_size);
2202 data += change->data.msg.message_size;
2206 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2211 snap = change->data.snapshot;
2213 sz += sizeof(SnapshotData) +
2214 sizeof(TransactionId) * snap->xcnt +
2215 sizeof(TransactionId) * snap->subxcnt
2218 /* make sure we have enough space */
2219 ReorderBufferSerializeReserve(rb, sz);
2220 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2221 /* might have been reallocated above */
2222 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2224 memcpy(data, snap, sizeof(SnapshotData));
2225 data += sizeof(SnapshotData);
2229 memcpy(data, snap->xip,
2230 sizeof(TransactionId) * snap->xcnt);
2231 data += sizeof(TransactionId) * snap->xcnt;
2236 memcpy(data, snap->subxip,
2237 sizeof(TransactionId) * snap->subxcnt);
2238 data += sizeof(TransactionId) * snap->subxcnt;
2242 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2243 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2244 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2245 /* ReorderBufferChange contains everything important */
2251 pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_WRITE);
2252 if (write(fd, rb->outbuf, ondisk->size) != ondisk->size)
2254 int save_errno = errno;
2256 CloseTransientFile(fd);
2259 (errcode_for_file_access(),
2260 errmsg("could not write to data file for XID %u: %m",
2263 pgstat_report_wait_end();
2265 Assert(ondisk->change.action == change->action);
2269 * Restore a number of changes spilled to disk back into memory.
2272 ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
2273 int *fd, XLogSegNo *segno)
2276 XLogSegNo last_segno;
2277 dlist_mutable_iter cleanup_iter;
2279 Assert(txn->first_lsn != InvalidXLogRecPtr);
2280 Assert(txn->final_lsn != InvalidXLogRecPtr);
2282 /* free current entries, so we have memory for more */
2283 dlist_foreach_modify(cleanup_iter, &txn->changes)
2285 ReorderBufferChange *cleanup =
2286 dlist_container(ReorderBufferChange, node, cleanup_iter.cur);
2288 dlist_delete(&cleanup->node);
2289 ReorderBufferReturnChange(rb, cleanup);
2291 txn->nentries_mem = 0;
2292 Assert(dlist_is_empty(&txn->changes));
2294 XLByteToSeg(txn->final_lsn, last_segno, wal_segment_size);
2296 while (restored < max_changes_in_memory && *segno <= last_segno)
2299 ReorderBufferDiskChange *ondisk;
2304 char path[MAXPGPATH];
2309 XLByteToSeg(txn->first_lsn, *segno, wal_segment_size);
2312 Assert(*segno != 0 || dlist_is_empty(&txn->changes));
2313 XLogSegNoOffsetToRecPtr(*segno, 0, recptr, wal_segment_size);
2316 * No need to care about TLIs here, only used during a single run,
2317 * so each LSN only maps to a specific WAL record.
2319 sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2320 NameStr(MyReplicationSlot->data.name), txn->xid,
2321 (uint32) (recptr >> 32), (uint32) recptr);
2323 *fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
2324 if (*fd < 0 && errno == ENOENT)
2332 (errcode_for_file_access(),
2333 errmsg("could not open file \"%s\": %m",
2339 * Read the statically sized part of a change which has information
2340 * about the total size. If we couldn't read a record, we're at the
2343 ReorderBufferSerializeReserve(rb, sizeof(ReorderBufferDiskChange));
2344 pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_READ);
2345 readBytes = read(*fd, rb->outbuf, sizeof(ReorderBufferDiskChange));
2346 pgstat_report_wait_end();
2351 CloseTransientFile(*fd);
2356 else if (readBytes < 0)
2358 (errcode_for_file_access(),
2359 errmsg("could not read from reorderbuffer spill file: %m")));
2360 else if (readBytes != sizeof(ReorderBufferDiskChange))
2362 (errcode_for_file_access(),
2363 errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2365 (uint32) sizeof(ReorderBufferDiskChange))));
2367 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2369 ReorderBufferSerializeReserve(rb,
2370 sizeof(ReorderBufferDiskChange) + ondisk->size);
2371 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2373 pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_READ);
2374 readBytes = read(*fd, rb->outbuf + sizeof(ReorderBufferDiskChange),
2375 ondisk->size - sizeof(ReorderBufferDiskChange));
2376 pgstat_report_wait_end();
2380 (errcode_for_file_access(),
2381 errmsg("could not read from reorderbuffer spill file: %m")));
2382 else if (readBytes != ondisk->size - sizeof(ReorderBufferDiskChange))
2384 (errcode_for_file_access(),
2385 errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2387 (uint32) (ondisk->size - sizeof(ReorderBufferDiskChange)))));
2390 * ok, read a full change from disk, now restore it into proper
2393 ReorderBufferRestoreChange(rb, txn, rb->outbuf);
2401 * Convert change from its on-disk format to in-memory format and queue it onto
2402 * the TXN's ->changes list.
2404 * Note: although "data" is declared char*, at entry it points to a
2405 * maxalign'd buffer, making it safe in most of this function to assume
2406 * that the pointed-to data is suitably aligned for direct access.
2409 ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2412 ReorderBufferDiskChange *ondisk;
2413 ReorderBufferChange *change;
2415 ondisk = (ReorderBufferDiskChange *) data;
2417 change = ReorderBufferGetChange(rb);
2419 /* copy static part */
2420 memcpy(change, &ondisk->change, sizeof(ReorderBufferChange));
2422 data += sizeof(ReorderBufferDiskChange);
2424 /* restore individual stuff */
2425 switch (change->action)
2427 /* fall through these, they're all similar enough */
2428 case REORDER_BUFFER_CHANGE_INSERT:
2429 case REORDER_BUFFER_CHANGE_UPDATE:
2430 case REORDER_BUFFER_CHANGE_DELETE:
2431 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2432 if (change->data.tp.oldtuple)
2434 uint32 tuplelen = ((HeapTuple) data)->t_len;
2436 change->data.tp.oldtuple =
2437 ReorderBufferGetTupleBuf(rb, tuplelen - SizeofHeapTupleHeader);
2439 /* restore ->tuple */
2440 memcpy(&change->data.tp.oldtuple->tuple, data,
2441 sizeof(HeapTupleData));
2442 data += sizeof(HeapTupleData);
2444 /* reset t_data pointer into the new tuplebuf */
2445 change->data.tp.oldtuple->tuple.t_data =
2446 ReorderBufferTupleBufData(change->data.tp.oldtuple);
2448 /* restore tuple data itself */
2449 memcpy(change->data.tp.oldtuple->tuple.t_data, data, tuplelen);
2453 if (change->data.tp.newtuple)
2455 /* here, data might not be suitably aligned! */
2458 memcpy(&tuplelen, data + offsetof(HeapTupleData, t_len),
2461 change->data.tp.newtuple =
2462 ReorderBufferGetTupleBuf(rb, tuplelen - SizeofHeapTupleHeader);
2464 /* restore ->tuple */
2465 memcpy(&change->data.tp.newtuple->tuple, data,
2466 sizeof(HeapTupleData));
2467 data += sizeof(HeapTupleData);
2469 /* reset t_data pointer into the new tuplebuf */
2470 change->data.tp.newtuple->tuple.t_data =
2471 ReorderBufferTupleBufData(change->data.tp.newtuple);
2473 /* restore tuple data itself */
2474 memcpy(change->data.tp.newtuple->tuple.t_data, data, tuplelen);
2479 case REORDER_BUFFER_CHANGE_MESSAGE:
2484 memcpy(&prefix_size, data, sizeof(Size));
2485 data += sizeof(Size);
2486 change->data.msg.prefix = MemoryContextAlloc(rb->context,
2488 memcpy(change->data.msg.prefix, data, prefix_size);
2489 Assert(change->data.msg.prefix[prefix_size - 1] == '\0');
2490 data += prefix_size;
2492 /* read the message */
2493 memcpy(&change->data.msg.message_size, data, sizeof(Size));
2494 data += sizeof(Size);
2495 change->data.msg.message = MemoryContextAlloc(rb->context,
2496 change->data.msg.message_size);
2497 memcpy(change->data.msg.message, data,
2498 change->data.msg.message_size);
2499 data += change->data.msg.message_size;
2503 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2509 oldsnap = (Snapshot) data;
2511 size = sizeof(SnapshotData) +
2512 sizeof(TransactionId) * oldsnap->xcnt +
2513 sizeof(TransactionId) * (oldsnap->subxcnt + 0);
2515 change->data.snapshot = MemoryContextAllocZero(rb->context, size);
2517 newsnap = change->data.snapshot;
2519 memcpy(newsnap, data, size);
2520 newsnap->xip = (TransactionId *)
2521 (((char *) newsnap) + sizeof(SnapshotData));
2522 newsnap->subxip = newsnap->xip + newsnap->xcnt;
2523 newsnap->copied = true;
2526 /* the base struct contains all the data, easy peasy */
2527 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2528 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2529 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2533 dlist_push_tail(&txn->changes, &change->node);
2534 txn->nentries_mem++;
2538 * Remove all on-disk stored for the passed in transaction.
2541 ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
2547 Assert(txn->first_lsn != InvalidXLogRecPtr);
2548 Assert(txn->final_lsn != InvalidXLogRecPtr);
2550 XLByteToSeg(txn->first_lsn, first, wal_segment_size);
2551 XLByteToSeg(txn->final_lsn, last, wal_segment_size);
2553 /* iterate over all possible filenames, and delete them */
2554 for (cur = first; cur <= last; cur++)
2556 char path[MAXPGPATH];
2559 XLogSegNoOffsetToRecPtr(cur, 0, recptr, wal_segment_size);
2561 sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2562 NameStr(MyReplicationSlot->data.name), txn->xid,
2563 (uint32) (recptr >> 32), (uint32) recptr);
2564 if (unlink(path) != 0 && errno != ENOENT)
2566 (errcode_for_file_access(),
2567 errmsg("could not remove file \"%s\": %m", path)));
2572 * Delete all data spilled to disk after we've restarted/crashed. It will be
2573 * recreated when the respective slots are reused.
2576 StartupReorderBuffer(void)
2579 struct dirent *logical_de;
2582 struct dirent *spill_de;
2584 logical_dir = AllocateDir("pg_replslot");
2585 while ((logical_de = ReadDir(logical_dir, "pg_replslot")) != NULL)
2587 struct stat statbuf;
2588 char path[MAXPGPATH * 2 + 12];
2590 if (strcmp(logical_de->d_name, ".") == 0 ||
2591 strcmp(logical_de->d_name, "..") == 0)
2594 /* if it cannot be a slot, skip the directory */
2595 if (!ReplicationSlotValidateName(logical_de->d_name, DEBUG2))
2599 * ok, has to be a surviving logical slot, iterate and delete
2600 * everything starting with xid-*
2602 sprintf(path, "pg_replslot/%s", logical_de->d_name);
2604 /* we're only creating directories here, skip if it's not our's */
2605 if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
2608 spill_dir = AllocateDir(path);
2609 while ((spill_de = ReadDir(spill_dir, path)) != NULL)
2611 if (strcmp(spill_de->d_name, ".") == 0 ||
2612 strcmp(spill_de->d_name, "..") == 0)
2615 /* only look at names that can be ours */
2616 if (strncmp(spill_de->d_name, "xid", 3) == 0)
2618 sprintf(path, "pg_replslot/%s/%s", logical_de->d_name,
2621 if (unlink(path) != 0)
2623 (errcode_for_file_access(),
2624 errmsg("could not remove file \"%s\": %m",
2630 FreeDir(logical_dir);
2633 /* ---------------------------------------
2634 * toast reassembly support
2635 * ---------------------------------------
2639 * Initialize per tuple toast reconstruction support.
2642 ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
2646 Assert(txn->toast_hash == NULL);
2648 memset(&hash_ctl, 0, sizeof(hash_ctl));
2649 hash_ctl.keysize = sizeof(Oid);
2650 hash_ctl.entrysize = sizeof(ReorderBufferToastEnt);
2651 hash_ctl.hcxt = rb->context;
2652 txn->toast_hash = hash_create("ReorderBufferToastHash", 5, &hash_ctl,
2653 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
2657 * Per toast-chunk handling for toast reconstruction
2659 * Appends a toast chunk so we can reconstruct it when the tuple "owning" the
2660 * toasted Datum comes along.
2663 ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
2664 Relation relation, ReorderBufferChange *change)
2666 ReorderBufferToastEnt *ent;
2667 ReorderBufferTupleBuf *newtup;
2672 TupleDesc desc = RelationGetDescr(relation);
2676 if (txn->toast_hash == NULL)
2677 ReorderBufferToastInitHash(rb, txn);
2679 Assert(IsToastRelation(relation));
2681 newtup = change->data.tp.newtuple;
2682 chunk_id = DatumGetObjectId(fastgetattr(&newtup->tuple, 1, desc, &isnull));
2684 chunk_seq = DatumGetInt32(fastgetattr(&newtup->tuple, 2, desc, &isnull));
2687 ent = (ReorderBufferToastEnt *)
2688 hash_search(txn->toast_hash,
2695 Assert(ent->chunk_id == chunk_id);
2696 ent->num_chunks = 0;
2697 ent->last_chunk_seq = 0;
2699 ent->reconstructed = NULL;
2700 dlist_init(&ent->chunks);
2703 elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq 0",
2704 chunk_seq, chunk_id);
2706 else if (found && chunk_seq != ent->last_chunk_seq + 1)
2707 elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq %d",
2708 chunk_seq, chunk_id, ent->last_chunk_seq + 1);
2710 chunk = DatumGetPointer(fastgetattr(&newtup->tuple, 3, desc, &isnull));
2713 /* calculate size so we can allocate the right size at once later */
2714 if (!VARATT_IS_EXTENDED(chunk))
2715 chunksize = VARSIZE(chunk) - VARHDRSZ;
2716 else if (VARATT_IS_SHORT(chunk))
2717 /* could happen due to heap_form_tuple doing its thing */
2718 chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT;
2720 elog(ERROR, "unexpected type of toast chunk");
2722 ent->size += chunksize;
2723 ent->last_chunk_seq = chunk_seq;
2725 dlist_push_tail(&ent->chunks, &change->node);
2729 * Rejigger change->newtuple to point to in-memory toast tuples instead to
2730 * on-disk toast tuples that may not longer exist (think DROP TABLE or VACUUM).
2732 * We cannot replace unchanged toast tuples though, so those will still point
2733 * to on-disk toast data.
2736 ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
2737 Relation relation, ReorderBufferChange *change)
2746 TupleDesc toast_desc;
2747 MemoryContext oldcontext;
2748 ReorderBufferTupleBuf *newtup;
2750 /* no toast tuples changed */
2751 if (txn->toast_hash == NULL)
2754 oldcontext = MemoryContextSwitchTo(rb->context);
2756 /* we should only have toast tuples in an INSERT or UPDATE */
2757 Assert(change->data.tp.newtuple);
2759 desc = RelationGetDescr(relation);
2761 toast_rel = RelationIdGetRelation(relation->rd_rel->reltoastrelid);
2762 toast_desc = RelationGetDescr(toast_rel);
2764 /* should we allocate from stack instead? */
2765 attrs = palloc0(sizeof(Datum) * desc->natts);
2766 isnull = palloc0(sizeof(bool) * desc->natts);
2767 free = palloc0(sizeof(bool) * desc->natts);
2769 newtup = change->data.tp.newtuple;
2771 heap_deform_tuple(&newtup->tuple, desc, attrs, isnull);
2773 for (natt = 0; natt < desc->natts; natt++)
2775 Form_pg_attribute attr = TupleDescAttr(desc, natt);
2776 ReorderBufferToastEnt *ent;
2777 struct varlena *varlena;
2779 /* va_rawsize is the size of the original datum -- including header */
2780 struct varatt_external toast_pointer;
2781 struct varatt_indirect redirect_pointer;
2782 struct varlena *new_datum = NULL;
2783 struct varlena *reconstructed;
2787 /* system columns aren't toasted */
2788 if (attr->attnum < 0)
2791 if (attr->attisdropped)
2794 /* not a varlena datatype */
2795 if (attr->attlen != -1)
2802 /* ok, we know we have a toast datum */
2803 varlena = (struct varlena *) DatumGetPointer(attrs[natt]);
2805 /* no need to do anything if the tuple isn't external */
2806 if (!VARATT_IS_EXTERNAL(varlena))
2809 VARATT_EXTERNAL_GET_POINTER(toast_pointer, varlena);
2812 * Check whether the toast tuple changed, replace if so.
2814 ent = (ReorderBufferToastEnt *)
2815 hash_search(txn->toast_hash,
2816 (void *) &toast_pointer.va_valueid,
2823 (struct varlena *) palloc0(INDIRECT_POINTER_SIZE);
2827 reconstructed = palloc0(toast_pointer.va_rawsize);
2829 ent->reconstructed = reconstructed;
2831 /* stitch toast tuple back together from its parts */
2832 dlist_foreach(it, &ent->chunks)
2835 ReorderBufferChange *cchange;
2836 ReorderBufferTupleBuf *ctup;
2839 cchange = dlist_container(ReorderBufferChange, node, it.cur);
2840 ctup = cchange->data.tp.newtuple;
2841 chunk = DatumGetPointer(
2842 fastgetattr(&ctup->tuple, 3, toast_desc, &isnull));
2845 Assert(!VARATT_IS_EXTERNAL(chunk));
2846 Assert(!VARATT_IS_SHORT(chunk));
2848 memcpy(VARDATA(reconstructed) + data_done,
2850 VARSIZE(chunk) - VARHDRSZ);
2851 data_done += VARSIZE(chunk) - VARHDRSZ;
2853 Assert(data_done == toast_pointer.va_extsize);
2855 /* make sure its marked as compressed or not */
2856 if (VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer))
2857 SET_VARSIZE_COMPRESSED(reconstructed, data_done + VARHDRSZ);
2859 SET_VARSIZE(reconstructed, data_done + VARHDRSZ);
2861 memset(&redirect_pointer, 0, sizeof(redirect_pointer));
2862 redirect_pointer.pointer = reconstructed;
2864 SET_VARTAG_EXTERNAL(new_datum, VARTAG_INDIRECT);
2865 memcpy(VARDATA_EXTERNAL(new_datum), &redirect_pointer,
2866 sizeof(redirect_pointer));
2868 attrs[natt] = PointerGetDatum(new_datum);
2872 * Build tuple in separate memory & copy tuple back into the tuplebuf
2873 * passed to the output plugin. We can't directly heap_fill_tuple() into
2874 * the tuplebuf because attrs[] will point back into the current content.
2876 tmphtup = heap_form_tuple(desc, attrs, isnull);
2877 Assert(newtup->tuple.t_len <= MaxHeapTupleSize);
2878 Assert(ReorderBufferTupleBufData(newtup) == newtup->tuple.t_data);
2880 memcpy(newtup->tuple.t_data, tmphtup->t_data, tmphtup->t_len);
2881 newtup->tuple.t_len = tmphtup->t_len;
2884 * free resources we won't further need, more persistent stuff will be
2885 * free'd in ReorderBufferToastReset().
2887 RelationClose(toast_rel);
2889 for (natt = 0; natt < desc->natts; natt++)
2892 pfree(DatumGetPointer(attrs[natt]));
2898 MemoryContextSwitchTo(oldcontext);
2902 * Free all resources allocated for toast reconstruction.
2905 ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn)
2907 HASH_SEQ_STATUS hstat;
2908 ReorderBufferToastEnt *ent;
2910 if (txn->toast_hash == NULL)
2913 /* sequentially walk over the hash and free everything */
2914 hash_seq_init(&hstat, txn->toast_hash);
2915 while ((ent = (ReorderBufferToastEnt *) hash_seq_search(&hstat)) != NULL)
2917 dlist_mutable_iter it;
2919 if (ent->reconstructed != NULL)
2920 pfree(ent->reconstructed);
2922 dlist_foreach_modify(it, &ent->chunks)
2924 ReorderBufferChange *change =
2925 dlist_container(ReorderBufferChange, node, it.cur);
2927 dlist_delete(&change->node);
2928 ReorderBufferReturnChange(rb, change);
2932 hash_destroy(txn->toast_hash);
2933 txn->toast_hash = NULL;
2937 /* ---------------------------------------
2938 * Visibility support for logical decoding
2941 * Lookup actual cmin/cmax values when using decoding snapshot. We can't
2942 * always rely on stored cmin/cmax values because of two scenarios:
2944 * * A tuple got changed multiple times during a single transaction and thus
2945 * has got a combocid. Combocid's are only valid for the duration of a
2946 * single transaction.
2947 * * A tuple with a cmin but no cmax (and thus no combocid) got
2948 * deleted/updated in another transaction than the one which created it
2949 * which we are looking at right now. As only one of cmin, cmax or combocid
2950 * is actually stored in the heap we don't have access to the value we
2953 * To resolve those problems we have a per-transaction hash of (cmin,
2954 * cmax) tuples keyed by (relfilenode, ctid) which contains the actual
2955 * (cmin, cmax) values. That also takes care of combocids by simply
2956 * not caring about them at all. As we have the real cmin/cmax values
2957 * combocids aren't interesting.
2959 * As we only care about catalog tuples here the overhead of this
2960 * hashtable should be acceptable.
2962 * Heap rewrites complicate this a bit, check rewriteheap.c for
2964 * -------------------------------------------------------------------------
2967 /* struct for qsort()ing mapping files by lsn somewhat efficiently */
2968 typedef struct RewriteMappingFile
2971 char fname[MAXPGPATH];
2972 } RewriteMappingFile;
2976 DisplayMapping(HTAB *tuplecid_data)
2978 HASH_SEQ_STATUS hstat;
2979 ReorderBufferTupleCidEnt *ent;
2981 hash_seq_init(&hstat, tuplecid_data);
2982 while ((ent = (ReorderBufferTupleCidEnt *) hash_seq_search(&hstat)) != NULL)
2984 elog(DEBUG3, "mapping: node: %u/%u/%u tid: %u/%u cmin: %u, cmax: %u",
2985 ent->key.relnode.dbNode,
2986 ent->key.relnode.spcNode,
2987 ent->key.relnode.relNode,
2988 ItemPointerGetBlockNumber(&ent->key.tid),
2989 ItemPointerGetOffsetNumber(&ent->key.tid),
2998 * Apply a single mapping file to tuplecid_data.
3000 * The mapping file has to have been verified to be a) committed b) for our
3001 * transaction c) applied in LSN order.
3004 ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname)
3006 char path[MAXPGPATH];
3009 LogicalRewriteMappingData map;
3011 sprintf(path, "pg_logical/mappings/%s", fname);
3012 fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
3015 (errcode_for_file_access(),
3016 errmsg("could not open file \"%s\": %m", path)));
3020 ReorderBufferTupleCidKey key;
3021 ReorderBufferTupleCidEnt *ent;
3022 ReorderBufferTupleCidEnt *new_ent;
3025 /* be careful about padding */
3026 memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
3028 /* read all mappings till the end of the file */
3029 pgstat_report_wait_start(WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ);
3030 readBytes = read(fd, &map, sizeof(LogicalRewriteMappingData));
3031 pgstat_report_wait_end();
3035 (errcode_for_file_access(),
3036 errmsg("could not read file \"%s\": %m",
3038 else if (readBytes == 0) /* EOF */
3040 else if (readBytes != sizeof(LogicalRewriteMappingData))
3042 (errcode_for_file_access(),
3043 errmsg("could not read from file \"%s\": read %d instead of %d bytes",
3045 (int32) sizeof(LogicalRewriteMappingData))));
3047 key.relnode = map.old_node;
3048 ItemPointerCopy(&map.old_tid,
3052 ent = (ReorderBufferTupleCidEnt *)
3053 hash_search(tuplecid_data,
3058 /* no existing mapping, no need to update */
3062 key.relnode = map.new_node;
3063 ItemPointerCopy(&map.new_tid,
3066 new_ent = (ReorderBufferTupleCidEnt *)
3067 hash_search(tuplecid_data,
3075 * Make sure the existing mapping makes sense. We sometime update
3076 * old records that did not yet have a cmax (e.g. pg_class' own
3077 * entry while rewriting it) during rewrites, so allow that.
3079 Assert(ent->cmin == InvalidCommandId || ent->cmin == new_ent->cmin);
3080 Assert(ent->cmax == InvalidCommandId || ent->cmax == new_ent->cmax);
3084 /* update mapping */
3085 new_ent->cmin = ent->cmin;
3086 new_ent->cmax = ent->cmax;
3087 new_ent->combocid = ent->combocid;
3094 * Check whether the TransactionOId 'xid' is in the pre-sorted array 'xip'.
3097 TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num)
3099 return bsearch(&xid, xip, num,
3100 sizeof(TransactionId), xidComparator) != NULL;
3104 * qsort() comparator for sorting RewriteMappingFiles in LSN order.
3107 file_sort_by_lsn(const void *a_p, const void *b_p)
3109 RewriteMappingFile *a = *(RewriteMappingFile **) a_p;
3110 RewriteMappingFile *b = *(RewriteMappingFile **) b_p;
3112 if (a->lsn < b->lsn)
3114 else if (a->lsn > b->lsn)
3120 * Apply any existing logical remapping files if there are any targeted at our
3121 * transaction for relid.
3124 UpdateLogicalMappings(HTAB *tuplecid_data, Oid relid, Snapshot snapshot)
3127 struct dirent *mapping_de;
3130 RewriteMappingFile **files_a;
3132 Oid dboid = IsSharedRelation(relid) ? InvalidOid : MyDatabaseId;
3134 mapping_dir = AllocateDir("pg_logical/mappings");
3135 while ((mapping_de = ReadDir(mapping_dir, "pg_logical/mappings")) != NULL)
3139 TransactionId f_mapped_xid;
3140 TransactionId f_create_xid;
3144 RewriteMappingFile *f;
3146 if (strcmp(mapping_de->d_name, ".") == 0 ||
3147 strcmp(mapping_de->d_name, "..") == 0)
3150 /* Ignore files that aren't ours */
3151 if (strncmp(mapping_de->d_name, "map-", 4) != 0)
3154 if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
3155 &f_dboid, &f_relid, &f_hi, &f_lo,
3156 &f_mapped_xid, &f_create_xid) != 6)
3157 elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
3159 f_lsn = ((uint64) f_hi) << 32 | f_lo;
3161 /* mapping for another database */
3162 if (f_dboid != dboid)
3165 /* mapping for another relation */
3166 if (f_relid != relid)
3169 /* did the creating transaction abort? */
3170 if (!TransactionIdDidCommit(f_create_xid))
3173 /* not for our transaction */
3174 if (!TransactionIdInArray(f_mapped_xid, snapshot->subxip, snapshot->subxcnt))
3177 /* ok, relevant, queue for apply */
3178 f = palloc(sizeof(RewriteMappingFile));
3180 strcpy(f->fname, mapping_de->d_name);
3181 files = lappend(files, f);
3183 FreeDir(mapping_dir);
3185 /* build array we can easily sort */
3186 files_a = palloc(list_length(files) * sizeof(RewriteMappingFile *));
3188 foreach(file, files)
3190 files_a[off++] = lfirst(file);
3193 /* sort files so we apply them in LSN order */
3194 qsort(files_a, list_length(files), sizeof(RewriteMappingFile *),
3197 for (off = 0; off < list_length(files); off++)
3199 RewriteMappingFile *f = files_a[off];
3201 elog(DEBUG1, "applying mapping: \"%s\" in %u", f->fname,
3202 snapshot->subxip[0]);
3203 ApplyLogicalMappingFile(tuplecid_data, relid, f->fname);
3209 * Lookup cmin/cmax of a tuple, during logical decoding where we can't rely on
3213 ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data,
3215 HeapTuple htup, Buffer buffer,
3216 CommandId *cmin, CommandId *cmax)
3218 ReorderBufferTupleCidKey key;
3219 ReorderBufferTupleCidEnt *ent;
3221 BlockNumber blockno;
3222 bool updated_mapping = false;
3224 /* be careful about padding */
3225 memset(&key, 0, sizeof(key));
3227 Assert(!BufferIsLocal(buffer));
3230 * get relfilenode from the buffer, no convenient way to access it other
3233 BufferGetTag(buffer, &key.relnode, &forkno, &blockno);
3235 /* tuples can only be in the main fork */
3236 Assert(forkno == MAIN_FORKNUM);
3237 Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self));
3239 ItemPointerCopy(&htup->t_self,
3243 ent = (ReorderBufferTupleCidEnt *)
3244 hash_search(tuplecid_data,
3250 * failed to find a mapping, check whether the table was rewritten and
3251 * apply mapping if so, but only do that once - there can be no new
3252 * mappings while we are in here since we have to hold a lock on the
3255 if (ent == NULL && !updated_mapping)
3257 UpdateLogicalMappings(tuplecid_data, htup->t_tableOid, snapshot);
3258 /* now check but don't update for a mapping again */
3259 updated_mapping = true;
3262 else if (ent == NULL)