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 (cf. 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);
199 static void ReorderBufferCleanupSerializedTXNs(const char *slotname);
200 static void ReorderBufferSerializedPath(char *path, ReplicationSlot *slot,
201 TransactionId xid, XLogSegNo segno);
203 static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap);
204 static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
205 ReorderBufferTXN *txn, CommandId cid);
207 /* ---------------------------------------
208 * toast reassembly support
209 * ---------------------------------------
211 static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn);
212 static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn);
213 static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
214 Relation relation, ReorderBufferChange *change);
215 static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
216 Relation relation, ReorderBufferChange *change);
220 * Allocate a new ReorderBuffer and clean out any old serialized state from
221 * prior ReorderBuffer instances for the same slot.
224 ReorderBufferAllocate(void)
226 ReorderBuffer *buffer;
228 MemoryContext new_ctx;
230 Assert(MyReplicationSlot != NULL);
232 /* allocate memory in own context, to have better accountability */
233 new_ctx = AllocSetContextCreate(CurrentMemoryContext,
235 ALLOCSET_DEFAULT_SIZES);
238 (ReorderBuffer *) MemoryContextAlloc(new_ctx, sizeof(ReorderBuffer));
240 memset(&hash_ctl, 0, sizeof(hash_ctl));
242 buffer->context = new_ctx;
244 buffer->change_context = SlabContextCreate(new_ctx,
246 SLAB_DEFAULT_BLOCK_SIZE,
247 sizeof(ReorderBufferChange));
249 buffer->txn_context = SlabContextCreate(new_ctx,
251 SLAB_DEFAULT_BLOCK_SIZE,
252 sizeof(ReorderBufferTXN));
254 buffer->tup_context = GenerationContextCreate(new_ctx,
256 SLAB_LARGE_BLOCK_SIZE);
258 hash_ctl.keysize = sizeof(TransactionId);
259 hash_ctl.entrysize = sizeof(ReorderBufferTXNByIdEnt);
260 hash_ctl.hcxt = buffer->context;
262 buffer->by_txn = hash_create("ReorderBufferByXid", 1000, &hash_ctl,
263 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
265 buffer->by_txn_last_xid = InvalidTransactionId;
266 buffer->by_txn_last_txn = NULL;
268 buffer->outbuf = NULL;
269 buffer->outbufsize = 0;
271 buffer->current_restart_decoding_lsn = InvalidXLogRecPtr;
273 dlist_init(&buffer->toplevel_by_lsn);
276 * Ensure there's no stale data from prior uses of this slot, in case some
277 * prior exit avoided calling ReorderBufferFree. Failure to do this can
278 * produce duplicated txns, and it's very cheap if there's nothing there.
280 ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name));
286 * Free a ReorderBuffer
289 ReorderBufferFree(ReorderBuffer *rb)
291 MemoryContext context = rb->context;
294 * We free separately allocated data by entirely scrapping reorderbuffer's
297 MemoryContextDelete(context);
299 /* Free disk space used by unconsumed reorder buffers */
300 ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name));
304 * Get an unused, possibly preallocated, ReorderBufferTXN.
306 static ReorderBufferTXN *
307 ReorderBufferGetTXN(ReorderBuffer *rb)
309 ReorderBufferTXN *txn;
311 txn = (ReorderBufferTXN *)
312 MemoryContextAlloc(rb->txn_context, sizeof(ReorderBufferTXN));
314 memset(txn, 0, sizeof(ReorderBufferTXN));
316 dlist_init(&txn->changes);
317 dlist_init(&txn->tuplecids);
318 dlist_init(&txn->subtxns);
324 * Free a ReorderBufferTXN.
326 * Deallocation might be delayed for efficiency purposes, for details check
327 * the comments above max_cached_changes's definition.
330 ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
332 /* clean the lookup cache if we were cached (quite likely) */
333 if (rb->by_txn_last_xid == txn->xid)
335 rb->by_txn_last_xid = InvalidTransactionId;
336 rb->by_txn_last_txn = NULL;
339 /* free data that's contained */
341 if (txn->tuplecid_hash != NULL)
343 hash_destroy(txn->tuplecid_hash);
344 txn->tuplecid_hash = NULL;
347 if (txn->invalidations)
349 pfree(txn->invalidations);
350 txn->invalidations = NULL;
357 * Get an unused, possibly preallocated, ReorderBufferChange.
359 ReorderBufferChange *
360 ReorderBufferGetChange(ReorderBuffer *rb)
362 ReorderBufferChange *change;
364 change = (ReorderBufferChange *)
365 MemoryContextAlloc(rb->change_context, sizeof(ReorderBufferChange));
367 memset(change, 0, sizeof(ReorderBufferChange));
372 * Free an ReorderBufferChange.
374 * Deallocation might be delayed for efficiency purposes, for details check
375 * the comments above max_cached_changes's definition.
378 ReorderBufferReturnChange(ReorderBuffer *rb, ReorderBufferChange *change)
380 /* free contained data */
381 switch (change->action)
383 case REORDER_BUFFER_CHANGE_INSERT:
384 case REORDER_BUFFER_CHANGE_UPDATE:
385 case REORDER_BUFFER_CHANGE_DELETE:
386 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
387 if (change->data.tp.newtuple)
389 ReorderBufferReturnTupleBuf(rb, change->data.tp.newtuple);
390 change->data.tp.newtuple = NULL;
393 if (change->data.tp.oldtuple)
395 ReorderBufferReturnTupleBuf(rb, change->data.tp.oldtuple);
396 change->data.tp.oldtuple = NULL;
399 case REORDER_BUFFER_CHANGE_MESSAGE:
400 if (change->data.msg.prefix != NULL)
401 pfree(change->data.msg.prefix);
402 change->data.msg.prefix = NULL;
403 if (change->data.msg.message != NULL)
404 pfree(change->data.msg.message);
405 change->data.msg.message = NULL;
407 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
408 if (change->data.snapshot)
410 ReorderBufferFreeSnap(rb, change->data.snapshot);
411 change->data.snapshot = NULL;
414 /* no data in addition to the struct itself */
415 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
416 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
417 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
425 * Get an unused, possibly preallocated, ReorderBufferTupleBuf fitting at
426 * least a tuple of size tuple_len (excluding header overhead).
428 ReorderBufferTupleBuf *
429 ReorderBufferGetTupleBuf(ReorderBuffer *rb, Size tuple_len)
431 ReorderBufferTupleBuf *tuple;
434 alloc_len = tuple_len + SizeofHeapTupleHeader;
436 tuple = (ReorderBufferTupleBuf *)
437 MemoryContextAlloc(rb->tup_context,
438 sizeof(ReorderBufferTupleBuf) +
439 MAXIMUM_ALIGNOF + alloc_len);
440 tuple->alloc_tuple_size = alloc_len;
441 tuple->tuple.t_data = ReorderBufferTupleBufData(tuple);
447 * Free an ReorderBufferTupleBuf.
449 * Deallocation might be delayed for efficiency purposes, for details check
450 * the comments above max_cached_changes's definition.
453 ReorderBufferReturnTupleBuf(ReorderBuffer *rb, ReorderBufferTupleBuf *tuple)
459 * Return the ReorderBufferTXN from the given buffer, specified by Xid.
460 * If create is true, and a transaction doesn't already exist, create it
461 * (with the given LSN, and as top transaction if that's specified);
462 * when this happens, is_new is set to true.
464 static ReorderBufferTXN *
465 ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create,
466 bool *is_new, XLogRecPtr lsn, bool create_as_top)
468 ReorderBufferTXN *txn;
469 ReorderBufferTXNByIdEnt *ent;
472 Assert(TransactionIdIsValid(xid));
473 Assert(!create || lsn != InvalidXLogRecPtr);
476 * Check the one-entry lookup cache first
478 if (TransactionIdIsValid(rb->by_txn_last_xid) &&
479 rb->by_txn_last_xid == xid)
481 txn = rb->by_txn_last_txn;
485 /* found it, and it's valid */
492 * cached as non-existent, and asked not to create? Then nothing else
497 /* otherwise fall through to create it */
501 * If the cache wasn't hit or it yielded an "does-not-exist" and we want
502 * to create an entry.
505 /* search the lookup table */
506 ent = (ReorderBufferTXNByIdEnt *)
507 hash_search(rb->by_txn,
509 create ? HASH_ENTER : HASH_FIND,
515 /* initialize the new entry, if creation was requested */
518 ent->txn = ReorderBufferGetTXN(rb);
521 txn->first_lsn = lsn;
522 txn->restart_decoding_lsn = rb->current_restart_decoding_lsn;
526 dlist_push_tail(&rb->toplevel_by_lsn, &txn->node);
527 AssertTXNLsnOrder(rb);
531 txn = NULL; /* not found and not asked to create */
534 rb->by_txn_last_xid = xid;
535 rb->by_txn_last_txn = txn;
540 Assert(!create || txn != NULL);
545 * Queue a change into a transaction so it can be replayed upon commit.
548 ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
549 ReorderBufferChange *change)
551 ReorderBufferTXN *txn;
553 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
556 Assert(InvalidXLogRecPtr != lsn);
557 dlist_push_tail(&txn->changes, &change->node);
561 ReorderBufferCheckSerializeTXN(rb, txn);
565 * Queue message into a transaction so it can be processed upon commit.
568 ReorderBufferQueueMessage(ReorderBuffer *rb, TransactionId xid,
569 Snapshot snapshot, XLogRecPtr lsn,
570 bool transactional, const char *prefix,
571 Size message_size, const char *message)
575 MemoryContext oldcontext;
576 ReorderBufferChange *change;
578 Assert(xid != InvalidTransactionId);
580 oldcontext = MemoryContextSwitchTo(rb->context);
582 change = ReorderBufferGetChange(rb);
583 change->action = REORDER_BUFFER_CHANGE_MESSAGE;
584 change->data.msg.prefix = pstrdup(prefix);
585 change->data.msg.message_size = message_size;
586 change->data.msg.message = palloc(message_size);
587 memcpy(change->data.msg.message, message, message_size);
589 ReorderBufferQueueChange(rb, xid, lsn, change);
591 MemoryContextSwitchTo(oldcontext);
595 ReorderBufferTXN *txn = NULL;
596 volatile Snapshot snapshot_now = snapshot;
598 if (xid != InvalidTransactionId)
599 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
601 /* setup snapshot to allow catalog access */
602 SetupHistoricSnapshot(snapshot_now, NULL);
605 rb->message(rb, txn, lsn, false, prefix, message_size, message);
607 TeardownHistoricSnapshot(false);
611 TeardownHistoricSnapshot(true);
620 AssertTXNLsnOrder(ReorderBuffer *rb)
622 #ifdef USE_ASSERT_CHECKING
624 XLogRecPtr prev_first_lsn = InvalidXLogRecPtr;
626 dlist_foreach(iter, &rb->toplevel_by_lsn)
628 ReorderBufferTXN *cur_txn;
630 cur_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
631 Assert(cur_txn->first_lsn != InvalidXLogRecPtr);
633 if (cur_txn->end_lsn != InvalidXLogRecPtr)
634 Assert(cur_txn->first_lsn <= cur_txn->end_lsn);
636 if (prev_first_lsn != InvalidXLogRecPtr)
637 Assert(prev_first_lsn < cur_txn->first_lsn);
639 Assert(!cur_txn->is_known_as_subxact);
640 prev_first_lsn = cur_txn->first_lsn;
646 ReorderBufferGetOldestTXN(ReorderBuffer *rb)
648 ReorderBufferTXN *txn;
650 if (dlist_is_empty(&rb->toplevel_by_lsn))
653 AssertTXNLsnOrder(rb);
655 txn = dlist_head_element(ReorderBufferTXN, node, &rb->toplevel_by_lsn);
657 Assert(!txn->is_known_as_subxact);
658 Assert(txn->first_lsn != InvalidXLogRecPtr);
663 ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr)
665 rb->current_restart_decoding_lsn = ptr;
669 ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid,
670 TransactionId subxid, XLogRecPtr lsn)
672 ReorderBufferTXN *txn;
673 ReorderBufferTXN *subtxn;
677 txn = ReorderBufferTXNByXid(rb, xid, true, &new_top, lsn, true);
678 subtxn = ReorderBufferTXNByXid(rb, subxid, true, &new_sub, lsn, false);
683 * we assign subtransactions to top level transaction even if we don't
684 * have data for it yet, assignment records frequently reference xids
685 * that have not yet produced any records. Knowing those aren't top
686 * level xids allows us to make processing cheaper in some places.
688 dlist_push_tail(&txn->subtxns, &subtxn->node);
691 else if (!subtxn->is_known_as_subxact)
693 subtxn->is_known_as_subxact = true;
694 Assert(subtxn->nsubtxns == 0);
696 /* remove from lsn order list of top-level transactions */
697 dlist_delete(&subtxn->node);
699 /* add to toplevel transaction */
700 dlist_push_tail(&txn->subtxns, &subtxn->node);
705 elog(ERROR, "existing subxact assigned to unknown toplevel xact");
710 * Associate a subtransaction with its toplevel transaction at commit
711 * time. There may be no further changes added after this.
714 ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
715 TransactionId subxid, XLogRecPtr commit_lsn,
718 ReorderBufferTXN *txn;
719 ReorderBufferTXN *subtxn;
721 subtxn = ReorderBufferTXNByXid(rb, subxid, false, NULL,
722 InvalidXLogRecPtr, false);
725 * No need to do anything if that subtxn didn't contain any changes
730 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, commit_lsn, true);
733 elog(ERROR, "subxact logged without previous toplevel record");
736 * Pass our base snapshot to the parent transaction if it doesn't have
737 * one, or ours is older. That can happen if there are no changes in the
738 * toplevel transaction but in one of the child transactions. This allows
739 * the parent to simply use its base snapshot initially.
741 if (subtxn->base_snapshot != NULL &&
742 (txn->base_snapshot == NULL ||
743 txn->base_snapshot_lsn > subtxn->base_snapshot_lsn))
745 txn->base_snapshot = subtxn->base_snapshot;
746 txn->base_snapshot_lsn = subtxn->base_snapshot_lsn;
747 subtxn->base_snapshot = NULL;
748 subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
751 subtxn->final_lsn = commit_lsn;
752 subtxn->end_lsn = end_lsn;
754 if (!subtxn->is_known_as_subxact)
756 subtxn->is_known_as_subxact = true;
757 Assert(subtxn->nsubtxns == 0);
759 /* remove from lsn order list of top-level transactions */
760 dlist_delete(&subtxn->node);
762 /* add to subtransaction list */
763 dlist_push_tail(&txn->subtxns, &subtxn->node);
770 * Support for efficiently iterating over a transaction's and its
771 * subtransactions' changes.
773 * We do by doing a k-way merge between transactions/subtransactions. For that
774 * we model the current heads of the different transactions as a binary heap
775 * so we easily know which (sub-)transaction has the change with the smallest
778 * We assume the changes in individual transactions are already sorted by LSN.
782 * Binary heap comparison function.
785 ReorderBufferIterCompare(Datum a, Datum b, void *arg)
787 ReorderBufferIterTXNState *state = (ReorderBufferIterTXNState *) arg;
788 XLogRecPtr pos_a = state->entries[DatumGetInt32(a)].lsn;
789 XLogRecPtr pos_b = state->entries[DatumGetInt32(b)].lsn;
793 else if (pos_a == pos_b)
799 * Allocate & initialize an iterator which iterates in lsn order over a
800 * transaction and all its subtransactions.
802 static ReorderBufferIterTXNState *
803 ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn)
806 ReorderBufferIterTXNState *state;
807 dlist_iter cur_txn_i;
811 * Calculate the size of our heap: one element for every transaction that
812 * contains changes. (Besides the transactions already in the reorder
813 * buffer, we count the one we were directly passed.)
815 if (txn->nentries > 0)
818 dlist_foreach(cur_txn_i, &txn->subtxns)
820 ReorderBufferTXN *cur_txn;
822 cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
824 if (cur_txn->nentries > 0)
829 * TODO: Consider adding fastpath for the rather common nr_txns=1 case, no
830 * need to allocate/build a heap then.
833 /* allocate iteration state */
834 state = (ReorderBufferIterTXNState *)
835 MemoryContextAllocZero(rb->context,
836 sizeof(ReorderBufferIterTXNState) +
837 sizeof(ReorderBufferIterTXNEntry) * nr_txns);
839 state->nr_txns = nr_txns;
840 dlist_init(&state->old_change);
842 for (off = 0; off < state->nr_txns; off++)
844 state->entries[off].fd = -1;
845 state->entries[off].segno = 0;
849 state->heap = binaryheap_allocate(state->nr_txns,
850 ReorderBufferIterCompare,
854 * Now insert items into the binary heap, in an unordered fashion. (We
855 * will run a heap assembly step at the end; this is more efficient.)
860 /* add toplevel transaction if it contains changes */
861 if (txn->nentries > 0)
863 ReorderBufferChange *cur_change;
867 /* serialize remaining changes */
868 ReorderBufferSerializeTXN(rb, txn);
869 ReorderBufferRestoreChanges(rb, txn, &state->entries[off].fd,
870 &state->entries[off].segno);
873 cur_change = dlist_head_element(ReorderBufferChange, node,
876 state->entries[off].lsn = cur_change->lsn;
877 state->entries[off].change = cur_change;
878 state->entries[off].txn = txn;
880 binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
883 /* add subtransactions if they contain changes */
884 dlist_foreach(cur_txn_i, &txn->subtxns)
886 ReorderBufferTXN *cur_txn;
888 cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
890 if (cur_txn->nentries > 0)
892 ReorderBufferChange *cur_change;
894 if (cur_txn->serialized)
896 /* serialize remaining changes */
897 ReorderBufferSerializeTXN(rb, cur_txn);
898 ReorderBufferRestoreChanges(rb, cur_txn,
899 &state->entries[off].fd,
900 &state->entries[off].segno);
902 cur_change = dlist_head_element(ReorderBufferChange, node,
905 state->entries[off].lsn = cur_change->lsn;
906 state->entries[off].change = cur_change;
907 state->entries[off].txn = cur_txn;
909 binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
913 /* assemble a valid binary heap */
914 binaryheap_build(state->heap);
920 * Return the next change when iterating over a transaction and its
923 * Returns NULL when no further changes exist.
925 static ReorderBufferChange *
926 ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state)
928 ReorderBufferChange *change;
929 ReorderBufferIterTXNEntry *entry;
932 /* nothing there anymore */
933 if (state->heap->bh_size == 0)
936 off = DatumGetInt32(binaryheap_first(state->heap));
937 entry = &state->entries[off];
939 /* free memory we might have "leaked" in the previous *Next call */
940 if (!dlist_is_empty(&state->old_change))
942 change = dlist_container(ReorderBufferChange, node,
943 dlist_pop_head_node(&state->old_change));
944 ReorderBufferReturnChange(rb, change);
945 Assert(dlist_is_empty(&state->old_change));
948 change = entry->change;
951 * update heap with information about which transaction has the next
952 * relevant change in LSN order
955 /* there are in-memory changes */
956 if (dlist_has_next(&entry->txn->changes, &entry->change->node))
958 dlist_node *next = dlist_next_node(&entry->txn->changes, &change->node);
959 ReorderBufferChange *next_change =
960 dlist_container(ReorderBufferChange, node, next);
962 /* txn stays the same */
963 state->entries[off].lsn = next_change->lsn;
964 state->entries[off].change = next_change;
966 binaryheap_replace_first(state->heap, Int32GetDatum(off));
970 /* try to load changes from disk */
971 if (entry->txn->nentries != entry->txn->nentries_mem)
974 * Ugly: restoring changes will reuse *Change records, thus delete the
975 * current one from the per-tx list and only free in the next call.
977 dlist_delete(&change->node);
978 dlist_push_tail(&state->old_change, &change->node);
980 if (ReorderBufferRestoreChanges(rb, entry->txn, &entry->fd,
981 &state->entries[off].segno))
983 /* successfully restored changes from disk */
984 ReorderBufferChange *next_change =
985 dlist_head_element(ReorderBufferChange, node,
986 &entry->txn->changes);
988 elog(DEBUG2, "restored %u/%u changes from disk",
989 (uint32) entry->txn->nentries_mem,
990 (uint32) entry->txn->nentries);
992 Assert(entry->txn->nentries_mem);
993 /* txn stays the same */
994 state->entries[off].lsn = next_change->lsn;
995 state->entries[off].change = next_change;
996 binaryheap_replace_first(state->heap, Int32GetDatum(off));
1002 /* ok, no changes there anymore, remove */
1003 binaryheap_remove_first(state->heap);
1009 * Deallocate the iterator
1012 ReorderBufferIterTXNFinish(ReorderBuffer *rb,
1013 ReorderBufferIterTXNState *state)
1017 for (off = 0; off < state->nr_txns; off++)
1019 if (state->entries[off].fd != -1)
1020 CloseTransientFile(state->entries[off].fd);
1023 /* free memory we might have "leaked" in the last *Next call */
1024 if (!dlist_is_empty(&state->old_change))
1026 ReorderBufferChange *change;
1028 change = dlist_container(ReorderBufferChange, node,
1029 dlist_pop_head_node(&state->old_change));
1030 ReorderBufferReturnChange(rb, change);
1031 Assert(dlist_is_empty(&state->old_change));
1034 binaryheap_free(state->heap);
1039 * Cleanup the contents of a transaction, usually after the transaction
1040 * committed or aborted.
1043 ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1046 dlist_mutable_iter iter;
1048 /* cleanup subtransactions & their changes */
1049 dlist_foreach_modify(iter, &txn->subtxns)
1051 ReorderBufferTXN *subtxn;
1053 subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
1056 * Subtransactions are always associated to the toplevel TXN, even if
1057 * they originally were happening inside another subtxn, so we won't
1058 * ever recurse more than one level deep here.
1060 Assert(subtxn->is_known_as_subxact);
1061 Assert(subtxn->nsubtxns == 0);
1063 ReorderBufferCleanupTXN(rb, subtxn);
1066 /* cleanup changes in the toplevel txn */
1067 dlist_foreach_modify(iter, &txn->changes)
1069 ReorderBufferChange *change;
1071 change = dlist_container(ReorderBufferChange, node, iter.cur);
1073 ReorderBufferReturnChange(rb, change);
1077 * Cleanup the tuplecids we stored for decoding catalog snapshot access.
1078 * They are always stored in the toplevel transaction.
1080 dlist_foreach_modify(iter, &txn->tuplecids)
1082 ReorderBufferChange *change;
1084 change = dlist_container(ReorderBufferChange, node, iter.cur);
1085 Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1086 ReorderBufferReturnChange(rb, change);
1089 if (txn->base_snapshot != NULL)
1091 SnapBuildSnapDecRefcount(txn->base_snapshot);
1092 txn->base_snapshot = NULL;
1093 txn->base_snapshot_lsn = InvalidXLogRecPtr;
1097 * Remove TXN from its containing list.
1099 * Note: if txn->is_known_as_subxact, we are deleting the TXN from its
1100 * parent's list of known subxacts; this leaves the parent's nsubxacts
1101 * count too high, but we don't care. Otherwise, we are deleting the TXN
1102 * from the LSN-ordered list of toplevel TXNs.
1104 dlist_delete(&txn->node);
1106 /* now remove reference from buffer */
1107 hash_search(rb->by_txn,
1113 /* remove entries spilled to disk */
1114 if (txn->serialized)
1115 ReorderBufferRestoreCleanup(rb, txn);
1118 ReorderBufferReturnTXN(rb, txn);
1122 * Build a hash with a (relfilenode, ctid) -> (cmin, cmax) mapping for use by
1123 * tqual.c's HeapTupleSatisfiesHistoricMVCC.
1126 ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
1131 if (!txn->has_catalog_changes || dlist_is_empty(&txn->tuplecids))
1134 memset(&hash_ctl, 0, sizeof(hash_ctl));
1136 hash_ctl.keysize = sizeof(ReorderBufferTupleCidKey);
1137 hash_ctl.entrysize = sizeof(ReorderBufferTupleCidEnt);
1138 hash_ctl.hcxt = rb->context;
1141 * create the hash with the exact number of to-be-stored tuplecids from
1144 txn->tuplecid_hash =
1145 hash_create("ReorderBufferTupleCid", txn->ntuplecids, &hash_ctl,
1146 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
1148 dlist_foreach(iter, &txn->tuplecids)
1150 ReorderBufferTupleCidKey key;
1151 ReorderBufferTupleCidEnt *ent;
1153 ReorderBufferChange *change;
1155 change = dlist_container(ReorderBufferChange, node, iter.cur);
1157 Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1159 /* be careful about padding */
1160 memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
1162 key.relnode = change->data.tuplecid.node;
1164 ItemPointerCopy(&change->data.tuplecid.tid,
1167 ent = (ReorderBufferTupleCidEnt *)
1168 hash_search(txn->tuplecid_hash,
1170 HASH_ENTER | HASH_FIND,
1174 ent->cmin = change->data.tuplecid.cmin;
1175 ent->cmax = change->data.tuplecid.cmax;
1176 ent->combocid = change->data.tuplecid.combocid;
1180 Assert(ent->cmin == change->data.tuplecid.cmin);
1181 Assert(ent->cmax == InvalidCommandId ||
1182 ent->cmax == change->data.tuplecid.cmax);
1185 * if the tuple got valid in this transaction and now got deleted
1186 * we already have a valid cmin stored. The cmax will be
1187 * InvalidCommandId though.
1189 ent->cmax = change->data.tuplecid.cmax;
1195 * Copy a provided snapshot so we can modify it privately. This is needed so
1196 * that catalog modifying transactions can look into intermediate catalog
1200 ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
1201 ReorderBufferTXN *txn, CommandId cid)
1208 size = sizeof(SnapshotData) +
1209 sizeof(TransactionId) * orig_snap->xcnt +
1210 sizeof(TransactionId) * (txn->nsubtxns + 1);
1212 snap = MemoryContextAllocZero(rb->context, size);
1213 memcpy(snap, orig_snap, sizeof(SnapshotData));
1215 snap->copied = true;
1216 snap->active_count = 1; /* mark as active so nobody frees it */
1217 snap->regd_count = 0;
1218 snap->xip = (TransactionId *) (snap + 1);
1220 memcpy(snap->xip, orig_snap->xip, sizeof(TransactionId) * snap->xcnt);
1223 * snap->subxip contains all txids that belong to our transaction which we
1224 * need to check via cmin/cmax. That's why we store the toplevel
1225 * transaction in there as well.
1227 snap->subxip = snap->xip + snap->xcnt;
1228 snap->subxip[i++] = txn->xid;
1231 * nsubxcnt isn't decreased when subtransactions abort, so count manually.
1232 * Since it's an upper boundary it is safe to use it for the allocation
1237 dlist_foreach(iter, &txn->subtxns)
1239 ReorderBufferTXN *sub_txn;
1241 sub_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
1242 snap->subxip[i++] = sub_txn->xid;
1246 /* sort so we can bsearch() later */
1247 qsort(snap->subxip, snap->subxcnt, sizeof(TransactionId), xidComparator);
1249 /* store the specified current CommandId */
1256 * Free a previously ReorderBufferCopySnap'ed snapshot
1259 ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap)
1264 SnapBuildSnapDecRefcount(snap);
1268 * Perform the replay of a transaction and it's non-aborted subtransactions.
1270 * Subtransactions previously have to be processed by
1271 * ReorderBufferCommitChild(), even if previously assigned to the toplevel
1272 * transaction with ReorderBufferAssignChild.
1274 * We currently can only decode a transaction's contents in when their commit
1275 * record is read because that's currently the only place where we know about
1276 * cache invalidations. Thus, once a toplevel commit is read, we iterate over
1277 * the top and subtransactions (using a k-way merge) and replay the changes in
1281 ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
1282 XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
1283 TimestampTz commit_time,
1284 RepOriginId origin_id, XLogRecPtr origin_lsn)
1286 ReorderBufferTXN *txn;
1287 volatile Snapshot snapshot_now;
1288 volatile CommandId command_id = FirstCommandId;
1290 ReorderBufferIterTXNState *volatile iterstate = NULL;
1292 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1295 /* unknown transaction, nothing to replay */
1299 txn->final_lsn = commit_lsn;
1300 txn->end_lsn = end_lsn;
1301 txn->commit_time = commit_time;
1302 txn->origin_id = origin_id;
1303 txn->origin_lsn = origin_lsn;
1306 * If this transaction didn't have any real changes in our database, it's
1307 * OK not to have a snapshot. Note that ReorderBufferCommitChild will have
1308 * transferred its snapshot to this transaction if it had one and the
1309 * toplevel tx didn't.
1311 if (txn->base_snapshot == NULL)
1313 Assert(txn->ninvalidations == 0);
1314 ReorderBufferCleanupTXN(rb, txn);
1318 snapshot_now = txn->base_snapshot;
1320 /* build data to be able to lookup the CommandIds of catalog tuples */
1321 ReorderBufferBuildTupleCidHash(rb, txn);
1323 /* setup the initial snapshot */
1324 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1327 * Decoding needs access to syscaches et al., which in turn use
1328 * heavyweight locks and such. Thus we need to have enough state around to
1329 * keep track of those. The easiest way is to simply use a transaction
1330 * internally. That also allows us to easily enforce that nothing writes
1331 * to the database by checking for xid assignments.
1333 * When we're called via the SQL SRF there's already a transaction
1334 * started, so start an explicit subtransaction there.
1336 using_subtxn = IsTransactionOrTransactionBlock();
1340 ReorderBufferChange *change;
1341 ReorderBufferChange *specinsert = NULL;
1344 BeginInternalSubTransaction("replay");
1346 StartTransactionCommand();
1350 iterstate = ReorderBufferIterTXNInit(rb, txn);
1351 while ((change = ReorderBufferIterTXNNext(rb, iterstate)) != NULL)
1353 Relation relation = NULL;
1356 switch (change->action)
1358 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
1361 * Confirmation for speculative insertion arrived. Simply
1362 * use as a normal record. It'll be cleaned up at the end
1363 * of INSERT processing.
1365 Assert(specinsert->data.tp.oldtuple == NULL);
1366 change = specinsert;
1367 change->action = REORDER_BUFFER_CHANGE_INSERT;
1369 /* intentionally fall through */
1370 case REORDER_BUFFER_CHANGE_INSERT:
1371 case REORDER_BUFFER_CHANGE_UPDATE:
1372 case REORDER_BUFFER_CHANGE_DELETE:
1373 Assert(snapshot_now);
1375 reloid = RelidByRelfilenode(change->data.tp.relnode.spcNode,
1376 change->data.tp.relnode.relNode);
1379 * Catalog tuple without data, emitted while catalog was
1380 * in the process of being rewritten.
1382 if (reloid == InvalidOid &&
1383 change->data.tp.newtuple == NULL &&
1384 change->data.tp.oldtuple == NULL)
1386 else if (reloid == InvalidOid)
1387 elog(ERROR, "could not map filenode \"%s\" to relation OID",
1388 relpathperm(change->data.tp.relnode,
1391 relation = RelationIdGetRelation(reloid);
1393 if (relation == NULL)
1394 elog(ERROR, "could not open relation with OID %u (for filenode \"%s\")",
1396 relpathperm(change->data.tp.relnode,
1399 if (!RelationIsLogicallyLogged(relation))
1403 * Ignore temporary heaps created during DDL unless the
1404 * plugin has asked for them.
1406 if (relation->rd_rel->relrewrite && !rb->output_rewrites)
1410 * For now ignore sequence changes entirely. Most of the
1411 * time they don't log changes using records we
1412 * understand, so it doesn't make sense to handle the few
1415 if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
1418 /* user-triggered change */
1419 if (!IsToastRelation(relation))
1421 ReorderBufferToastReplace(rb, txn, relation, change);
1422 rb->apply_change(rb, txn, relation, change);
1425 * Only clear reassembled toast chunks if we're sure
1426 * they're not required anymore. The creator of the
1429 if (change->data.tp.clear_toast_afterwards)
1430 ReorderBufferToastReset(rb, txn);
1432 /* we're not interested in toast deletions */
1433 else if (change->action == REORDER_BUFFER_CHANGE_INSERT)
1436 * Need to reassemble the full toasted Datum in
1437 * memory, to ensure the chunks don't get reused till
1438 * we're done remove it from the list of this
1439 * transaction's changes. Otherwise it will get
1440 * freed/reused while restoring spooled data from
1443 dlist_delete(&change->node);
1444 ReorderBufferToastAppendChunk(rb, txn, relation,
1451 * Either speculative insertion was confirmed, or it was
1452 * unsuccessful and the record isn't needed anymore.
1454 if (specinsert != NULL)
1456 ReorderBufferReturnChange(rb, specinsert);
1460 if (relation != NULL)
1462 RelationClose(relation);
1467 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
1470 * Speculative insertions are dealt with by delaying the
1471 * processing of the insert until the confirmation record
1472 * arrives. For that we simply unlink the record from the
1473 * chain, so it does not get freed/reused while restoring
1474 * spooled data from disk.
1476 * This is safe in the face of concurrent catalog changes
1477 * because the relevant relation can't be changed between
1478 * speculative insertion and confirmation due to
1479 * CheckTableNotInUse() and locking.
1482 /* clear out a pending (and thus failed) speculation */
1483 if (specinsert != NULL)
1485 ReorderBufferReturnChange(rb, specinsert);
1489 /* and memorize the pending insertion */
1490 dlist_delete(&change->node);
1491 specinsert = change;
1494 case REORDER_BUFFER_CHANGE_MESSAGE:
1495 rb->message(rb, txn, change->lsn, true,
1496 change->data.msg.prefix,
1497 change->data.msg.message_size,
1498 change->data.msg.message);
1501 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
1502 /* get rid of the old */
1503 TeardownHistoricSnapshot(false);
1505 if (snapshot_now->copied)
1507 ReorderBufferFreeSnap(rb, snapshot_now);
1509 ReorderBufferCopySnap(rb, change->data.snapshot,
1514 * Restored from disk, need to be careful not to double
1515 * free. We could introduce refcounting for that, but for
1516 * now this seems infrequent enough not to care.
1518 else if (change->data.snapshot->copied)
1521 ReorderBufferCopySnap(rb, change->data.snapshot,
1526 snapshot_now = change->data.snapshot;
1530 /* and continue with the new one */
1531 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1534 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
1535 Assert(change->data.command_id != InvalidCommandId);
1537 if (command_id < change->data.command_id)
1539 command_id = change->data.command_id;
1541 if (!snapshot_now->copied)
1543 /* we don't use the global one anymore */
1544 snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
1548 snapshot_now->curcid = command_id;
1550 TeardownHistoricSnapshot(false);
1551 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1554 * Every time the CommandId is incremented, we could
1555 * see new catalog contents, so execute all
1558 ReorderBufferExecuteInvalidations(rb, txn);
1563 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
1564 elog(ERROR, "tuplecid value in changequeue");
1570 * There's a speculative insertion remaining, just clean in up, it
1571 * can't have been successful, otherwise we'd gotten a confirmation
1576 ReorderBufferReturnChange(rb, specinsert);
1580 /* clean up the iterator */
1581 ReorderBufferIterTXNFinish(rb, iterstate);
1584 /* call commit callback */
1585 rb->commit(rb, txn, commit_lsn);
1587 /* this is just a sanity check against bad output plugin behaviour */
1588 if (GetCurrentTransactionIdIfAny() != InvalidTransactionId)
1589 elog(ERROR, "output plugin used XID %u",
1590 GetCurrentTransactionId());
1593 TeardownHistoricSnapshot(false);
1596 * Aborting the current (sub-)transaction as a whole has the right
1597 * semantics. We want all locks acquired in here to be released, not
1598 * reassigned to the parent and we do not want any database access
1599 * have persistent effects.
1601 AbortCurrentTransaction();
1603 /* make sure there's no cache pollution */
1604 ReorderBufferExecuteInvalidations(rb, txn);
1607 RollbackAndReleaseCurrentSubTransaction();
1609 if (snapshot_now->copied)
1610 ReorderBufferFreeSnap(rb, snapshot_now);
1612 /* remove potential on-disk data, and deallocate */
1613 ReorderBufferCleanupTXN(rb, txn);
1617 /* TODO: Encapsulate cleanup from the PG_TRY and PG_CATCH blocks */
1619 ReorderBufferIterTXNFinish(rb, iterstate);
1621 TeardownHistoricSnapshot(true);
1624 * Force cache invalidation to happen outside of a valid transaction
1625 * to prevent catalog access as we just caught an error.
1627 AbortCurrentTransaction();
1629 /* make sure there's no cache pollution */
1630 ReorderBufferExecuteInvalidations(rb, txn);
1633 RollbackAndReleaseCurrentSubTransaction();
1635 if (snapshot_now->copied)
1636 ReorderBufferFreeSnap(rb, snapshot_now);
1638 /* remove potential on-disk data, and deallocate */
1639 ReorderBufferCleanupTXN(rb, txn);
1647 * Abort a transaction that possibly has previous changes. Needs to be first
1648 * called for subtransactions and then for the toplevel xid.
1650 * NB: Transactions handled here have to have actively aborted (i.e. have
1651 * produced an abort record). Implicitly aborted transactions are handled via
1652 * ReorderBufferAbortOld(); transactions we're just not interested in, but
1653 * which have committed are handled in ReorderBufferForget().
1655 * This function purges this transaction and its contents from memory and
1659 ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1661 ReorderBufferTXN *txn;
1663 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1666 /* unknown, nothing to remove */
1671 txn->final_lsn = lsn;
1673 /* remove potential on-disk data, and deallocate */
1674 ReorderBufferCleanupTXN(rb, txn);
1678 * Abort all transactions that aren't actually running anymore because the
1681 * NB: These really have to be transactions that have aborted due to a server
1682 * crash/immediate restart, as we don't deal with invalidations here.
1685 ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid)
1687 dlist_mutable_iter it;
1690 * Iterate through all (potential) toplevel TXNs and abort all that are
1691 * older than what possibly can be running. Once we've found the first
1692 * that is alive we stop, there might be some that acquired an xid earlier
1693 * but started writing later, but it's unlikely and they will be cleaned
1694 * up in a later call to this function.
1696 dlist_foreach_modify(it, &rb->toplevel_by_lsn)
1698 ReorderBufferTXN *txn;
1700 txn = dlist_container(ReorderBufferTXN, node, it.cur);
1702 if (TransactionIdPrecedes(txn->xid, oldestRunningXid))
1705 * We set final_lsn on a transaction when we decode its commit or
1706 * abort record, but we never see those records for crashed
1707 * transactions. To ensure cleanup of these transactions, set
1708 * final_lsn to that of their last change; this causes
1709 * ReorderBufferRestoreCleanup to do the right thing.
1711 if (txn->serialized && txn->final_lsn == 0)
1713 ReorderBufferChange *last =
1714 dlist_tail_element(ReorderBufferChange, node, &txn->changes);
1716 txn->final_lsn = last->lsn;
1719 elog(DEBUG2, "aborting old transaction %u", txn->xid);
1721 /* remove potential on-disk data, and deallocate this tx */
1722 ReorderBufferCleanupTXN(rb, txn);
1730 * Forget the contents of a transaction if we aren't interested in it's
1731 * contents. Needs to be first called for subtransactions and then for the
1734 * This is significantly different to ReorderBufferAbort() because
1735 * transactions that have committed need to be treated differently from aborted
1736 * ones since they may have modified the catalog.
1738 * Note that this is only allowed to be called in the moment a transaction
1739 * commit has just been read, not earlier; otherwise later records referring
1740 * to this xid might re-create the transaction incompletely.
1743 ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1745 ReorderBufferTXN *txn;
1747 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1750 /* unknown, nothing to forget */
1755 txn->final_lsn = lsn;
1758 * Process cache invalidation messages if there are any. Even if we're not
1759 * interested in the transaction's contents, it could have manipulated the
1760 * catalog and we need to update the caches according to that.
1762 if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
1763 ReorderBufferImmediateInvalidation(rb, txn->ninvalidations,
1764 txn->invalidations);
1766 Assert(txn->ninvalidations == 0);
1768 /* remove potential on-disk data, and deallocate */
1769 ReorderBufferCleanupTXN(rb, txn);
1773 * Execute invalidations happening outside the context of a decoded
1774 * transaction. That currently happens either for xid-less commits
1775 * (cf. RecordTransactionCommit()) or for invalidations in uninteresting
1776 * transactions (via ReorderBufferForget()).
1779 ReorderBufferImmediateInvalidation(ReorderBuffer *rb, uint32 ninvalidations,
1780 SharedInvalidationMessage *invalidations)
1782 bool use_subtxn = IsTransactionOrTransactionBlock();
1786 BeginInternalSubTransaction("replay");
1789 * Force invalidations to happen outside of a valid transaction - that way
1790 * entries will just be marked as invalid without accessing the catalog.
1791 * That's advantageous because we don't need to setup the full state
1792 * necessary for catalog access.
1795 AbortCurrentTransaction();
1797 for (i = 0; i < ninvalidations; i++)
1798 LocalExecuteInvalidationMessage(&invalidations[i]);
1801 RollbackAndReleaseCurrentSubTransaction();
1805 * Tell reorderbuffer about an xid seen in the WAL stream. Has to be called at
1806 * least once for every xid in XLogRecord->xl_xid (other places in records
1807 * may, but do not have to be passed through here).
1809 * Reorderbuffer keeps some datastructures about transactions in LSN order,
1810 * for efficiency. To do that it has to know about when transactions are seen
1811 * first in the WAL. As many types of records are not actually interesting for
1812 * logical decoding, they do not necessarily pass though here.
1815 ReorderBufferProcessXid(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1817 /* many records won't have an xid assigned, centralize check here */
1818 if (xid != InvalidTransactionId)
1819 ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1823 * Add a new snapshot to this transaction that may only used after lsn 'lsn'
1824 * because the previous snapshot doesn't describe the catalog correctly for
1828 ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid,
1829 XLogRecPtr lsn, Snapshot snap)
1831 ReorderBufferChange *change = ReorderBufferGetChange(rb);
1833 change->data.snapshot = snap;
1834 change->action = REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT;
1836 ReorderBufferQueueChange(rb, xid, lsn, change);
1840 * Setup the base snapshot of a transaction. The base snapshot is the snapshot
1841 * that is used to decode all changes until either this transaction modifies
1842 * the catalog or another catalog modifying transaction commits.
1844 * Needs to be called before any changes are added with
1845 * ReorderBufferQueueChange().
1848 ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid,
1849 XLogRecPtr lsn, Snapshot snap)
1851 ReorderBufferTXN *txn;
1854 txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true);
1855 Assert(txn->base_snapshot == NULL);
1856 Assert(snap != NULL);
1858 txn->base_snapshot = snap;
1859 txn->base_snapshot_lsn = lsn;
1863 * Access the catalog with this CommandId at this point in the changestream.
1865 * May only be called for command ids > 1
1868 ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
1869 XLogRecPtr lsn, CommandId cid)
1871 ReorderBufferChange *change = ReorderBufferGetChange(rb);
1873 change->data.command_id = cid;
1874 change->action = REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID;
1876 ReorderBufferQueueChange(rb, xid, lsn, change);
1881 * Add new (relfilenode, tid) -> (cmin, cmax) mappings.
1884 ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
1885 XLogRecPtr lsn, RelFileNode node,
1886 ItemPointerData tid, CommandId cmin,
1887 CommandId cmax, CommandId combocid)
1889 ReorderBufferChange *change = ReorderBufferGetChange(rb);
1890 ReorderBufferTXN *txn;
1892 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1894 change->data.tuplecid.node = node;
1895 change->data.tuplecid.tid = tid;
1896 change->data.tuplecid.cmin = cmin;
1897 change->data.tuplecid.cmax = cmax;
1898 change->data.tuplecid.combocid = combocid;
1900 change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
1902 dlist_push_tail(&txn->tuplecids, &change->node);
1907 * Setup the invalidation of the toplevel transaction.
1909 * This needs to be done before ReorderBufferCommit is called!
1912 ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid,
1913 XLogRecPtr lsn, Size nmsgs,
1914 SharedInvalidationMessage *msgs)
1916 ReorderBufferTXN *txn;
1918 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1920 if (txn->ninvalidations != 0)
1921 elog(ERROR, "only ever add one set of invalidations");
1925 txn->ninvalidations = nmsgs;
1926 txn->invalidations = (SharedInvalidationMessage *)
1927 MemoryContextAlloc(rb->context,
1928 sizeof(SharedInvalidationMessage) * nmsgs);
1929 memcpy(txn->invalidations, msgs,
1930 sizeof(SharedInvalidationMessage) * nmsgs);
1934 * Apply all invalidations we know. Possibly we only need parts at this point
1935 * in the changestream but we don't know which those are.
1938 ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn)
1942 for (i = 0; i < txn->ninvalidations; i++)
1943 LocalExecuteInvalidationMessage(&txn->invalidations[i]);
1947 * Mark a transaction as containing catalog changes
1950 ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid,
1953 ReorderBufferTXN *txn;
1955 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1957 txn->has_catalog_changes = true;
1961 * Query whether a transaction is already *known* to contain catalog
1962 * changes. This can be wrong until directly before the commit!
1965 ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
1967 ReorderBufferTXN *txn;
1969 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1974 return txn->has_catalog_changes;
1978 * Have we already added the first snapshot?
1981 ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
1983 ReorderBufferTXN *txn;
1985 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1988 /* transaction isn't known yet, ergo no snapshot */
1993 * TODO: It would be a nice improvement if we would check the toplevel
1994 * transaction in subtransactions, but we'd need to keep track of a bit
1997 return txn->base_snapshot != NULL;
2002 * ---------------------------------------
2003 * Disk serialization support
2004 * ---------------------------------------
2008 * Ensure the IO buffer is >= sz.
2011 ReorderBufferSerializeReserve(ReorderBuffer *rb, Size sz)
2013 if (!rb->outbufsize)
2015 rb->outbuf = MemoryContextAlloc(rb->context, sz);
2016 rb->outbufsize = sz;
2018 else if (rb->outbufsize < sz)
2020 rb->outbuf = repalloc(rb->outbuf, sz);
2021 rb->outbufsize = sz;
2026 * Check whether the transaction tx should spill its data to disk.
2029 ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
2032 * TODO: improve accounting so we cheaply can take subtransactions into
2035 if (txn->nentries_mem >= max_changes_in_memory)
2037 ReorderBufferSerializeTXN(rb, txn);
2038 Assert(txn->nentries_mem == 0);
2043 * Spill data of a large transaction (and its subtransactions) to disk.
2046 ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
2048 dlist_iter subtxn_i;
2049 dlist_mutable_iter change_i;
2051 XLogSegNo curOpenSegNo = 0;
2054 elog(DEBUG2, "spill %u changes in XID %u to disk",
2055 (uint32) txn->nentries_mem, txn->xid);
2057 /* do the same to all child TXs */
2058 dlist_foreach(subtxn_i, &txn->subtxns)
2060 ReorderBufferTXN *subtxn;
2062 subtxn = dlist_container(ReorderBufferTXN, node, subtxn_i.cur);
2063 ReorderBufferSerializeTXN(rb, subtxn);
2066 /* serialize changestream */
2067 dlist_foreach_modify(change_i, &txn->changes)
2069 ReorderBufferChange *change;
2071 change = dlist_container(ReorderBufferChange, node, change_i.cur);
2074 * store in segment in which it belongs by start lsn, don't split over
2075 * multiple segments tho
2078 !XLByteInSeg(change->lsn, curOpenSegNo, wal_segment_size))
2080 char path[MAXPGPATH];
2083 CloseTransientFile(fd);
2085 XLByteToSeg(change->lsn, curOpenSegNo, wal_segment_size);
2088 * No need to care about TLIs here, only used during a single run,
2089 * so each LSN only maps to a specific WAL record.
2091 ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
2094 /* open segment, create it if necessary */
2095 fd = OpenTransientFile(path,
2096 O_CREAT | O_WRONLY | O_APPEND | PG_BINARY);
2100 (errcode_for_file_access(),
2101 errmsg("could not open file \"%s\": %m", path)));
2104 ReorderBufferSerializeChange(rb, txn, fd, change);
2105 dlist_delete(&change->node);
2106 ReorderBufferReturnChange(rb, change);
2111 Assert(spilled == txn->nentries_mem);
2112 Assert(dlist_is_empty(&txn->changes));
2113 txn->nentries_mem = 0;
2114 txn->serialized = true;
2117 CloseTransientFile(fd);
2121 * Serialize individual change to disk.
2124 ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2125 int fd, ReorderBufferChange *change)
2127 ReorderBufferDiskChange *ondisk;
2128 Size sz = sizeof(ReorderBufferDiskChange);
2130 ReorderBufferSerializeReserve(rb, sz);
2132 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2133 memcpy(&ondisk->change, change, sizeof(ReorderBufferChange));
2135 switch (change->action)
2137 /* fall through these, they're all similar enough */
2138 case REORDER_BUFFER_CHANGE_INSERT:
2139 case REORDER_BUFFER_CHANGE_UPDATE:
2140 case REORDER_BUFFER_CHANGE_DELETE:
2141 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2144 ReorderBufferTupleBuf *oldtup,
2149 oldtup = change->data.tp.oldtuple;
2150 newtup = change->data.tp.newtuple;
2154 sz += sizeof(HeapTupleData);
2155 oldlen = oldtup->tuple.t_len;
2161 sz += sizeof(HeapTupleData);
2162 newlen = newtup->tuple.t_len;
2166 /* make sure we have enough space */
2167 ReorderBufferSerializeReserve(rb, sz);
2169 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2170 /* might have been reallocated above */
2171 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2175 memcpy(data, &oldtup->tuple, sizeof(HeapTupleData));
2176 data += sizeof(HeapTupleData);
2178 memcpy(data, oldtup->tuple.t_data, oldlen);
2184 memcpy(data, &newtup->tuple, sizeof(HeapTupleData));
2185 data += sizeof(HeapTupleData);
2187 memcpy(data, newtup->tuple.t_data, newlen);
2192 case REORDER_BUFFER_CHANGE_MESSAGE:
2195 Size prefix_size = strlen(change->data.msg.prefix) + 1;
2197 sz += prefix_size + change->data.msg.message_size +
2198 sizeof(Size) + sizeof(Size);
2199 ReorderBufferSerializeReserve(rb, sz);
2201 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2203 /* might have been reallocated above */
2204 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2206 /* write the prefix including the size */
2207 memcpy(data, &prefix_size, sizeof(Size));
2208 data += sizeof(Size);
2209 memcpy(data, change->data.msg.prefix,
2211 data += prefix_size;
2213 /* write the message including the size */
2214 memcpy(data, &change->data.msg.message_size, sizeof(Size));
2215 data += sizeof(Size);
2216 memcpy(data, change->data.msg.message,
2217 change->data.msg.message_size);
2218 data += change->data.msg.message_size;
2222 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2227 snap = change->data.snapshot;
2229 sz += sizeof(SnapshotData) +
2230 sizeof(TransactionId) * snap->xcnt +
2231 sizeof(TransactionId) * snap->subxcnt
2234 /* make sure we have enough space */
2235 ReorderBufferSerializeReserve(rb, sz);
2236 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2237 /* might have been reallocated above */
2238 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2240 memcpy(data, snap, sizeof(SnapshotData));
2241 data += sizeof(SnapshotData);
2245 memcpy(data, snap->xip,
2246 sizeof(TransactionId) * snap->xcnt);
2247 data += sizeof(TransactionId) * snap->xcnt;
2252 memcpy(data, snap->subxip,
2253 sizeof(TransactionId) * snap->subxcnt);
2254 data += sizeof(TransactionId) * snap->subxcnt;
2258 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2259 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2260 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2261 /* ReorderBufferChange contains everything important */
2267 pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_WRITE);
2268 if (write(fd, rb->outbuf, ondisk->size) != ondisk->size)
2270 int save_errno = errno;
2272 CloseTransientFile(fd);
2275 (errcode_for_file_access(),
2276 errmsg("could not write to data file for XID %u: %m",
2279 pgstat_report_wait_end();
2281 Assert(ondisk->change.action == change->action);
2285 * Restore a number of changes spilled to disk back into memory.
2288 ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
2289 int *fd, XLogSegNo *segno)
2292 XLogSegNo last_segno;
2293 dlist_mutable_iter cleanup_iter;
2295 Assert(txn->first_lsn != InvalidXLogRecPtr);
2296 Assert(txn->final_lsn != InvalidXLogRecPtr);
2298 /* free current entries, so we have memory for more */
2299 dlist_foreach_modify(cleanup_iter, &txn->changes)
2301 ReorderBufferChange *cleanup =
2302 dlist_container(ReorderBufferChange, node, cleanup_iter.cur);
2304 dlist_delete(&cleanup->node);
2305 ReorderBufferReturnChange(rb, cleanup);
2307 txn->nentries_mem = 0;
2308 Assert(dlist_is_empty(&txn->changes));
2310 XLByteToSeg(txn->final_lsn, last_segno, wal_segment_size);
2312 while (restored < max_changes_in_memory && *segno <= last_segno)
2315 ReorderBufferDiskChange *ondisk;
2319 char path[MAXPGPATH];
2323 XLByteToSeg(txn->first_lsn, *segno, wal_segment_size);
2325 Assert(*segno != 0 || dlist_is_empty(&txn->changes));
2328 * No need to care about TLIs here, only used during a single run,
2329 * so each LSN only maps to a specific WAL record.
2331 ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
2334 *fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
2335 if (*fd < 0 && errno == ENOENT)
2343 (errcode_for_file_access(),
2344 errmsg("could not open file \"%s\": %m",
2349 * Read the statically sized part of a change which has information
2350 * about the total size. If we couldn't read a record, we're at the
2353 ReorderBufferSerializeReserve(rb, sizeof(ReorderBufferDiskChange));
2354 pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_READ);
2355 readBytes = read(*fd, rb->outbuf, sizeof(ReorderBufferDiskChange));
2356 pgstat_report_wait_end();
2361 CloseTransientFile(*fd);
2366 else if (readBytes < 0)
2368 (errcode_for_file_access(),
2369 errmsg("could not read from reorderbuffer spill file: %m")));
2370 else if (readBytes != sizeof(ReorderBufferDiskChange))
2372 (errcode_for_file_access(),
2373 errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2375 (uint32) sizeof(ReorderBufferDiskChange))));
2377 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2379 ReorderBufferSerializeReserve(rb,
2380 sizeof(ReorderBufferDiskChange) + ondisk->size);
2381 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2383 pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_READ);
2384 readBytes = read(*fd, rb->outbuf + sizeof(ReorderBufferDiskChange),
2385 ondisk->size - sizeof(ReorderBufferDiskChange));
2386 pgstat_report_wait_end();
2390 (errcode_for_file_access(),
2391 errmsg("could not read from reorderbuffer spill file: %m")));
2392 else if (readBytes != ondisk->size - sizeof(ReorderBufferDiskChange))
2394 (errcode_for_file_access(),
2395 errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2397 (uint32) (ondisk->size - sizeof(ReorderBufferDiskChange)))));
2400 * ok, read a full change from disk, now restore it into proper
2403 ReorderBufferRestoreChange(rb, txn, rb->outbuf);
2411 * Convert change from its on-disk format to in-memory format and queue it onto
2412 * the TXN's ->changes list.
2414 * Note: although "data" is declared char*, at entry it points to a
2415 * maxalign'd buffer, making it safe in most of this function to assume
2416 * that the pointed-to data is suitably aligned for direct access.
2419 ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2422 ReorderBufferDiskChange *ondisk;
2423 ReorderBufferChange *change;
2425 ondisk = (ReorderBufferDiskChange *) data;
2427 change = ReorderBufferGetChange(rb);
2429 /* copy static part */
2430 memcpy(change, &ondisk->change, sizeof(ReorderBufferChange));
2432 data += sizeof(ReorderBufferDiskChange);
2434 /* restore individual stuff */
2435 switch (change->action)
2437 /* fall through these, they're all similar enough */
2438 case REORDER_BUFFER_CHANGE_INSERT:
2439 case REORDER_BUFFER_CHANGE_UPDATE:
2440 case REORDER_BUFFER_CHANGE_DELETE:
2441 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2442 if (change->data.tp.oldtuple)
2444 uint32 tuplelen = ((HeapTuple) data)->t_len;
2446 change->data.tp.oldtuple =
2447 ReorderBufferGetTupleBuf(rb, tuplelen - SizeofHeapTupleHeader);
2449 /* restore ->tuple */
2450 memcpy(&change->data.tp.oldtuple->tuple, data,
2451 sizeof(HeapTupleData));
2452 data += sizeof(HeapTupleData);
2454 /* reset t_data pointer into the new tuplebuf */
2455 change->data.tp.oldtuple->tuple.t_data =
2456 ReorderBufferTupleBufData(change->data.tp.oldtuple);
2458 /* restore tuple data itself */
2459 memcpy(change->data.tp.oldtuple->tuple.t_data, data, tuplelen);
2463 if (change->data.tp.newtuple)
2465 /* here, data might not be suitably aligned! */
2468 memcpy(&tuplelen, data + offsetof(HeapTupleData, t_len),
2471 change->data.tp.newtuple =
2472 ReorderBufferGetTupleBuf(rb, tuplelen - SizeofHeapTupleHeader);
2474 /* restore ->tuple */
2475 memcpy(&change->data.tp.newtuple->tuple, data,
2476 sizeof(HeapTupleData));
2477 data += sizeof(HeapTupleData);
2479 /* reset t_data pointer into the new tuplebuf */
2480 change->data.tp.newtuple->tuple.t_data =
2481 ReorderBufferTupleBufData(change->data.tp.newtuple);
2483 /* restore tuple data itself */
2484 memcpy(change->data.tp.newtuple->tuple.t_data, data, tuplelen);
2489 case REORDER_BUFFER_CHANGE_MESSAGE:
2494 memcpy(&prefix_size, data, sizeof(Size));
2495 data += sizeof(Size);
2496 change->data.msg.prefix = MemoryContextAlloc(rb->context,
2498 memcpy(change->data.msg.prefix, data, prefix_size);
2499 Assert(change->data.msg.prefix[prefix_size - 1] == '\0');
2500 data += prefix_size;
2502 /* read the message */
2503 memcpy(&change->data.msg.message_size, data, sizeof(Size));
2504 data += sizeof(Size);
2505 change->data.msg.message = MemoryContextAlloc(rb->context,
2506 change->data.msg.message_size);
2507 memcpy(change->data.msg.message, data,
2508 change->data.msg.message_size);
2509 data += change->data.msg.message_size;
2513 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2519 oldsnap = (Snapshot) data;
2521 size = sizeof(SnapshotData) +
2522 sizeof(TransactionId) * oldsnap->xcnt +
2523 sizeof(TransactionId) * (oldsnap->subxcnt + 0);
2525 change->data.snapshot = MemoryContextAllocZero(rb->context, size);
2527 newsnap = change->data.snapshot;
2529 memcpy(newsnap, data, size);
2530 newsnap->xip = (TransactionId *)
2531 (((char *) newsnap) + sizeof(SnapshotData));
2532 newsnap->subxip = newsnap->xip + newsnap->xcnt;
2533 newsnap->copied = true;
2536 /* the base struct contains all the data, easy peasy */
2537 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2538 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2539 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2543 dlist_push_tail(&txn->changes, &change->node);
2544 txn->nentries_mem++;
2548 * Remove all on-disk stored for the passed in transaction.
2551 ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
2557 Assert(txn->first_lsn != InvalidXLogRecPtr);
2558 Assert(txn->final_lsn != InvalidXLogRecPtr);
2560 XLByteToSeg(txn->first_lsn, first, wal_segment_size);
2561 XLByteToSeg(txn->final_lsn, last, wal_segment_size);
2563 /* iterate over all possible filenames, and delete them */
2564 for (cur = first; cur <= last; cur++)
2566 char path[MAXPGPATH];
2568 ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid, cur);
2569 if (unlink(path) != 0 && errno != ENOENT)
2571 (errcode_for_file_access(),
2572 errmsg("could not remove file \"%s\": %m", path)));
2577 * Remove any leftover serialized reorder buffers from a slot directory after a
2578 * prior crash or decoding session exit.
2581 ReorderBufferCleanupSerializedTXNs(const char *slotname)
2584 struct dirent *spill_de;
2585 struct stat statbuf;
2586 char path[MAXPGPATH * 2 + 12];
2588 sprintf(path, "pg_replslot/%s", slotname);
2590 /* we're only handling directories here, skip if it's not ours */
2591 if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
2594 spill_dir = AllocateDir(path);
2595 while ((spill_de = ReadDirExtended(spill_dir, path, INFO)) != NULL)
2597 /* only look at names that can be ours */
2598 if (strncmp(spill_de->d_name, "xid", 3) == 0)
2600 snprintf(path, sizeof(path),
2601 "pg_replslot/%s/%s", slotname,
2604 if (unlink(path) != 0)
2606 (errcode_for_file_access(),
2607 errmsg("could not remove file \"%s\" during removal of pg_replslot/%s/*.xid: %m",
2615 * Given a replication slot, transaction ID and segment number, fill in the
2616 * corresponding spill file into 'path', which is a caller-owned buffer of size
2617 * at least MAXPGPATH.
2620 ReorderBufferSerializedPath(char *path, ReplicationSlot *slot, TransactionId xid,
2625 XLogSegNoOffsetToRecPtr(segno, 0, recptr, wal_segment_size);
2627 snprintf(path, MAXPGPATH, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2628 NameStr(MyReplicationSlot->data.name),
2630 (uint32) (recptr >> 32), (uint32) recptr);
2634 * Delete all data spilled to disk after we've restarted/crashed. It will be
2635 * recreated when the respective slots are reused.
2638 StartupReorderBuffer(void)
2641 struct dirent *logical_de;
2643 logical_dir = AllocateDir("pg_replslot");
2644 while ((logical_de = ReadDir(logical_dir, "pg_replslot")) != NULL)
2646 if (strcmp(logical_de->d_name, ".") == 0 ||
2647 strcmp(logical_de->d_name, "..") == 0)
2650 /* if it cannot be a slot, skip the directory */
2651 if (!ReplicationSlotValidateName(logical_de->d_name, DEBUG2))
2655 * ok, has to be a surviving logical slot, iterate and delete
2656 * everything starting with xid-*
2658 ReorderBufferCleanupSerializedTXNs(logical_de->d_name);
2660 FreeDir(logical_dir);
2663 /* ---------------------------------------
2664 * toast reassembly support
2665 * ---------------------------------------
2669 * Initialize per tuple toast reconstruction support.
2672 ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
2676 Assert(txn->toast_hash == NULL);
2678 memset(&hash_ctl, 0, sizeof(hash_ctl));
2679 hash_ctl.keysize = sizeof(Oid);
2680 hash_ctl.entrysize = sizeof(ReorderBufferToastEnt);
2681 hash_ctl.hcxt = rb->context;
2682 txn->toast_hash = hash_create("ReorderBufferToastHash", 5, &hash_ctl,
2683 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
2687 * Per toast-chunk handling for toast reconstruction
2689 * Appends a toast chunk so we can reconstruct it when the tuple "owning" the
2690 * toasted Datum comes along.
2693 ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
2694 Relation relation, ReorderBufferChange *change)
2696 ReorderBufferToastEnt *ent;
2697 ReorderBufferTupleBuf *newtup;
2702 TupleDesc desc = RelationGetDescr(relation);
2706 if (txn->toast_hash == NULL)
2707 ReorderBufferToastInitHash(rb, txn);
2709 Assert(IsToastRelation(relation));
2711 newtup = change->data.tp.newtuple;
2712 chunk_id = DatumGetObjectId(fastgetattr(&newtup->tuple, 1, desc, &isnull));
2714 chunk_seq = DatumGetInt32(fastgetattr(&newtup->tuple, 2, desc, &isnull));
2717 ent = (ReorderBufferToastEnt *)
2718 hash_search(txn->toast_hash,
2725 Assert(ent->chunk_id == chunk_id);
2726 ent->num_chunks = 0;
2727 ent->last_chunk_seq = 0;
2729 ent->reconstructed = NULL;
2730 dlist_init(&ent->chunks);
2733 elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq 0",
2734 chunk_seq, chunk_id);
2736 else if (found && chunk_seq != ent->last_chunk_seq + 1)
2737 elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq %d",
2738 chunk_seq, chunk_id, ent->last_chunk_seq + 1);
2740 chunk = DatumGetPointer(fastgetattr(&newtup->tuple, 3, desc, &isnull));
2743 /* calculate size so we can allocate the right size at once later */
2744 if (!VARATT_IS_EXTENDED(chunk))
2745 chunksize = VARSIZE(chunk) - VARHDRSZ;
2746 else if (VARATT_IS_SHORT(chunk))
2747 /* could happen due to heap_form_tuple doing its thing */
2748 chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT;
2750 elog(ERROR, "unexpected type of toast chunk");
2752 ent->size += chunksize;
2753 ent->last_chunk_seq = chunk_seq;
2755 dlist_push_tail(&ent->chunks, &change->node);
2759 * Rejigger change->newtuple to point to in-memory toast tuples instead to
2760 * on-disk toast tuples that may not longer exist (think DROP TABLE or VACUUM).
2762 * We cannot replace unchanged toast tuples though, so those will still point
2763 * to on-disk toast data.
2766 ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
2767 Relation relation, ReorderBufferChange *change)
2776 TupleDesc toast_desc;
2777 MemoryContext oldcontext;
2778 ReorderBufferTupleBuf *newtup;
2780 /* no toast tuples changed */
2781 if (txn->toast_hash == NULL)
2784 oldcontext = MemoryContextSwitchTo(rb->context);
2786 /* we should only have toast tuples in an INSERT or UPDATE */
2787 Assert(change->data.tp.newtuple);
2789 desc = RelationGetDescr(relation);
2791 toast_rel = RelationIdGetRelation(relation->rd_rel->reltoastrelid);
2792 toast_desc = RelationGetDescr(toast_rel);
2794 /* should we allocate from stack instead? */
2795 attrs = palloc0(sizeof(Datum) * desc->natts);
2796 isnull = palloc0(sizeof(bool) * desc->natts);
2797 free = palloc0(sizeof(bool) * desc->natts);
2799 newtup = change->data.tp.newtuple;
2801 heap_deform_tuple(&newtup->tuple, desc, attrs, isnull);
2803 for (natt = 0; natt < desc->natts; natt++)
2805 Form_pg_attribute attr = TupleDescAttr(desc, natt);
2806 ReorderBufferToastEnt *ent;
2807 struct varlena *varlena;
2809 /* va_rawsize is the size of the original datum -- including header */
2810 struct varatt_external toast_pointer;
2811 struct varatt_indirect redirect_pointer;
2812 struct varlena *new_datum = NULL;
2813 struct varlena *reconstructed;
2817 /* system columns aren't toasted */
2818 if (attr->attnum < 0)
2821 if (attr->attisdropped)
2824 /* not a varlena datatype */
2825 if (attr->attlen != -1)
2832 /* ok, we know we have a toast datum */
2833 varlena = (struct varlena *) DatumGetPointer(attrs[natt]);
2835 /* no need to do anything if the tuple isn't external */
2836 if (!VARATT_IS_EXTERNAL(varlena))
2839 VARATT_EXTERNAL_GET_POINTER(toast_pointer, varlena);
2842 * Check whether the toast tuple changed, replace if so.
2844 ent = (ReorderBufferToastEnt *)
2845 hash_search(txn->toast_hash,
2846 (void *) &toast_pointer.va_valueid,
2853 (struct varlena *) palloc0(INDIRECT_POINTER_SIZE);
2857 reconstructed = palloc0(toast_pointer.va_rawsize);
2859 ent->reconstructed = reconstructed;
2861 /* stitch toast tuple back together from its parts */
2862 dlist_foreach(it, &ent->chunks)
2865 ReorderBufferChange *cchange;
2866 ReorderBufferTupleBuf *ctup;
2869 cchange = dlist_container(ReorderBufferChange, node, it.cur);
2870 ctup = cchange->data.tp.newtuple;
2871 chunk = DatumGetPointer(
2872 fastgetattr(&ctup->tuple, 3, toast_desc, &isnull));
2875 Assert(!VARATT_IS_EXTERNAL(chunk));
2876 Assert(!VARATT_IS_SHORT(chunk));
2878 memcpy(VARDATA(reconstructed) + data_done,
2880 VARSIZE(chunk) - VARHDRSZ);
2881 data_done += VARSIZE(chunk) - VARHDRSZ;
2883 Assert(data_done == toast_pointer.va_extsize);
2885 /* make sure its marked as compressed or not */
2886 if (VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer))
2887 SET_VARSIZE_COMPRESSED(reconstructed, data_done + VARHDRSZ);
2889 SET_VARSIZE(reconstructed, data_done + VARHDRSZ);
2891 memset(&redirect_pointer, 0, sizeof(redirect_pointer));
2892 redirect_pointer.pointer = reconstructed;
2894 SET_VARTAG_EXTERNAL(new_datum, VARTAG_INDIRECT);
2895 memcpy(VARDATA_EXTERNAL(new_datum), &redirect_pointer,
2896 sizeof(redirect_pointer));
2898 attrs[natt] = PointerGetDatum(new_datum);
2902 * Build tuple in separate memory & copy tuple back into the tuplebuf
2903 * passed to the output plugin. We can't directly heap_fill_tuple() into
2904 * the tuplebuf because attrs[] will point back into the current content.
2906 tmphtup = heap_form_tuple(desc, attrs, isnull);
2907 Assert(newtup->tuple.t_len <= MaxHeapTupleSize);
2908 Assert(ReorderBufferTupleBufData(newtup) == newtup->tuple.t_data);
2910 memcpy(newtup->tuple.t_data, tmphtup->t_data, tmphtup->t_len);
2911 newtup->tuple.t_len = tmphtup->t_len;
2914 * free resources we won't further need, more persistent stuff will be
2915 * free'd in ReorderBufferToastReset().
2917 RelationClose(toast_rel);
2919 for (natt = 0; natt < desc->natts; natt++)
2922 pfree(DatumGetPointer(attrs[natt]));
2928 MemoryContextSwitchTo(oldcontext);
2932 * Free all resources allocated for toast reconstruction.
2935 ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn)
2937 HASH_SEQ_STATUS hstat;
2938 ReorderBufferToastEnt *ent;
2940 if (txn->toast_hash == NULL)
2943 /* sequentially walk over the hash and free everything */
2944 hash_seq_init(&hstat, txn->toast_hash);
2945 while ((ent = (ReorderBufferToastEnt *) hash_seq_search(&hstat)) != NULL)
2947 dlist_mutable_iter it;
2949 if (ent->reconstructed != NULL)
2950 pfree(ent->reconstructed);
2952 dlist_foreach_modify(it, &ent->chunks)
2954 ReorderBufferChange *change =
2955 dlist_container(ReorderBufferChange, node, it.cur);
2957 dlist_delete(&change->node);
2958 ReorderBufferReturnChange(rb, change);
2962 hash_destroy(txn->toast_hash);
2963 txn->toast_hash = NULL;
2967 /* ---------------------------------------
2968 * Visibility support for logical decoding
2971 * Lookup actual cmin/cmax values when using decoding snapshot. We can't
2972 * always rely on stored cmin/cmax values because of two scenarios:
2974 * * A tuple got changed multiple times during a single transaction and thus
2975 * has got a combocid. Combocid's are only valid for the duration of a
2976 * single transaction.
2977 * * A tuple with a cmin but no cmax (and thus no combocid) got
2978 * deleted/updated in another transaction than the one which created it
2979 * which we are looking at right now. As only one of cmin, cmax or combocid
2980 * is actually stored in the heap we don't have access to the value we
2983 * To resolve those problems we have a per-transaction hash of (cmin,
2984 * cmax) tuples keyed by (relfilenode, ctid) which contains the actual
2985 * (cmin, cmax) values. That also takes care of combocids by simply
2986 * not caring about them at all. As we have the real cmin/cmax values
2987 * combocids aren't interesting.
2989 * As we only care about catalog tuples here the overhead of this
2990 * hashtable should be acceptable.
2992 * Heap rewrites complicate this a bit, check rewriteheap.c for
2994 * -------------------------------------------------------------------------
2997 /* struct for qsort()ing mapping files by lsn somewhat efficiently */
2998 typedef struct RewriteMappingFile
3001 char fname[MAXPGPATH];
3002 } RewriteMappingFile;
3006 DisplayMapping(HTAB *tuplecid_data)
3008 HASH_SEQ_STATUS hstat;
3009 ReorderBufferTupleCidEnt *ent;
3011 hash_seq_init(&hstat, tuplecid_data);
3012 while ((ent = (ReorderBufferTupleCidEnt *) hash_seq_search(&hstat)) != NULL)
3014 elog(DEBUG3, "mapping: node: %u/%u/%u tid: %u/%u cmin: %u, cmax: %u",
3015 ent->key.relnode.dbNode,
3016 ent->key.relnode.spcNode,
3017 ent->key.relnode.relNode,
3018 ItemPointerGetBlockNumber(&ent->key.tid),
3019 ItemPointerGetOffsetNumber(&ent->key.tid),
3028 * Apply a single mapping file to tuplecid_data.
3030 * The mapping file has to have been verified to be a) committed b) for our
3031 * transaction c) applied in LSN order.
3034 ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname)
3036 char path[MAXPGPATH];
3039 LogicalRewriteMappingData map;
3041 sprintf(path, "pg_logical/mappings/%s", fname);
3042 fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
3045 (errcode_for_file_access(),
3046 errmsg("could not open file \"%s\": %m", path)));
3050 ReorderBufferTupleCidKey key;
3051 ReorderBufferTupleCidEnt *ent;
3052 ReorderBufferTupleCidEnt *new_ent;
3055 /* be careful about padding */
3056 memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
3058 /* read all mappings till the end of the file */
3059 pgstat_report_wait_start(WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ);
3060 readBytes = read(fd, &map, sizeof(LogicalRewriteMappingData));
3061 pgstat_report_wait_end();
3065 (errcode_for_file_access(),
3066 errmsg("could not read file \"%s\": %m",
3068 else if (readBytes == 0) /* EOF */
3070 else if (readBytes != sizeof(LogicalRewriteMappingData))
3072 (errcode_for_file_access(),
3073 errmsg("could not read from file \"%s\": read %d instead of %d bytes",
3075 (int32) sizeof(LogicalRewriteMappingData))));
3077 key.relnode = map.old_node;
3078 ItemPointerCopy(&map.old_tid,
3082 ent = (ReorderBufferTupleCidEnt *)
3083 hash_search(tuplecid_data,
3088 /* no existing mapping, no need to update */
3092 key.relnode = map.new_node;
3093 ItemPointerCopy(&map.new_tid,
3096 new_ent = (ReorderBufferTupleCidEnt *)
3097 hash_search(tuplecid_data,
3105 * Make sure the existing mapping makes sense. We sometime update
3106 * old records that did not yet have a cmax (e.g. pg_class' own
3107 * entry while rewriting it) during rewrites, so allow that.
3109 Assert(ent->cmin == InvalidCommandId || ent->cmin == new_ent->cmin);
3110 Assert(ent->cmax == InvalidCommandId || ent->cmax == new_ent->cmax);
3114 /* update mapping */
3115 new_ent->cmin = ent->cmin;
3116 new_ent->cmax = ent->cmax;
3117 new_ent->combocid = ent->combocid;
3124 * Check whether the TransactionOId 'xid' is in the pre-sorted array 'xip'.
3127 TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num)
3129 return bsearch(&xid, xip, num,
3130 sizeof(TransactionId), xidComparator) != NULL;
3134 * qsort() comparator for sorting RewriteMappingFiles in LSN order.
3137 file_sort_by_lsn(const void *a_p, const void *b_p)
3139 RewriteMappingFile *a = *(RewriteMappingFile **) a_p;
3140 RewriteMappingFile *b = *(RewriteMappingFile **) b_p;
3142 if (a->lsn < b->lsn)
3144 else if (a->lsn > b->lsn)
3150 * Apply any existing logical remapping files if there are any targeted at our
3151 * transaction for relid.
3154 UpdateLogicalMappings(HTAB *tuplecid_data, Oid relid, Snapshot snapshot)
3157 struct dirent *mapping_de;
3160 RewriteMappingFile **files_a;
3162 Oid dboid = IsSharedRelation(relid) ? InvalidOid : MyDatabaseId;
3164 mapping_dir = AllocateDir("pg_logical/mappings");
3165 while ((mapping_de = ReadDir(mapping_dir, "pg_logical/mappings")) != NULL)
3169 TransactionId f_mapped_xid;
3170 TransactionId f_create_xid;
3174 RewriteMappingFile *f;
3176 if (strcmp(mapping_de->d_name, ".") == 0 ||
3177 strcmp(mapping_de->d_name, "..") == 0)
3180 /* Ignore files that aren't ours */
3181 if (strncmp(mapping_de->d_name, "map-", 4) != 0)
3184 if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
3185 &f_dboid, &f_relid, &f_hi, &f_lo,
3186 &f_mapped_xid, &f_create_xid) != 6)
3187 elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
3189 f_lsn = ((uint64) f_hi) << 32 | f_lo;
3191 /* mapping for another database */
3192 if (f_dboid != dboid)
3195 /* mapping for another relation */
3196 if (f_relid != relid)
3199 /* did the creating transaction abort? */
3200 if (!TransactionIdDidCommit(f_create_xid))
3203 /* not for our transaction */
3204 if (!TransactionIdInArray(f_mapped_xid, snapshot->subxip, snapshot->subxcnt))
3207 /* ok, relevant, queue for apply */
3208 f = palloc(sizeof(RewriteMappingFile));
3210 strcpy(f->fname, mapping_de->d_name);
3211 files = lappend(files, f);
3213 FreeDir(mapping_dir);
3215 /* build array we can easily sort */
3216 files_a = palloc(list_length(files) * sizeof(RewriteMappingFile *));
3218 foreach(file, files)
3220 files_a[off++] = lfirst(file);
3223 /* sort files so we apply them in LSN order */
3224 qsort(files_a, list_length(files), sizeof(RewriteMappingFile *),
3227 for (off = 0; off < list_length(files); off++)
3229 RewriteMappingFile *f = files_a[off];
3231 elog(DEBUG1, "applying mapping: \"%s\" in %u", f->fname,
3232 snapshot->subxip[0]);
3233 ApplyLogicalMappingFile(tuplecid_data, relid, f->fname);
3239 * Lookup cmin/cmax of a tuple, during logical decoding where we can't rely on
3243 ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data,
3245 HeapTuple htup, Buffer buffer,
3246 CommandId *cmin, CommandId *cmax)
3248 ReorderBufferTupleCidKey key;
3249 ReorderBufferTupleCidEnt *ent;
3251 BlockNumber blockno;
3252 bool updated_mapping = false;
3254 /* be careful about padding */
3255 memset(&key, 0, sizeof(key));
3257 Assert(!BufferIsLocal(buffer));
3260 * get relfilenode from the buffer, no convenient way to access it other
3263 BufferGetTag(buffer, &key.relnode, &forkno, &blockno);
3265 /* tuples can only be in the main fork */
3266 Assert(forkno == MAIN_FORKNUM);
3267 Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self));
3269 ItemPointerCopy(&htup->t_self,
3273 ent = (ReorderBufferTupleCidEnt *)
3274 hash_search(tuplecid_data,
3280 * failed to find a mapping, check whether the table was rewritten and
3281 * apply mapping if so, but only do that once - there can be no new
3282 * mappings while we are in here since we have to hold a lock on the
3285 if (ent == NULL && !updated_mapping)
3287 UpdateLogicalMappings(tuplecid_data, htup->t_tableOid, snapshot);
3288 /* now check but don't update for a mapping again */
3289 updated_mapping = true;
3292 else if (ent == NULL)