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);
168 static void ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
169 ReorderBufferTXN *subtxn);
171 static void AssertTXNLsnOrder(ReorderBuffer *rb);
173 /* ---------------------------------------
174 * support functions for lsn-order iterating over the ->changes of a
175 * transaction and its subtransactions
177 * used for iteration over the k-way heap merge of a transaction and its
179 * ---------------------------------------
181 static ReorderBufferIterTXNState *ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn);
182 static ReorderBufferChange *ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state);
183 static void ReorderBufferIterTXNFinish(ReorderBuffer *rb,
184 ReorderBufferIterTXNState *state);
185 static void ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn);
188 * ---------------------------------------
189 * Disk serialization support functions
190 * ---------------------------------------
192 static void ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
193 static void ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
194 static void ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
195 int fd, ReorderBufferChange *change);
196 static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
197 int *fd, XLogSegNo *segno);
198 static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
200 static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn);
201 static void ReorderBufferCleanupSerializedTXNs(const char *slotname);
202 static void ReorderBufferSerializedPath(char *path, ReplicationSlot *slot,
203 TransactionId xid, XLogSegNo segno);
205 static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap);
206 static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
207 ReorderBufferTXN *txn, CommandId cid);
209 /* ---------------------------------------
210 * toast reassembly support
211 * ---------------------------------------
213 static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn);
214 static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn);
215 static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
216 Relation relation, ReorderBufferChange *change);
217 static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
218 Relation relation, ReorderBufferChange *change);
222 * Allocate a new ReorderBuffer and clean out any old serialized state from
223 * prior ReorderBuffer instances for the same slot.
226 ReorderBufferAllocate(void)
228 ReorderBuffer *buffer;
230 MemoryContext new_ctx;
232 Assert(MyReplicationSlot != NULL);
234 /* allocate memory in own context, to have better accountability */
235 new_ctx = AllocSetContextCreate(CurrentMemoryContext,
237 ALLOCSET_DEFAULT_SIZES);
240 (ReorderBuffer *) MemoryContextAlloc(new_ctx, sizeof(ReorderBuffer));
242 memset(&hash_ctl, 0, sizeof(hash_ctl));
244 buffer->context = new_ctx;
246 buffer->change_context = SlabContextCreate(new_ctx,
248 SLAB_DEFAULT_BLOCK_SIZE,
249 sizeof(ReorderBufferChange));
251 buffer->txn_context = SlabContextCreate(new_ctx,
253 SLAB_DEFAULT_BLOCK_SIZE,
254 sizeof(ReorderBufferTXN));
256 buffer->tup_context = GenerationContextCreate(new_ctx,
258 SLAB_LARGE_BLOCK_SIZE);
260 hash_ctl.keysize = sizeof(TransactionId);
261 hash_ctl.entrysize = sizeof(ReorderBufferTXNByIdEnt);
262 hash_ctl.hcxt = buffer->context;
264 buffer->by_txn = hash_create("ReorderBufferByXid", 1000, &hash_ctl,
265 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
267 buffer->by_txn_last_xid = InvalidTransactionId;
268 buffer->by_txn_last_txn = NULL;
270 buffer->outbuf = NULL;
271 buffer->outbufsize = 0;
273 buffer->current_restart_decoding_lsn = InvalidXLogRecPtr;
275 dlist_init(&buffer->toplevel_by_lsn);
276 dlist_init(&buffer->txns_by_base_snapshot_lsn);
279 * Ensure there's no stale data from prior uses of this slot, in case some
280 * prior exit avoided calling ReorderBufferFree. Failure to do this can
281 * produce duplicated txns, and it's very cheap if there's nothing there.
283 ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name));
289 * Free a ReorderBuffer
292 ReorderBufferFree(ReorderBuffer *rb)
294 MemoryContext context = rb->context;
297 * We free separately allocated data by entirely scrapping reorderbuffer's
300 MemoryContextDelete(context);
302 /* Free disk space used by unconsumed reorder buffers */
303 ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name));
307 * Get an unused, possibly preallocated, ReorderBufferTXN.
309 static ReorderBufferTXN *
310 ReorderBufferGetTXN(ReorderBuffer *rb)
312 ReorderBufferTXN *txn;
314 txn = (ReorderBufferTXN *)
315 MemoryContextAlloc(rb->txn_context, sizeof(ReorderBufferTXN));
317 memset(txn, 0, sizeof(ReorderBufferTXN));
319 dlist_init(&txn->changes);
320 dlist_init(&txn->tuplecids);
321 dlist_init(&txn->subtxns);
327 * Free a ReorderBufferTXN.
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 fresh 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.
375 ReorderBufferReturnChange(ReorderBuffer *rb, ReorderBufferChange *change)
377 /* free contained data */
378 switch (change->action)
380 case REORDER_BUFFER_CHANGE_INSERT:
381 case REORDER_BUFFER_CHANGE_UPDATE:
382 case REORDER_BUFFER_CHANGE_DELETE:
383 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
384 if (change->data.tp.newtuple)
386 ReorderBufferReturnTupleBuf(rb, change->data.tp.newtuple);
387 change->data.tp.newtuple = NULL;
390 if (change->data.tp.oldtuple)
392 ReorderBufferReturnTupleBuf(rb, change->data.tp.oldtuple);
393 change->data.tp.oldtuple = NULL;
396 case REORDER_BUFFER_CHANGE_MESSAGE:
397 if (change->data.msg.prefix != NULL)
398 pfree(change->data.msg.prefix);
399 change->data.msg.prefix = NULL;
400 if (change->data.msg.message != NULL)
401 pfree(change->data.msg.message);
402 change->data.msg.message = NULL;
404 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
405 if (change->data.snapshot)
407 ReorderBufferFreeSnap(rb, change->data.snapshot);
408 change->data.snapshot = NULL;
411 /* no data in addition to the struct itself */
412 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
413 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
414 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
415 case REORDER_BUFFER_CHANGE_TRUNCATE:
423 * Get a fresh ReorderBufferTupleBuf fitting at least a tuple of size
424 * tuple_len (excluding header overhead).
426 ReorderBufferTupleBuf *
427 ReorderBufferGetTupleBuf(ReorderBuffer *rb, Size tuple_len)
429 ReorderBufferTupleBuf *tuple;
432 alloc_len = tuple_len + SizeofHeapTupleHeader;
434 tuple = (ReorderBufferTupleBuf *)
435 MemoryContextAlloc(rb->tup_context,
436 sizeof(ReorderBufferTupleBuf) +
437 MAXIMUM_ALIGNOF + alloc_len);
438 tuple->alloc_tuple_size = alloc_len;
439 tuple->tuple.t_data = ReorderBufferTupleBufData(tuple);
445 * Free an ReorderBufferTupleBuf.
448 ReorderBufferReturnTupleBuf(ReorderBuffer *rb, ReorderBufferTupleBuf *tuple)
454 * Return the ReorderBufferTXN from the given buffer, specified by Xid.
455 * If create is true, and a transaction doesn't already exist, create it
456 * (with the given LSN, and as top transaction if that's specified);
457 * when this happens, is_new is set to true.
459 static ReorderBufferTXN *
460 ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create,
461 bool *is_new, XLogRecPtr lsn, bool create_as_top)
463 ReorderBufferTXN *txn;
464 ReorderBufferTXNByIdEnt *ent;
467 Assert(TransactionIdIsValid(xid));
470 * Check the one-entry lookup cache first
472 if (TransactionIdIsValid(rb->by_txn_last_xid) &&
473 rb->by_txn_last_xid == xid)
475 txn = rb->by_txn_last_txn;
479 /* found it, and it's valid */
486 * cached as non-existent, and asked not to create? Then nothing else
491 /* otherwise fall through to create it */
495 * If the cache wasn't hit or it yielded an "does-not-exist" and we want
496 * to create an entry.
499 /* search the lookup table */
500 ent = (ReorderBufferTXNByIdEnt *)
501 hash_search(rb->by_txn,
503 create ? HASH_ENTER : HASH_FIND,
509 /* initialize the new entry, if creation was requested */
511 Assert(lsn != InvalidXLogRecPtr);
513 ent->txn = ReorderBufferGetTXN(rb);
516 txn->first_lsn = lsn;
517 txn->restart_decoding_lsn = rb->current_restart_decoding_lsn;
521 dlist_push_tail(&rb->toplevel_by_lsn, &txn->node);
522 AssertTXNLsnOrder(rb);
526 txn = NULL; /* not found and not asked to create */
529 rb->by_txn_last_xid = xid;
530 rb->by_txn_last_txn = txn;
535 Assert(!create || txn != NULL);
540 * Queue a change into a transaction so it can be replayed upon commit.
543 ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
544 ReorderBufferChange *change)
546 ReorderBufferTXN *txn;
548 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
551 Assert(InvalidXLogRecPtr != lsn);
552 dlist_push_tail(&txn->changes, &change->node);
556 ReorderBufferCheckSerializeTXN(rb, txn);
560 * Queue message into a transaction so it can be processed upon commit.
563 ReorderBufferQueueMessage(ReorderBuffer *rb, TransactionId xid,
564 Snapshot snapshot, XLogRecPtr lsn,
565 bool transactional, const char *prefix,
566 Size message_size, const char *message)
570 MemoryContext oldcontext;
571 ReorderBufferChange *change;
573 Assert(xid != InvalidTransactionId);
575 oldcontext = MemoryContextSwitchTo(rb->context);
577 change = ReorderBufferGetChange(rb);
578 change->action = REORDER_BUFFER_CHANGE_MESSAGE;
579 change->data.msg.prefix = pstrdup(prefix);
580 change->data.msg.message_size = message_size;
581 change->data.msg.message = palloc(message_size);
582 memcpy(change->data.msg.message, message, message_size);
584 ReorderBufferQueueChange(rb, xid, lsn, change);
586 MemoryContextSwitchTo(oldcontext);
590 ReorderBufferTXN *txn = NULL;
591 volatile Snapshot snapshot_now = snapshot;
593 if (xid != InvalidTransactionId)
594 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
596 /* setup snapshot to allow catalog access */
597 SetupHistoricSnapshot(snapshot_now, NULL);
600 rb->message(rb, txn, lsn, false, prefix, message_size, message);
602 TeardownHistoricSnapshot(false);
606 TeardownHistoricSnapshot(true);
615 * Verify LSN ordering of transaction lists in the reorderbuffer
617 * Other LSN-related invariants are checked too.
619 * No-op if assertions are not in use.
622 AssertTXNLsnOrder(ReorderBuffer *rb)
624 #ifdef USE_ASSERT_CHECKING
626 XLogRecPtr prev_first_lsn = InvalidXLogRecPtr;
627 XLogRecPtr prev_base_snap_lsn = InvalidXLogRecPtr;
629 dlist_foreach(iter, &rb->toplevel_by_lsn)
631 ReorderBufferTXN *cur_txn = dlist_container(ReorderBufferTXN, node,
634 /* start LSN must be set */
635 Assert(cur_txn->first_lsn != InvalidXLogRecPtr);
637 /* If there is an end LSN, it must be higher than start LSN */
638 if (cur_txn->end_lsn != InvalidXLogRecPtr)
639 Assert(cur_txn->first_lsn <= cur_txn->end_lsn);
641 /* Current initial LSN must be strictly higher than previous */
642 if (prev_first_lsn != InvalidXLogRecPtr)
643 Assert(prev_first_lsn < cur_txn->first_lsn);
645 /* known-as-subtxn txns must not be listed */
646 Assert(!cur_txn->is_known_as_subxact);
648 prev_first_lsn = cur_txn->first_lsn;
651 dlist_foreach(iter, &rb->txns_by_base_snapshot_lsn)
653 ReorderBufferTXN *cur_txn = dlist_container(ReorderBufferTXN,
657 /* base snapshot (and its LSN) must be set */
658 Assert(cur_txn->base_snapshot != NULL);
659 Assert(cur_txn->base_snapshot_lsn != InvalidXLogRecPtr);
661 /* current LSN must be strictly higher than previous */
662 if (prev_base_snap_lsn != InvalidXLogRecPtr)
663 Assert(prev_base_snap_lsn < cur_txn->base_snapshot_lsn);
665 /* known-as-subtxn txns must not be listed */
666 Assert(!cur_txn->is_known_as_subxact);
668 prev_base_snap_lsn = cur_txn->base_snapshot_lsn;
674 * ReorderBufferGetOldestTXN
675 * Return oldest transaction in reorderbuffer
678 ReorderBufferGetOldestTXN(ReorderBuffer *rb)
680 ReorderBufferTXN *txn;
682 AssertTXNLsnOrder(rb);
684 if (dlist_is_empty(&rb->toplevel_by_lsn))
687 txn = dlist_head_element(ReorderBufferTXN, node, &rb->toplevel_by_lsn);
689 Assert(!txn->is_known_as_subxact);
690 Assert(txn->first_lsn != InvalidXLogRecPtr);
695 * ReorderBufferGetOldestXmin
696 * Return oldest Xmin in reorderbuffer
698 * Returns oldest possibly running Xid from the point of view of snapshots
699 * used in the transactions kept by reorderbuffer, or InvalidTransactionId if
702 * Since snapshots are assigned monotonically, this equals the Xmin of the
703 * base snapshot with minimal base_snapshot_lsn.
706 ReorderBufferGetOldestXmin(ReorderBuffer *rb)
708 ReorderBufferTXN *txn;
710 AssertTXNLsnOrder(rb);
712 if (dlist_is_empty(&rb->txns_by_base_snapshot_lsn))
713 return InvalidTransactionId;
715 txn = dlist_head_element(ReorderBufferTXN, base_snapshot_node,
716 &rb->txns_by_base_snapshot_lsn);
717 return txn->base_snapshot->xmin;
721 ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr)
723 rb->current_restart_decoding_lsn = ptr;
727 * ReorderBufferAssignChild
729 * Make note that we know that subxid is a subtransaction of xid, seen as of
733 ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid,
734 TransactionId subxid, XLogRecPtr lsn)
736 ReorderBufferTXN *txn;
737 ReorderBufferTXN *subtxn;
741 txn = ReorderBufferTXNByXid(rb, xid, true, &new_top, lsn, true);
742 subtxn = ReorderBufferTXNByXid(rb, subxid, true, &new_sub, lsn, false);
744 if (new_top && !new_sub)
745 elog(ERROR, "subtransaction logged without previous top-level txn record");
749 if (subtxn->is_known_as_subxact)
751 /* already associated, nothing to do */
757 * We already saw this transaction, but initially added it to the
758 * list of top-level txns. Now that we know it's not top-level,
759 * remove it from there.
761 dlist_delete(&subtxn->node);
765 subtxn->is_known_as_subxact = true;
766 subtxn->toplevel_xid = xid;
767 Assert(subtxn->nsubtxns == 0);
769 /* add to subtransaction list */
770 dlist_push_tail(&txn->subtxns, &subtxn->node);
773 /* Possibly transfer the subtxn's snapshot to its top-level txn. */
774 ReorderBufferTransferSnapToParent(txn, subtxn);
776 /* Verify LSN-ordering invariant */
777 AssertTXNLsnOrder(rb);
781 * ReorderBufferTransferSnapToParent
782 * Transfer base snapshot from subtxn to top-level txn, if needed
784 * This is done if the top-level txn doesn't have a base snapshot, or if the
785 * subtxn's base snapshot has an earlier LSN than the top-level txn's base
786 * snapshot's LSN. This can happen if there are no changes in the toplevel
787 * txn but there are some in the subtxn, or the first change in subtxn has
788 * earlier LSN than first change in the top-level txn and we learned about
789 * their kinship only now.
791 * The subtransaction's snapshot is cleared regardless of the transfer
792 * happening, since it's not needed anymore in either case.
794 * We do this as soon as we become aware of their kinship, to avoid queueing
795 * extra snapshots to txns known-as-subtxns -- only top-level txns will
796 * receive further snapshots.
799 ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
800 ReorderBufferTXN *subtxn)
802 Assert(subtxn->toplevel_xid == txn->xid);
804 if (subtxn->base_snapshot != NULL)
806 if (txn->base_snapshot == NULL ||
807 subtxn->base_snapshot_lsn < txn->base_snapshot_lsn)
810 * If the toplevel transaction already has a base snapshot but
811 * it's newer than the subxact's, purge it.
813 if (txn->base_snapshot != NULL)
815 SnapBuildSnapDecRefcount(txn->base_snapshot);
816 dlist_delete(&txn->base_snapshot_node);
820 * The snapshot is now the top transaction's; transfer it, and
821 * adjust the list position of the top transaction in the list by
822 * moving it to where the subtransaction is.
824 txn->base_snapshot = subtxn->base_snapshot;
825 txn->base_snapshot_lsn = subtxn->base_snapshot_lsn;
826 dlist_insert_before(&subtxn->base_snapshot_node,
827 &txn->base_snapshot_node);
830 * The subtransaction doesn't have a snapshot anymore (so it
831 * mustn't be in the list.)
833 subtxn->base_snapshot = NULL;
834 subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
835 dlist_delete(&subtxn->base_snapshot_node);
839 /* Base snap of toplevel is fine, so subxact's is not needed */
840 SnapBuildSnapDecRefcount(subtxn->base_snapshot);
841 dlist_delete(&subtxn->base_snapshot_node);
842 subtxn->base_snapshot = NULL;
843 subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
849 * Associate a subtransaction with its toplevel transaction at commit
850 * time. There may be no further changes added after this.
853 ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
854 TransactionId subxid, XLogRecPtr commit_lsn,
857 ReorderBufferTXN *subtxn;
859 subtxn = ReorderBufferTXNByXid(rb, subxid, false, NULL,
860 InvalidXLogRecPtr, false);
863 * No need to do anything if that subtxn didn't contain any changes
868 subtxn->final_lsn = commit_lsn;
869 subtxn->end_lsn = end_lsn;
872 * Assign this subxact as a child of the toplevel xact (no-op if already
875 ReorderBufferAssignChild(rb, xid, subxid, InvalidXLogRecPtr);
880 * Support for efficiently iterating over a transaction's and its
881 * subtransactions' changes.
883 * We do by doing a k-way merge between transactions/subtransactions. For that
884 * we model the current heads of the different transactions as a binary heap
885 * so we easily know which (sub-)transaction has the change with the smallest
888 * We assume the changes in individual transactions are already sorted by LSN.
892 * Binary heap comparison function.
895 ReorderBufferIterCompare(Datum a, Datum b, void *arg)
897 ReorderBufferIterTXNState *state = (ReorderBufferIterTXNState *) arg;
898 XLogRecPtr pos_a = state->entries[DatumGetInt32(a)].lsn;
899 XLogRecPtr pos_b = state->entries[DatumGetInt32(b)].lsn;
903 else if (pos_a == pos_b)
909 * Allocate & initialize an iterator which iterates in lsn order over a
910 * transaction and all its subtransactions.
912 static ReorderBufferIterTXNState *
913 ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn)
916 ReorderBufferIterTXNState *state;
917 dlist_iter cur_txn_i;
921 * Calculate the size of our heap: one element for every transaction that
922 * contains changes. (Besides the transactions already in the reorder
923 * buffer, we count the one we were directly passed.)
925 if (txn->nentries > 0)
928 dlist_foreach(cur_txn_i, &txn->subtxns)
930 ReorderBufferTXN *cur_txn;
932 cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
934 if (cur_txn->nentries > 0)
939 * TODO: Consider adding fastpath for the rather common nr_txns=1 case, no
940 * need to allocate/build a heap then.
943 /* allocate iteration state */
944 state = (ReorderBufferIterTXNState *)
945 MemoryContextAllocZero(rb->context,
946 sizeof(ReorderBufferIterTXNState) +
947 sizeof(ReorderBufferIterTXNEntry) * nr_txns);
949 state->nr_txns = nr_txns;
950 dlist_init(&state->old_change);
952 for (off = 0; off < state->nr_txns; off++)
954 state->entries[off].fd = -1;
955 state->entries[off].segno = 0;
959 state->heap = binaryheap_allocate(state->nr_txns,
960 ReorderBufferIterCompare,
964 * Now insert items into the binary heap, in an unordered fashion. (We
965 * will run a heap assembly step at the end; this is more efficient.)
970 /* add toplevel transaction if it contains changes */
971 if (txn->nentries > 0)
973 ReorderBufferChange *cur_change;
977 /* serialize remaining changes */
978 ReorderBufferSerializeTXN(rb, txn);
979 ReorderBufferRestoreChanges(rb, txn, &state->entries[off].fd,
980 &state->entries[off].segno);
983 cur_change = dlist_head_element(ReorderBufferChange, node,
986 state->entries[off].lsn = cur_change->lsn;
987 state->entries[off].change = cur_change;
988 state->entries[off].txn = txn;
990 binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
993 /* add subtransactions if they contain changes */
994 dlist_foreach(cur_txn_i, &txn->subtxns)
996 ReorderBufferTXN *cur_txn;
998 cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
1000 if (cur_txn->nentries > 0)
1002 ReorderBufferChange *cur_change;
1004 if (cur_txn->serialized)
1006 /* serialize remaining changes */
1007 ReorderBufferSerializeTXN(rb, cur_txn);
1008 ReorderBufferRestoreChanges(rb, cur_txn,
1009 &state->entries[off].fd,
1010 &state->entries[off].segno);
1012 cur_change = dlist_head_element(ReorderBufferChange, node,
1015 state->entries[off].lsn = cur_change->lsn;
1016 state->entries[off].change = cur_change;
1017 state->entries[off].txn = cur_txn;
1019 binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
1023 /* assemble a valid binary heap */
1024 binaryheap_build(state->heap);
1030 * Return the next change when iterating over a transaction and its
1033 * Returns NULL when no further changes exist.
1035 static ReorderBufferChange *
1036 ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state)
1038 ReorderBufferChange *change;
1039 ReorderBufferIterTXNEntry *entry;
1042 /* nothing there anymore */
1043 if (state->heap->bh_size == 0)
1046 off = DatumGetInt32(binaryheap_first(state->heap));
1047 entry = &state->entries[off];
1049 /* free memory we might have "leaked" in the previous *Next call */
1050 if (!dlist_is_empty(&state->old_change))
1052 change = dlist_container(ReorderBufferChange, node,
1053 dlist_pop_head_node(&state->old_change));
1054 ReorderBufferReturnChange(rb, change);
1055 Assert(dlist_is_empty(&state->old_change));
1058 change = entry->change;
1061 * update heap with information about which transaction has the next
1062 * relevant change in LSN order
1065 /* there are in-memory changes */
1066 if (dlist_has_next(&entry->txn->changes, &entry->change->node))
1068 dlist_node *next = dlist_next_node(&entry->txn->changes, &change->node);
1069 ReorderBufferChange *next_change =
1070 dlist_container(ReorderBufferChange, node, next);
1072 /* txn stays the same */
1073 state->entries[off].lsn = next_change->lsn;
1074 state->entries[off].change = next_change;
1076 binaryheap_replace_first(state->heap, Int32GetDatum(off));
1080 /* try to load changes from disk */
1081 if (entry->txn->nentries != entry->txn->nentries_mem)
1084 * Ugly: restoring changes will reuse *Change records, thus delete the
1085 * current one from the per-tx list and only free in the next call.
1087 dlist_delete(&change->node);
1088 dlist_push_tail(&state->old_change, &change->node);
1090 if (ReorderBufferRestoreChanges(rb, entry->txn, &entry->fd,
1091 &state->entries[off].segno))
1093 /* successfully restored changes from disk */
1094 ReorderBufferChange *next_change =
1095 dlist_head_element(ReorderBufferChange, node,
1096 &entry->txn->changes);
1098 elog(DEBUG2, "restored %u/%u changes from disk",
1099 (uint32) entry->txn->nentries_mem,
1100 (uint32) entry->txn->nentries);
1102 Assert(entry->txn->nentries_mem);
1103 /* txn stays the same */
1104 state->entries[off].lsn = next_change->lsn;
1105 state->entries[off].change = next_change;
1106 binaryheap_replace_first(state->heap, Int32GetDatum(off));
1112 /* ok, no changes there anymore, remove */
1113 binaryheap_remove_first(state->heap);
1119 * Deallocate the iterator
1122 ReorderBufferIterTXNFinish(ReorderBuffer *rb,
1123 ReorderBufferIterTXNState *state)
1127 for (off = 0; off < state->nr_txns; off++)
1129 if (state->entries[off].fd != -1)
1130 CloseTransientFile(state->entries[off].fd);
1133 /* free memory we might have "leaked" in the last *Next call */
1134 if (!dlist_is_empty(&state->old_change))
1136 ReorderBufferChange *change;
1138 change = dlist_container(ReorderBufferChange, node,
1139 dlist_pop_head_node(&state->old_change));
1140 ReorderBufferReturnChange(rb, change);
1141 Assert(dlist_is_empty(&state->old_change));
1144 binaryheap_free(state->heap);
1149 * Cleanup the contents of a transaction, usually after the transaction
1150 * committed or aborted.
1153 ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1156 dlist_mutable_iter iter;
1158 /* cleanup subtransactions & their changes */
1159 dlist_foreach_modify(iter, &txn->subtxns)
1161 ReorderBufferTXN *subtxn;
1163 subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
1166 * Subtransactions are always associated to the toplevel TXN, even if
1167 * they originally were happening inside another subtxn, so we won't
1168 * ever recurse more than one level deep here.
1170 Assert(subtxn->is_known_as_subxact);
1171 Assert(subtxn->nsubtxns == 0);
1173 ReorderBufferCleanupTXN(rb, subtxn);
1176 /* cleanup changes in the toplevel txn */
1177 dlist_foreach_modify(iter, &txn->changes)
1179 ReorderBufferChange *change;
1181 change = dlist_container(ReorderBufferChange, node, iter.cur);
1183 ReorderBufferReturnChange(rb, change);
1187 * Cleanup the tuplecids we stored for decoding catalog snapshot access.
1188 * They are always stored in the toplevel transaction.
1190 dlist_foreach_modify(iter, &txn->tuplecids)
1192 ReorderBufferChange *change;
1194 change = dlist_container(ReorderBufferChange, node, iter.cur);
1195 Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1196 ReorderBufferReturnChange(rb, change);
1200 * Cleanup the base snapshot, if set.
1202 if (txn->base_snapshot != NULL)
1204 SnapBuildSnapDecRefcount(txn->base_snapshot);
1205 dlist_delete(&txn->base_snapshot_node);
1209 * Remove TXN from its containing list.
1211 * Note: if txn->is_known_as_subxact, we are deleting the TXN from its
1212 * parent's list of known subxacts; this leaves the parent's nsubxacts
1213 * count too high, but we don't care. Otherwise, we are deleting the TXN
1214 * from the LSN-ordered list of toplevel TXNs.
1216 dlist_delete(&txn->node);
1218 /* now remove reference from buffer */
1219 hash_search(rb->by_txn,
1225 /* remove entries spilled to disk */
1226 if (txn->serialized)
1227 ReorderBufferRestoreCleanup(rb, txn);
1230 ReorderBufferReturnTXN(rb, txn);
1234 * Build a hash with a (relfilenode, ctid) -> (cmin, cmax) mapping for use by
1235 * tqual.c's HeapTupleSatisfiesHistoricMVCC.
1238 ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
1243 if (!txn->has_catalog_changes || dlist_is_empty(&txn->tuplecids))
1246 memset(&hash_ctl, 0, sizeof(hash_ctl));
1248 hash_ctl.keysize = sizeof(ReorderBufferTupleCidKey);
1249 hash_ctl.entrysize = sizeof(ReorderBufferTupleCidEnt);
1250 hash_ctl.hcxt = rb->context;
1253 * create the hash with the exact number of to-be-stored tuplecids from
1256 txn->tuplecid_hash =
1257 hash_create("ReorderBufferTupleCid", txn->ntuplecids, &hash_ctl,
1258 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
1260 dlist_foreach(iter, &txn->tuplecids)
1262 ReorderBufferTupleCidKey key;
1263 ReorderBufferTupleCidEnt *ent;
1265 ReorderBufferChange *change;
1267 change = dlist_container(ReorderBufferChange, node, iter.cur);
1269 Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1271 /* be careful about padding */
1272 memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
1274 key.relnode = change->data.tuplecid.node;
1276 ItemPointerCopy(&change->data.tuplecid.tid,
1279 ent = (ReorderBufferTupleCidEnt *)
1280 hash_search(txn->tuplecid_hash,
1282 HASH_ENTER | HASH_FIND,
1286 ent->cmin = change->data.tuplecid.cmin;
1287 ent->cmax = change->data.tuplecid.cmax;
1288 ent->combocid = change->data.tuplecid.combocid;
1292 Assert(ent->cmin == change->data.tuplecid.cmin);
1293 Assert(ent->cmax == InvalidCommandId ||
1294 ent->cmax == change->data.tuplecid.cmax);
1297 * if the tuple got valid in this transaction and now got deleted
1298 * we already have a valid cmin stored. The cmax will be
1299 * InvalidCommandId though.
1301 ent->cmax = change->data.tuplecid.cmax;
1307 * Copy a provided snapshot so we can modify it privately. This is needed so
1308 * that catalog modifying transactions can look into intermediate catalog
1312 ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
1313 ReorderBufferTXN *txn, CommandId cid)
1320 size = sizeof(SnapshotData) +
1321 sizeof(TransactionId) * orig_snap->xcnt +
1322 sizeof(TransactionId) * (txn->nsubtxns + 1);
1324 snap = MemoryContextAllocZero(rb->context, size);
1325 memcpy(snap, orig_snap, sizeof(SnapshotData));
1327 snap->copied = true;
1328 snap->active_count = 1; /* mark as active so nobody frees it */
1329 snap->regd_count = 0;
1330 snap->xip = (TransactionId *) (snap + 1);
1332 memcpy(snap->xip, orig_snap->xip, sizeof(TransactionId) * snap->xcnt);
1335 * snap->subxip contains all txids that belong to our transaction which we
1336 * need to check via cmin/cmax. That's why we store the toplevel
1337 * transaction in there as well.
1339 snap->subxip = snap->xip + snap->xcnt;
1340 snap->subxip[i++] = txn->xid;
1343 * nsubxcnt isn't decreased when subtransactions abort, so count manually.
1344 * Since it's an upper boundary it is safe to use it for the allocation
1349 dlist_foreach(iter, &txn->subtxns)
1351 ReorderBufferTXN *sub_txn;
1353 sub_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
1354 snap->subxip[i++] = sub_txn->xid;
1358 /* sort so we can bsearch() later */
1359 qsort(snap->subxip, snap->subxcnt, sizeof(TransactionId), xidComparator);
1361 /* store the specified current CommandId */
1368 * Free a previously ReorderBufferCopySnap'ed snapshot
1371 ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap)
1376 SnapBuildSnapDecRefcount(snap);
1380 * Perform the replay of a transaction and its non-aborted subtransactions.
1382 * Subtransactions previously have to be processed by
1383 * ReorderBufferCommitChild(), even if previously assigned to the toplevel
1384 * transaction with ReorderBufferAssignChild.
1386 * We currently can only decode a transaction's contents when its commit
1387 * record is read because that's the only place where we know about cache
1388 * invalidations. Thus, once a toplevel commit is read, we iterate over the top
1389 * and subtransactions (using a k-way merge) and replay the changes in lsn
1393 ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
1394 XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
1395 TimestampTz commit_time,
1396 RepOriginId origin_id, XLogRecPtr origin_lsn)
1398 ReorderBufferTXN *txn;
1399 volatile Snapshot snapshot_now;
1400 volatile CommandId command_id = FirstCommandId;
1402 ReorderBufferIterTXNState *volatile iterstate = NULL;
1404 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1407 /* unknown transaction, nothing to replay */
1411 txn->final_lsn = commit_lsn;
1412 txn->end_lsn = end_lsn;
1413 txn->commit_time = commit_time;
1414 txn->origin_id = origin_id;
1415 txn->origin_lsn = origin_lsn;
1418 * If this transaction has no snapshot, it didn't make any changes to the
1419 * database, so there's nothing to decode. Note that
1420 * ReorderBufferCommitChild will have transferred any snapshots from
1421 * subtransactions if there were any.
1423 if (txn->base_snapshot == NULL)
1425 Assert(txn->ninvalidations == 0);
1426 ReorderBufferCleanupTXN(rb, txn);
1430 snapshot_now = txn->base_snapshot;
1432 /* build data to be able to lookup the CommandIds of catalog tuples */
1433 ReorderBufferBuildTupleCidHash(rb, txn);
1435 /* setup the initial snapshot */
1436 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1439 * Decoding needs access to syscaches et al., which in turn use
1440 * heavyweight locks and such. Thus we need to have enough state around to
1441 * keep track of those. The easiest way is to simply use a transaction
1442 * internally. That also allows us to easily enforce that nothing writes
1443 * to the database by checking for xid assignments.
1445 * When we're called via the SQL SRF there's already a transaction
1446 * started, so start an explicit subtransaction there.
1448 using_subtxn = IsTransactionOrTransactionBlock();
1452 ReorderBufferChange *change;
1453 ReorderBufferChange *specinsert = NULL;
1456 BeginInternalSubTransaction("replay");
1458 StartTransactionCommand();
1462 iterstate = ReorderBufferIterTXNInit(rb, txn);
1463 while ((change = ReorderBufferIterTXNNext(rb, iterstate)) != NULL)
1465 Relation relation = NULL;
1468 switch (change->action)
1470 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
1473 * Confirmation for speculative insertion arrived. Simply
1474 * use as a normal record. It'll be cleaned up at the end
1475 * of INSERT processing.
1477 if (specinsert == NULL)
1478 elog(ERROR, "invalid ordering of speculative insertion changes");
1479 Assert(specinsert->data.tp.oldtuple == NULL);
1480 change = specinsert;
1481 change->action = REORDER_BUFFER_CHANGE_INSERT;
1483 /* intentionally fall through */
1484 case REORDER_BUFFER_CHANGE_INSERT:
1485 case REORDER_BUFFER_CHANGE_UPDATE:
1486 case REORDER_BUFFER_CHANGE_DELETE:
1487 Assert(snapshot_now);
1489 reloid = RelidByRelfilenode(change->data.tp.relnode.spcNode,
1490 change->data.tp.relnode.relNode);
1493 * Catalog tuple without data, emitted while catalog was
1494 * in the process of being rewritten.
1496 if (reloid == InvalidOid &&
1497 change->data.tp.newtuple == NULL &&
1498 change->data.tp.oldtuple == NULL)
1500 else if (reloid == InvalidOid)
1501 elog(ERROR, "could not map filenode \"%s\" to relation OID",
1502 relpathperm(change->data.tp.relnode,
1505 relation = RelationIdGetRelation(reloid);
1507 if (relation == NULL)
1508 elog(ERROR, "could not open relation with OID %u (for filenode \"%s\")",
1510 relpathperm(change->data.tp.relnode,
1513 if (!RelationIsLogicallyLogged(relation))
1517 * Ignore temporary heaps created during DDL unless the
1518 * plugin has asked for them.
1520 if (relation->rd_rel->relrewrite && !rb->output_rewrites)
1524 * For now ignore sequence changes entirely. Most of the
1525 * time they don't log changes using records we
1526 * understand, so it doesn't make sense to handle the few
1529 if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
1532 /* user-triggered change */
1533 if (!IsToastRelation(relation))
1535 ReorderBufferToastReplace(rb, txn, relation, change);
1536 rb->apply_change(rb, txn, relation, change);
1539 * Only clear reassembled toast chunks if we're sure
1540 * they're not required anymore. The creator of the
1543 if (change->data.tp.clear_toast_afterwards)
1544 ReorderBufferToastReset(rb, txn);
1546 /* we're not interested in toast deletions */
1547 else if (change->action == REORDER_BUFFER_CHANGE_INSERT)
1550 * Need to reassemble the full toasted Datum in
1551 * memory, to ensure the chunks don't get reused till
1552 * we're done remove it from the list of this
1553 * transaction's changes. Otherwise it will get
1554 * freed/reused while restoring spooled data from
1557 dlist_delete(&change->node);
1558 ReorderBufferToastAppendChunk(rb, txn, relation,
1565 * Either speculative insertion was confirmed, or it was
1566 * unsuccessful and the record isn't needed anymore.
1568 if (specinsert != NULL)
1570 ReorderBufferReturnChange(rb, specinsert);
1574 if (relation != NULL)
1576 RelationClose(relation);
1581 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
1584 * Speculative insertions are dealt with by delaying the
1585 * processing of the insert until the confirmation record
1586 * arrives. For that we simply unlink the record from the
1587 * chain, so it does not get freed/reused while restoring
1588 * spooled data from disk.
1590 * This is safe in the face of concurrent catalog changes
1591 * because the relevant relation can't be changed between
1592 * speculative insertion and confirmation due to
1593 * CheckTableNotInUse() and locking.
1596 /* clear out a pending (and thus failed) speculation */
1597 if (specinsert != NULL)
1599 ReorderBufferReturnChange(rb, specinsert);
1603 /* and memorize the pending insertion */
1604 dlist_delete(&change->node);
1605 specinsert = change;
1608 case REORDER_BUFFER_CHANGE_TRUNCATE:
1611 int nrelids = change->data.truncate.nrelids;
1613 Relation *relations;
1615 relations = palloc0(nrelids * sizeof(Relation));
1616 for (i = 0; i < nrelids; i++)
1618 Oid relid = change->data.truncate.relids[i];
1621 relation = RelationIdGetRelation(relid);
1623 if (relation == NULL)
1624 elog(ERROR, "could not open relation with OID %u", relid);
1626 if (!RelationIsLogicallyLogged(relation))
1629 relations[nrelations++] = relation;
1632 rb->apply_truncate(rb, txn, nrelations, relations, change);
1634 for (i = 0; i < nrelations; i++)
1635 RelationClose(relations[i]);
1640 case REORDER_BUFFER_CHANGE_MESSAGE:
1641 rb->message(rb, txn, change->lsn, true,
1642 change->data.msg.prefix,
1643 change->data.msg.message_size,
1644 change->data.msg.message);
1647 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
1648 /* get rid of the old */
1649 TeardownHistoricSnapshot(false);
1651 if (snapshot_now->copied)
1653 ReorderBufferFreeSnap(rb, snapshot_now);
1655 ReorderBufferCopySnap(rb, change->data.snapshot,
1660 * Restored from disk, need to be careful not to double
1661 * free. We could introduce refcounting for that, but for
1662 * now this seems infrequent enough not to care.
1664 else if (change->data.snapshot->copied)
1667 ReorderBufferCopySnap(rb, change->data.snapshot,
1672 snapshot_now = change->data.snapshot;
1676 /* and continue with the new one */
1677 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1680 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
1681 Assert(change->data.command_id != InvalidCommandId);
1683 if (command_id < change->data.command_id)
1685 command_id = change->data.command_id;
1687 if (!snapshot_now->copied)
1689 /* we don't use the global one anymore */
1690 snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
1694 snapshot_now->curcid = command_id;
1696 TeardownHistoricSnapshot(false);
1697 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1700 * Every time the CommandId is incremented, we could
1701 * see new catalog contents, so execute all
1704 ReorderBufferExecuteInvalidations(rb, txn);
1709 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
1710 elog(ERROR, "tuplecid value in changequeue");
1716 * There's a speculative insertion remaining, just clean in up, it
1717 * can't have been successful, otherwise we'd gotten a confirmation
1722 ReorderBufferReturnChange(rb, specinsert);
1726 /* clean up the iterator */
1727 ReorderBufferIterTXNFinish(rb, iterstate);
1730 /* call commit callback */
1731 rb->commit(rb, txn, commit_lsn);
1733 /* this is just a sanity check against bad output plugin behaviour */
1734 if (GetCurrentTransactionIdIfAny() != InvalidTransactionId)
1735 elog(ERROR, "output plugin used XID %u",
1736 GetCurrentTransactionId());
1739 TeardownHistoricSnapshot(false);
1742 * Aborting the current (sub-)transaction as a whole has the right
1743 * semantics. We want all locks acquired in here to be released, not
1744 * reassigned to the parent and we do not want any database access
1745 * have persistent effects.
1747 AbortCurrentTransaction();
1749 /* make sure there's no cache pollution */
1750 ReorderBufferExecuteInvalidations(rb, txn);
1753 RollbackAndReleaseCurrentSubTransaction();
1755 if (snapshot_now->copied)
1756 ReorderBufferFreeSnap(rb, snapshot_now);
1758 /* remove potential on-disk data, and deallocate */
1759 ReorderBufferCleanupTXN(rb, txn);
1763 /* TODO: Encapsulate cleanup from the PG_TRY and PG_CATCH blocks */
1765 ReorderBufferIterTXNFinish(rb, iterstate);
1767 TeardownHistoricSnapshot(true);
1770 * Force cache invalidation to happen outside of a valid transaction
1771 * to prevent catalog access as we just caught an error.
1773 AbortCurrentTransaction();
1775 /* make sure there's no cache pollution */
1776 ReorderBufferExecuteInvalidations(rb, txn);
1779 RollbackAndReleaseCurrentSubTransaction();
1781 if (snapshot_now->copied)
1782 ReorderBufferFreeSnap(rb, snapshot_now);
1784 /* remove potential on-disk data, and deallocate */
1785 ReorderBufferCleanupTXN(rb, txn);
1793 * Abort a transaction that possibly has previous changes. Needs to be first
1794 * called for subtransactions and then for the toplevel xid.
1796 * NB: Transactions handled here have to have actively aborted (i.e. have
1797 * produced an abort record). Implicitly aborted transactions are handled via
1798 * ReorderBufferAbortOld(); transactions we're just not interested in, but
1799 * which have committed are handled in ReorderBufferForget().
1801 * This function purges this transaction and its contents from memory and
1805 ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1807 ReorderBufferTXN *txn;
1809 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1812 /* unknown, nothing to remove */
1817 txn->final_lsn = lsn;
1819 /* remove potential on-disk data, and deallocate */
1820 ReorderBufferCleanupTXN(rb, txn);
1824 * Abort all transactions that aren't actually running anymore because the
1827 * NB: These really have to be transactions that have aborted due to a server
1828 * crash/immediate restart, as we don't deal with invalidations here.
1831 ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid)
1833 dlist_mutable_iter it;
1836 * Iterate through all (potential) toplevel TXNs and abort all that are
1837 * older than what possibly can be running. Once we've found the first
1838 * that is alive we stop, there might be some that acquired an xid earlier
1839 * but started writing later, but it's unlikely and they will be cleaned
1840 * up in a later call to this function.
1842 dlist_foreach_modify(it, &rb->toplevel_by_lsn)
1844 ReorderBufferTXN *txn;
1846 txn = dlist_container(ReorderBufferTXN, node, it.cur);
1848 if (TransactionIdPrecedes(txn->xid, oldestRunningXid))
1851 * We set final_lsn on a transaction when we decode its commit or
1852 * abort record, but we never see those records for crashed
1853 * transactions. To ensure cleanup of these transactions, set
1854 * final_lsn to that of their last change; this causes
1855 * ReorderBufferRestoreCleanup to do the right thing.
1857 if (txn->serialized && txn->final_lsn == 0)
1859 ReorderBufferChange *last =
1860 dlist_tail_element(ReorderBufferChange, node, &txn->changes);
1862 txn->final_lsn = last->lsn;
1865 elog(DEBUG2, "aborting old transaction %u", txn->xid);
1867 /* remove potential on-disk data, and deallocate this tx */
1868 ReorderBufferCleanupTXN(rb, txn);
1876 * Forget the contents of a transaction if we aren't interested in it's
1877 * contents. Needs to be first called for subtransactions and then for the
1880 * This is significantly different to ReorderBufferAbort() because
1881 * transactions that have committed need to be treated differently from aborted
1882 * ones since they may have modified the catalog.
1884 * Note that this is only allowed to be called in the moment a transaction
1885 * commit has just been read, not earlier; otherwise later records referring
1886 * to this xid might re-create the transaction incompletely.
1889 ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1891 ReorderBufferTXN *txn;
1893 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1896 /* unknown, nothing to forget */
1901 txn->final_lsn = lsn;
1904 * Process cache invalidation messages if there are any. Even if we're not
1905 * interested in the transaction's contents, it could have manipulated the
1906 * catalog and we need to update the caches according to that.
1908 if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
1909 ReorderBufferImmediateInvalidation(rb, txn->ninvalidations,
1910 txn->invalidations);
1912 Assert(txn->ninvalidations == 0);
1914 /* remove potential on-disk data, and deallocate */
1915 ReorderBufferCleanupTXN(rb, txn);
1919 * Execute invalidations happening outside the context of a decoded
1920 * transaction. That currently happens either for xid-less commits
1921 * (cf. RecordTransactionCommit()) or for invalidations in uninteresting
1922 * transactions (via ReorderBufferForget()).
1925 ReorderBufferImmediateInvalidation(ReorderBuffer *rb, uint32 ninvalidations,
1926 SharedInvalidationMessage *invalidations)
1928 bool use_subtxn = IsTransactionOrTransactionBlock();
1932 BeginInternalSubTransaction("replay");
1935 * Force invalidations to happen outside of a valid transaction - that way
1936 * entries will just be marked as invalid without accessing the catalog.
1937 * That's advantageous because we don't need to setup the full state
1938 * necessary for catalog access.
1941 AbortCurrentTransaction();
1943 for (i = 0; i < ninvalidations; i++)
1944 LocalExecuteInvalidationMessage(&invalidations[i]);
1947 RollbackAndReleaseCurrentSubTransaction();
1951 * Tell reorderbuffer about an xid seen in the WAL stream. Has to be called at
1952 * least once for every xid in XLogRecord->xl_xid (other places in records
1953 * may, but do not have to be passed through here).
1955 * Reorderbuffer keeps some datastructures about transactions in LSN order,
1956 * for efficiency. To do that it has to know about when transactions are seen
1957 * first in the WAL. As many types of records are not actually interesting for
1958 * logical decoding, they do not necessarily pass though here.
1961 ReorderBufferProcessXid(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1963 /* many records won't have an xid assigned, centralize check here */
1964 if (xid != InvalidTransactionId)
1965 ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1969 * Add a new snapshot to this transaction that may only used after lsn 'lsn'
1970 * because the previous snapshot doesn't describe the catalog correctly for
1974 ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid,
1975 XLogRecPtr lsn, Snapshot snap)
1977 ReorderBufferChange *change = ReorderBufferGetChange(rb);
1979 change->data.snapshot = snap;
1980 change->action = REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT;
1982 ReorderBufferQueueChange(rb, xid, lsn, change);
1986 * Set up the transaction's base snapshot.
1988 * If we know that xid is a subtransaction, set the base snapshot on the
1989 * top-level transaction instead.
1992 ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid,
1993 XLogRecPtr lsn, Snapshot snap)
1995 ReorderBufferTXN *txn;
1998 AssertArg(snap != NULL);
2001 * Fetch the transaction to operate on. If we know it's a subtransaction,
2002 * operate on its top-level transaction instead.
2004 txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true);
2005 if (txn->is_known_as_subxact)
2006 txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false,
2007 NULL, InvalidXLogRecPtr, false);
2008 Assert(txn->base_snapshot == NULL);
2010 txn->base_snapshot = snap;
2011 txn->base_snapshot_lsn = lsn;
2012 dlist_push_tail(&rb->txns_by_base_snapshot_lsn, &txn->base_snapshot_node);
2014 AssertTXNLsnOrder(rb);
2018 * Access the catalog with this CommandId at this point in the changestream.
2020 * May only be called for command ids > 1
2023 ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
2024 XLogRecPtr lsn, CommandId cid)
2026 ReorderBufferChange *change = ReorderBufferGetChange(rb);
2028 change->data.command_id = cid;
2029 change->action = REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID;
2031 ReorderBufferQueueChange(rb, xid, lsn, change);
2036 * Add new (relfilenode, tid) -> (cmin, cmax) mappings.
2039 ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
2040 XLogRecPtr lsn, RelFileNode node,
2041 ItemPointerData tid, CommandId cmin,
2042 CommandId cmax, CommandId combocid)
2044 ReorderBufferChange *change = ReorderBufferGetChange(rb);
2045 ReorderBufferTXN *txn;
2047 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
2049 change->data.tuplecid.node = node;
2050 change->data.tuplecid.tid = tid;
2051 change->data.tuplecid.cmin = cmin;
2052 change->data.tuplecid.cmax = cmax;
2053 change->data.tuplecid.combocid = combocid;
2055 change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
2057 dlist_push_tail(&txn->tuplecids, &change->node);
2062 * Setup the invalidation of the toplevel transaction.
2064 * This needs to be done before ReorderBufferCommit is called!
2067 ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid,
2068 XLogRecPtr lsn, Size nmsgs,
2069 SharedInvalidationMessage *msgs)
2071 ReorderBufferTXN *txn;
2073 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
2075 if (txn->ninvalidations != 0)
2076 elog(ERROR, "only ever add one set of invalidations");
2080 txn->ninvalidations = nmsgs;
2081 txn->invalidations = (SharedInvalidationMessage *)
2082 MemoryContextAlloc(rb->context,
2083 sizeof(SharedInvalidationMessage) * nmsgs);
2084 memcpy(txn->invalidations, msgs,
2085 sizeof(SharedInvalidationMessage) * nmsgs);
2089 * Apply all invalidations we know. Possibly we only need parts at this point
2090 * in the changestream but we don't know which those are.
2093 ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn)
2097 for (i = 0; i < txn->ninvalidations; i++)
2098 LocalExecuteInvalidationMessage(&txn->invalidations[i]);
2102 * Mark a transaction as containing catalog changes
2105 ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid,
2108 ReorderBufferTXN *txn;
2110 txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
2112 txn->has_catalog_changes = true;
2116 * Query whether a transaction is already *known* to contain catalog
2117 * changes. This can be wrong until directly before the commit!
2120 ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
2122 ReorderBufferTXN *txn;
2124 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
2129 return txn->has_catalog_changes;
2133 * ReorderBufferXidHasBaseSnapshot
2134 * Have we already set the base snapshot for the given txn/subtxn?
2137 ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
2139 ReorderBufferTXN *txn;
2141 txn = ReorderBufferTXNByXid(rb, xid, false,
2142 NULL, InvalidXLogRecPtr, false);
2144 /* transaction isn't known yet, ergo no snapshot */
2148 /* a known subtxn? operate on top-level txn instead */
2149 if (txn->is_known_as_subxact)
2150 txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false,
2151 NULL, InvalidXLogRecPtr, false);
2153 return txn->base_snapshot != NULL;
2158 * ---------------------------------------
2159 * Disk serialization support
2160 * ---------------------------------------
2164 * Ensure the IO buffer is >= sz.
2167 ReorderBufferSerializeReserve(ReorderBuffer *rb, Size sz)
2169 if (!rb->outbufsize)
2171 rb->outbuf = MemoryContextAlloc(rb->context, sz);
2172 rb->outbufsize = sz;
2174 else if (rb->outbufsize < sz)
2176 rb->outbuf = repalloc(rb->outbuf, sz);
2177 rb->outbufsize = sz;
2182 * Check whether the transaction tx should spill its data to disk.
2185 ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
2188 * TODO: improve accounting so we cheaply can take subtransactions into
2191 if (txn->nentries_mem >= max_changes_in_memory)
2193 ReorderBufferSerializeTXN(rb, txn);
2194 Assert(txn->nentries_mem == 0);
2199 * Spill data of a large transaction (and its subtransactions) to disk.
2202 ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
2204 dlist_iter subtxn_i;
2205 dlist_mutable_iter change_i;
2207 XLogSegNo curOpenSegNo = 0;
2210 elog(DEBUG2, "spill %u changes in XID %u to disk",
2211 (uint32) txn->nentries_mem, txn->xid);
2213 /* do the same to all child TXs */
2214 dlist_foreach(subtxn_i, &txn->subtxns)
2216 ReorderBufferTXN *subtxn;
2218 subtxn = dlist_container(ReorderBufferTXN, node, subtxn_i.cur);
2219 ReorderBufferSerializeTXN(rb, subtxn);
2222 /* serialize changestream */
2223 dlist_foreach_modify(change_i, &txn->changes)
2225 ReorderBufferChange *change;
2227 change = dlist_container(ReorderBufferChange, node, change_i.cur);
2230 * store in segment in which it belongs by start lsn, don't split over
2231 * multiple segments tho
2234 !XLByteInSeg(change->lsn, curOpenSegNo, wal_segment_size))
2236 char path[MAXPGPATH];
2239 CloseTransientFile(fd);
2241 XLByteToSeg(change->lsn, curOpenSegNo, wal_segment_size);
2244 * No need to care about TLIs here, only used during a single run,
2245 * so each LSN only maps to a specific WAL record.
2247 ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
2250 /* open segment, create it if necessary */
2251 fd = OpenTransientFile(path,
2252 O_CREAT | O_WRONLY | O_APPEND | PG_BINARY);
2256 (errcode_for_file_access(),
2257 errmsg("could not open file \"%s\": %m", path)));
2260 ReorderBufferSerializeChange(rb, txn, fd, change);
2261 dlist_delete(&change->node);
2262 ReorderBufferReturnChange(rb, change);
2267 Assert(spilled == txn->nentries_mem);
2268 Assert(dlist_is_empty(&txn->changes));
2269 txn->nentries_mem = 0;
2270 txn->serialized = true;
2273 CloseTransientFile(fd);
2277 * Serialize individual change to disk.
2280 ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2281 int fd, ReorderBufferChange *change)
2283 ReorderBufferDiskChange *ondisk;
2284 Size sz = sizeof(ReorderBufferDiskChange);
2286 ReorderBufferSerializeReserve(rb, sz);
2288 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2289 memcpy(&ondisk->change, change, sizeof(ReorderBufferChange));
2291 switch (change->action)
2293 /* fall through these, they're all similar enough */
2294 case REORDER_BUFFER_CHANGE_INSERT:
2295 case REORDER_BUFFER_CHANGE_UPDATE:
2296 case REORDER_BUFFER_CHANGE_DELETE:
2297 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2300 ReorderBufferTupleBuf *oldtup,
2305 oldtup = change->data.tp.oldtuple;
2306 newtup = change->data.tp.newtuple;
2310 sz += sizeof(HeapTupleData);
2311 oldlen = oldtup->tuple.t_len;
2317 sz += sizeof(HeapTupleData);
2318 newlen = newtup->tuple.t_len;
2322 /* make sure we have enough space */
2323 ReorderBufferSerializeReserve(rb, sz);
2325 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2326 /* might have been reallocated above */
2327 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2331 memcpy(data, &oldtup->tuple, sizeof(HeapTupleData));
2332 data += sizeof(HeapTupleData);
2334 memcpy(data, oldtup->tuple.t_data, oldlen);
2340 memcpy(data, &newtup->tuple, sizeof(HeapTupleData));
2341 data += sizeof(HeapTupleData);
2343 memcpy(data, newtup->tuple.t_data, newlen);
2348 case REORDER_BUFFER_CHANGE_MESSAGE:
2351 Size prefix_size = strlen(change->data.msg.prefix) + 1;
2353 sz += prefix_size + change->data.msg.message_size +
2354 sizeof(Size) + sizeof(Size);
2355 ReorderBufferSerializeReserve(rb, sz);
2357 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2359 /* might have been reallocated above */
2360 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2362 /* write the prefix including the size */
2363 memcpy(data, &prefix_size, sizeof(Size));
2364 data += sizeof(Size);
2365 memcpy(data, change->data.msg.prefix,
2367 data += prefix_size;
2369 /* write the message including the size */
2370 memcpy(data, &change->data.msg.message_size, sizeof(Size));
2371 data += sizeof(Size);
2372 memcpy(data, change->data.msg.message,
2373 change->data.msg.message_size);
2374 data += change->data.msg.message_size;
2378 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2383 snap = change->data.snapshot;
2385 sz += sizeof(SnapshotData) +
2386 sizeof(TransactionId) * snap->xcnt +
2387 sizeof(TransactionId) * snap->subxcnt
2390 /* make sure we have enough space */
2391 ReorderBufferSerializeReserve(rb, sz);
2392 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2393 /* might have been reallocated above */
2394 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2396 memcpy(data, snap, sizeof(SnapshotData));
2397 data += sizeof(SnapshotData);
2401 memcpy(data, snap->xip,
2402 sizeof(TransactionId) * snap->xcnt);
2403 data += sizeof(TransactionId) * snap->xcnt;
2408 memcpy(data, snap->subxip,
2409 sizeof(TransactionId) * snap->subxcnt);
2410 data += sizeof(TransactionId) * snap->subxcnt;
2414 case REORDER_BUFFER_CHANGE_TRUNCATE:
2415 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2416 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2417 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2418 /* ReorderBufferChange contains everything important */
2425 pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_WRITE);
2426 if (write(fd, rb->outbuf, ondisk->size) != ondisk->size)
2428 int save_errno = errno;
2430 CloseTransientFile(fd);
2432 /* if write didn't set errno, assume problem is no disk space */
2433 errno = save_errno ? save_errno : ENOSPC;
2435 (errcode_for_file_access(),
2436 errmsg("could not write to data file for XID %u: %m",
2439 pgstat_report_wait_end();
2441 Assert(ondisk->change.action == change->action);
2445 * Restore a number of changes spilled to disk back into memory.
2448 ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
2449 int *fd, XLogSegNo *segno)
2452 XLogSegNo last_segno;
2453 dlist_mutable_iter cleanup_iter;
2455 Assert(txn->first_lsn != InvalidXLogRecPtr);
2456 Assert(txn->final_lsn != InvalidXLogRecPtr);
2458 /* free current entries, so we have memory for more */
2459 dlist_foreach_modify(cleanup_iter, &txn->changes)
2461 ReorderBufferChange *cleanup =
2462 dlist_container(ReorderBufferChange, node, cleanup_iter.cur);
2464 dlist_delete(&cleanup->node);
2465 ReorderBufferReturnChange(rb, cleanup);
2467 txn->nentries_mem = 0;
2468 Assert(dlist_is_empty(&txn->changes));
2470 XLByteToSeg(txn->final_lsn, last_segno, wal_segment_size);
2472 while (restored < max_changes_in_memory && *segno <= last_segno)
2475 ReorderBufferDiskChange *ondisk;
2479 char path[MAXPGPATH];
2483 XLByteToSeg(txn->first_lsn, *segno, wal_segment_size);
2485 Assert(*segno != 0 || dlist_is_empty(&txn->changes));
2488 * No need to care about TLIs here, only used during a single run,
2489 * so each LSN only maps to a specific WAL record.
2491 ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
2494 *fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
2495 if (*fd < 0 && errno == ENOENT)
2503 (errcode_for_file_access(),
2504 errmsg("could not open file \"%s\": %m",
2509 * Read the statically sized part of a change which has information
2510 * about the total size. If we couldn't read a record, we're at the
2513 ReorderBufferSerializeReserve(rb, sizeof(ReorderBufferDiskChange));
2514 pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_READ);
2515 readBytes = read(*fd, rb->outbuf, sizeof(ReorderBufferDiskChange));
2516 pgstat_report_wait_end();
2521 CloseTransientFile(*fd);
2526 else if (readBytes < 0)
2528 (errcode_for_file_access(),
2529 errmsg("could not read from reorderbuffer spill file: %m")));
2530 else if (readBytes != sizeof(ReorderBufferDiskChange))
2532 (errcode_for_file_access(),
2533 errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2535 (uint32) sizeof(ReorderBufferDiskChange))));
2537 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2539 ReorderBufferSerializeReserve(rb,
2540 sizeof(ReorderBufferDiskChange) + ondisk->size);
2541 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2543 pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_READ);
2544 readBytes = read(*fd, rb->outbuf + sizeof(ReorderBufferDiskChange),
2545 ondisk->size - sizeof(ReorderBufferDiskChange));
2546 pgstat_report_wait_end();
2550 (errcode_for_file_access(),
2551 errmsg("could not read from reorderbuffer spill file: %m")));
2552 else if (readBytes != ondisk->size - sizeof(ReorderBufferDiskChange))
2554 (errcode_for_file_access(),
2555 errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2557 (uint32) (ondisk->size - sizeof(ReorderBufferDiskChange)))));
2560 * ok, read a full change from disk, now restore it into proper
2563 ReorderBufferRestoreChange(rb, txn, rb->outbuf);
2571 * Convert change from its on-disk format to in-memory format and queue it onto
2572 * the TXN's ->changes list.
2574 * Note: although "data" is declared char*, at entry it points to a
2575 * maxalign'd buffer, making it safe in most of this function to assume
2576 * that the pointed-to data is suitably aligned for direct access.
2579 ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2582 ReorderBufferDiskChange *ondisk;
2583 ReorderBufferChange *change;
2585 ondisk = (ReorderBufferDiskChange *) data;
2587 change = ReorderBufferGetChange(rb);
2589 /* copy static part */
2590 memcpy(change, &ondisk->change, sizeof(ReorderBufferChange));
2592 data += sizeof(ReorderBufferDiskChange);
2594 /* restore individual stuff */
2595 switch (change->action)
2597 /* fall through these, they're all similar enough */
2598 case REORDER_BUFFER_CHANGE_INSERT:
2599 case REORDER_BUFFER_CHANGE_UPDATE:
2600 case REORDER_BUFFER_CHANGE_DELETE:
2601 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2602 if (change->data.tp.oldtuple)
2604 uint32 tuplelen = ((HeapTuple) data)->t_len;
2606 change->data.tp.oldtuple =
2607 ReorderBufferGetTupleBuf(rb, tuplelen - SizeofHeapTupleHeader);
2609 /* restore ->tuple */
2610 memcpy(&change->data.tp.oldtuple->tuple, data,
2611 sizeof(HeapTupleData));
2612 data += sizeof(HeapTupleData);
2614 /* reset t_data pointer into the new tuplebuf */
2615 change->data.tp.oldtuple->tuple.t_data =
2616 ReorderBufferTupleBufData(change->data.tp.oldtuple);
2618 /* restore tuple data itself */
2619 memcpy(change->data.tp.oldtuple->tuple.t_data, data, tuplelen);
2623 if (change->data.tp.newtuple)
2625 /* here, data might not be suitably aligned! */
2628 memcpy(&tuplelen, data + offsetof(HeapTupleData, t_len),
2631 change->data.tp.newtuple =
2632 ReorderBufferGetTupleBuf(rb, tuplelen - SizeofHeapTupleHeader);
2634 /* restore ->tuple */
2635 memcpy(&change->data.tp.newtuple->tuple, data,
2636 sizeof(HeapTupleData));
2637 data += sizeof(HeapTupleData);
2639 /* reset t_data pointer into the new tuplebuf */
2640 change->data.tp.newtuple->tuple.t_data =
2641 ReorderBufferTupleBufData(change->data.tp.newtuple);
2643 /* restore tuple data itself */
2644 memcpy(change->data.tp.newtuple->tuple.t_data, data, tuplelen);
2649 case REORDER_BUFFER_CHANGE_MESSAGE:
2654 memcpy(&prefix_size, data, sizeof(Size));
2655 data += sizeof(Size);
2656 change->data.msg.prefix = MemoryContextAlloc(rb->context,
2658 memcpy(change->data.msg.prefix, data, prefix_size);
2659 Assert(change->data.msg.prefix[prefix_size - 1] == '\0');
2660 data += prefix_size;
2662 /* read the message */
2663 memcpy(&change->data.msg.message_size, data, sizeof(Size));
2664 data += sizeof(Size);
2665 change->data.msg.message = MemoryContextAlloc(rb->context,
2666 change->data.msg.message_size);
2667 memcpy(change->data.msg.message, data,
2668 change->data.msg.message_size);
2669 data += change->data.msg.message_size;
2673 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2679 oldsnap = (Snapshot) data;
2681 size = sizeof(SnapshotData) +
2682 sizeof(TransactionId) * oldsnap->xcnt +
2683 sizeof(TransactionId) * (oldsnap->subxcnt + 0);
2685 change->data.snapshot = MemoryContextAllocZero(rb->context, size);
2687 newsnap = change->data.snapshot;
2689 memcpy(newsnap, data, size);
2690 newsnap->xip = (TransactionId *)
2691 (((char *) newsnap) + sizeof(SnapshotData));
2692 newsnap->subxip = newsnap->xip + newsnap->xcnt;
2693 newsnap->copied = true;
2696 /* the base struct contains all the data, easy peasy */
2697 case REORDER_BUFFER_CHANGE_TRUNCATE:
2698 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2699 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2700 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2704 dlist_push_tail(&txn->changes, &change->node);
2705 txn->nentries_mem++;
2709 * Remove all on-disk stored for the passed in transaction.
2712 ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
2718 Assert(txn->first_lsn != InvalidXLogRecPtr);
2719 Assert(txn->final_lsn != InvalidXLogRecPtr);
2721 XLByteToSeg(txn->first_lsn, first, wal_segment_size);
2722 XLByteToSeg(txn->final_lsn, last, wal_segment_size);
2724 /* iterate over all possible filenames, and delete them */
2725 for (cur = first; cur <= last; cur++)
2727 char path[MAXPGPATH];
2729 ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid, cur);
2730 if (unlink(path) != 0 && errno != ENOENT)
2732 (errcode_for_file_access(),
2733 errmsg("could not remove file \"%s\": %m", path)));
2738 * Remove any leftover serialized reorder buffers from a slot directory after a
2739 * prior crash or decoding session exit.
2742 ReorderBufferCleanupSerializedTXNs(const char *slotname)
2745 struct dirent *spill_de;
2746 struct stat statbuf;
2747 char path[MAXPGPATH * 2 + 12];
2749 sprintf(path, "pg_replslot/%s", slotname);
2751 /* we're only handling directories here, skip if it's not ours */
2752 if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
2755 spill_dir = AllocateDir(path);
2756 while ((spill_de = ReadDirExtended(spill_dir, path, INFO)) != NULL)
2758 /* only look at names that can be ours */
2759 if (strncmp(spill_de->d_name, "xid", 3) == 0)
2761 snprintf(path, sizeof(path),
2762 "pg_replslot/%s/%s", slotname,
2765 if (unlink(path) != 0)
2767 (errcode_for_file_access(),
2768 errmsg("could not remove file \"%s\" during removal of pg_replslot/%s/xid*: %m",
2776 * Given a replication slot, transaction ID and segment number, fill in the
2777 * corresponding spill file into 'path', which is a caller-owned buffer of size
2778 * at least MAXPGPATH.
2781 ReorderBufferSerializedPath(char *path, ReplicationSlot *slot, TransactionId xid,
2786 XLogSegNoOffsetToRecPtr(segno, 0, wal_segment_size, recptr);
2788 snprintf(path, MAXPGPATH, "pg_replslot/%s/xid-%u-lsn-%X-%X.tmp",
2789 NameStr(MyReplicationSlot->data.name),
2791 (uint32) (recptr >> 32), (uint32) recptr);
2795 * Delete all data spilled to disk after we've restarted/crashed. It will be
2796 * recreated when the respective slots are reused.
2799 StartupReorderBuffer(void)
2802 struct dirent *logical_de;
2804 logical_dir = AllocateDir("pg_replslot");
2805 while ((logical_de = ReadDir(logical_dir, "pg_replslot")) != NULL)
2807 if (strcmp(logical_de->d_name, ".") == 0 ||
2808 strcmp(logical_de->d_name, "..") == 0)
2811 /* if it cannot be a slot, skip the directory */
2812 if (!ReplicationSlotValidateName(logical_de->d_name, DEBUG2))
2816 * ok, has to be a surviving logical slot, iterate and delete
2817 * everything starting with xid-*
2819 ReorderBufferCleanupSerializedTXNs(logical_de->d_name);
2821 FreeDir(logical_dir);
2824 /* ---------------------------------------
2825 * toast reassembly support
2826 * ---------------------------------------
2830 * Initialize per tuple toast reconstruction support.
2833 ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
2837 Assert(txn->toast_hash == NULL);
2839 memset(&hash_ctl, 0, sizeof(hash_ctl));
2840 hash_ctl.keysize = sizeof(Oid);
2841 hash_ctl.entrysize = sizeof(ReorderBufferToastEnt);
2842 hash_ctl.hcxt = rb->context;
2843 txn->toast_hash = hash_create("ReorderBufferToastHash", 5, &hash_ctl,
2844 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
2848 * Per toast-chunk handling for toast reconstruction
2850 * Appends a toast chunk so we can reconstruct it when the tuple "owning" the
2851 * toasted Datum comes along.
2854 ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
2855 Relation relation, ReorderBufferChange *change)
2857 ReorderBufferToastEnt *ent;
2858 ReorderBufferTupleBuf *newtup;
2863 TupleDesc desc = RelationGetDescr(relation);
2867 if (txn->toast_hash == NULL)
2868 ReorderBufferToastInitHash(rb, txn);
2870 Assert(IsToastRelation(relation));
2872 newtup = change->data.tp.newtuple;
2873 chunk_id = DatumGetObjectId(fastgetattr(&newtup->tuple, 1, desc, &isnull));
2875 chunk_seq = DatumGetInt32(fastgetattr(&newtup->tuple, 2, desc, &isnull));
2878 ent = (ReorderBufferToastEnt *)
2879 hash_search(txn->toast_hash,
2886 Assert(ent->chunk_id == chunk_id);
2887 ent->num_chunks = 0;
2888 ent->last_chunk_seq = 0;
2890 ent->reconstructed = NULL;
2891 dlist_init(&ent->chunks);
2894 elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq 0",
2895 chunk_seq, chunk_id);
2897 else if (found && chunk_seq != ent->last_chunk_seq + 1)
2898 elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq %d",
2899 chunk_seq, chunk_id, ent->last_chunk_seq + 1);
2901 chunk = DatumGetPointer(fastgetattr(&newtup->tuple, 3, desc, &isnull));
2904 /* calculate size so we can allocate the right size at once later */
2905 if (!VARATT_IS_EXTENDED(chunk))
2906 chunksize = VARSIZE(chunk) - VARHDRSZ;
2907 else if (VARATT_IS_SHORT(chunk))
2908 /* could happen due to heap_form_tuple doing its thing */
2909 chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT;
2911 elog(ERROR, "unexpected type of toast chunk");
2913 ent->size += chunksize;
2914 ent->last_chunk_seq = chunk_seq;
2916 dlist_push_tail(&ent->chunks, &change->node);
2920 * Rejigger change->newtuple to point to in-memory toast tuples instead to
2921 * on-disk toast tuples that may not longer exist (think DROP TABLE or VACUUM).
2923 * We cannot replace unchanged toast tuples though, so those will still point
2924 * to on-disk toast data.
2927 ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
2928 Relation relation, ReorderBufferChange *change)
2937 TupleDesc toast_desc;
2938 MemoryContext oldcontext;
2939 ReorderBufferTupleBuf *newtup;
2941 /* no toast tuples changed */
2942 if (txn->toast_hash == NULL)
2945 oldcontext = MemoryContextSwitchTo(rb->context);
2947 /* we should only have toast tuples in an INSERT or UPDATE */
2948 Assert(change->data.tp.newtuple);
2950 desc = RelationGetDescr(relation);
2952 toast_rel = RelationIdGetRelation(relation->rd_rel->reltoastrelid);
2953 toast_desc = RelationGetDescr(toast_rel);
2955 /* should we allocate from stack instead? */
2956 attrs = palloc0(sizeof(Datum) * desc->natts);
2957 isnull = palloc0(sizeof(bool) * desc->natts);
2958 free = palloc0(sizeof(bool) * desc->natts);
2960 newtup = change->data.tp.newtuple;
2962 heap_deform_tuple(&newtup->tuple, desc, attrs, isnull);
2964 for (natt = 0; natt < desc->natts; natt++)
2966 Form_pg_attribute attr = TupleDescAttr(desc, natt);
2967 ReorderBufferToastEnt *ent;
2968 struct varlena *varlena;
2970 /* va_rawsize is the size of the original datum -- including header */
2971 struct varatt_external toast_pointer;
2972 struct varatt_indirect redirect_pointer;
2973 struct varlena *new_datum = NULL;
2974 struct varlena *reconstructed;
2978 /* system columns aren't toasted */
2979 if (attr->attnum < 0)
2982 if (attr->attisdropped)
2985 /* not a varlena datatype */
2986 if (attr->attlen != -1)
2993 /* ok, we know we have a toast datum */
2994 varlena = (struct varlena *) DatumGetPointer(attrs[natt]);
2996 /* no need to do anything if the tuple isn't external */
2997 if (!VARATT_IS_EXTERNAL(varlena))
3000 VARATT_EXTERNAL_GET_POINTER(toast_pointer, varlena);
3003 * Check whether the toast tuple changed, replace if so.
3005 ent = (ReorderBufferToastEnt *)
3006 hash_search(txn->toast_hash,
3007 (void *) &toast_pointer.va_valueid,
3014 (struct varlena *) palloc0(INDIRECT_POINTER_SIZE);
3018 reconstructed = palloc0(toast_pointer.va_rawsize);
3020 ent->reconstructed = reconstructed;
3022 /* stitch toast tuple back together from its parts */
3023 dlist_foreach(it, &ent->chunks)
3026 ReorderBufferChange *cchange;
3027 ReorderBufferTupleBuf *ctup;
3030 cchange = dlist_container(ReorderBufferChange, node, it.cur);
3031 ctup = cchange->data.tp.newtuple;
3032 chunk = DatumGetPointer(
3033 fastgetattr(&ctup->tuple, 3, toast_desc, &isnull));
3036 Assert(!VARATT_IS_EXTERNAL(chunk));
3037 Assert(!VARATT_IS_SHORT(chunk));
3039 memcpy(VARDATA(reconstructed) + data_done,
3041 VARSIZE(chunk) - VARHDRSZ);
3042 data_done += VARSIZE(chunk) - VARHDRSZ;
3044 Assert(data_done == toast_pointer.va_extsize);
3046 /* make sure its marked as compressed or not */
3047 if (VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer))
3048 SET_VARSIZE_COMPRESSED(reconstructed, data_done + VARHDRSZ);
3050 SET_VARSIZE(reconstructed, data_done + VARHDRSZ);
3052 memset(&redirect_pointer, 0, sizeof(redirect_pointer));
3053 redirect_pointer.pointer = reconstructed;
3055 SET_VARTAG_EXTERNAL(new_datum, VARTAG_INDIRECT);
3056 memcpy(VARDATA_EXTERNAL(new_datum), &redirect_pointer,
3057 sizeof(redirect_pointer));
3059 attrs[natt] = PointerGetDatum(new_datum);
3063 * Build tuple in separate memory & copy tuple back into the tuplebuf
3064 * passed to the output plugin. We can't directly heap_fill_tuple() into
3065 * the tuplebuf because attrs[] will point back into the current content.
3067 tmphtup = heap_form_tuple(desc, attrs, isnull);
3068 Assert(newtup->tuple.t_len <= MaxHeapTupleSize);
3069 Assert(ReorderBufferTupleBufData(newtup) == newtup->tuple.t_data);
3071 memcpy(newtup->tuple.t_data, tmphtup->t_data, tmphtup->t_len);
3072 newtup->tuple.t_len = tmphtup->t_len;
3075 * free resources we won't further need, more persistent stuff will be
3076 * free'd in ReorderBufferToastReset().
3078 RelationClose(toast_rel);
3080 for (natt = 0; natt < desc->natts; natt++)
3083 pfree(DatumGetPointer(attrs[natt]));
3089 MemoryContextSwitchTo(oldcontext);
3093 * Free all resources allocated for toast reconstruction.
3096 ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn)
3098 HASH_SEQ_STATUS hstat;
3099 ReorderBufferToastEnt *ent;
3101 if (txn->toast_hash == NULL)
3104 /* sequentially walk over the hash and free everything */
3105 hash_seq_init(&hstat, txn->toast_hash);
3106 while ((ent = (ReorderBufferToastEnt *) hash_seq_search(&hstat)) != NULL)
3108 dlist_mutable_iter it;
3110 if (ent->reconstructed != NULL)
3111 pfree(ent->reconstructed);
3113 dlist_foreach_modify(it, &ent->chunks)
3115 ReorderBufferChange *change =
3116 dlist_container(ReorderBufferChange, node, it.cur);
3118 dlist_delete(&change->node);
3119 ReorderBufferReturnChange(rb, change);
3123 hash_destroy(txn->toast_hash);
3124 txn->toast_hash = NULL;
3128 /* ---------------------------------------
3129 * Visibility support for logical decoding
3132 * Lookup actual cmin/cmax values when using decoding snapshot. We can't
3133 * always rely on stored cmin/cmax values because of two scenarios:
3135 * * A tuple got changed multiple times during a single transaction and thus
3136 * has got a combocid. Combocid's are only valid for the duration of a
3137 * single transaction.
3138 * * A tuple with a cmin but no cmax (and thus no combocid) got
3139 * deleted/updated in another transaction than the one which created it
3140 * which we are looking at right now. As only one of cmin, cmax or combocid
3141 * is actually stored in the heap we don't have access to the value we
3144 * To resolve those problems we have a per-transaction hash of (cmin,
3145 * cmax) tuples keyed by (relfilenode, ctid) which contains the actual
3146 * (cmin, cmax) values. That also takes care of combocids by simply
3147 * not caring about them at all. As we have the real cmin/cmax values
3148 * combocids aren't interesting.
3150 * As we only care about catalog tuples here the overhead of this
3151 * hashtable should be acceptable.
3153 * Heap rewrites complicate this a bit, check rewriteheap.c for
3155 * -------------------------------------------------------------------------
3158 /* struct for qsort()ing mapping files by lsn somewhat efficiently */
3159 typedef struct RewriteMappingFile
3162 char fname[MAXPGPATH];
3163 } RewriteMappingFile;
3167 DisplayMapping(HTAB *tuplecid_data)
3169 HASH_SEQ_STATUS hstat;
3170 ReorderBufferTupleCidEnt *ent;
3172 hash_seq_init(&hstat, tuplecid_data);
3173 while ((ent = (ReorderBufferTupleCidEnt *) hash_seq_search(&hstat)) != NULL)
3175 elog(DEBUG3, "mapping: node: %u/%u/%u tid: %u/%u cmin: %u, cmax: %u",
3176 ent->key.relnode.dbNode,
3177 ent->key.relnode.spcNode,
3178 ent->key.relnode.relNode,
3179 ItemPointerGetBlockNumber(&ent->key.tid),
3180 ItemPointerGetOffsetNumber(&ent->key.tid),
3189 * Apply a single mapping file to tuplecid_data.
3191 * The mapping file has to have been verified to be a) committed b) for our
3192 * transaction c) applied in LSN order.
3195 ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname)
3197 char path[MAXPGPATH];
3200 LogicalRewriteMappingData map;
3202 sprintf(path, "pg_logical/mappings/%s", fname);
3203 fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
3206 (errcode_for_file_access(),
3207 errmsg("could not open file \"%s\": %m", path)));
3211 ReorderBufferTupleCidKey key;
3212 ReorderBufferTupleCidEnt *ent;
3213 ReorderBufferTupleCidEnt *new_ent;
3216 /* be careful about padding */
3217 memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
3219 /* read all mappings till the end of the file */
3220 pgstat_report_wait_start(WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ);
3221 readBytes = read(fd, &map, sizeof(LogicalRewriteMappingData));
3222 pgstat_report_wait_end();
3226 (errcode_for_file_access(),
3227 errmsg("could not read file \"%s\": %m",
3229 else if (readBytes == 0) /* EOF */
3231 else if (readBytes != sizeof(LogicalRewriteMappingData))
3233 (errcode_for_file_access(),
3234 errmsg("could not read from file \"%s\": read %d instead of %d bytes",
3236 (int32) sizeof(LogicalRewriteMappingData))));
3238 key.relnode = map.old_node;
3239 ItemPointerCopy(&map.old_tid,
3243 ent = (ReorderBufferTupleCidEnt *)
3244 hash_search(tuplecid_data,
3249 /* no existing mapping, no need to update */
3253 key.relnode = map.new_node;
3254 ItemPointerCopy(&map.new_tid,
3257 new_ent = (ReorderBufferTupleCidEnt *)
3258 hash_search(tuplecid_data,
3266 * Make sure the existing mapping makes sense. We sometime update
3267 * old records that did not yet have a cmax (e.g. pg_class' own
3268 * entry while rewriting it) during rewrites, so allow that.
3270 Assert(ent->cmin == InvalidCommandId || ent->cmin == new_ent->cmin);
3271 Assert(ent->cmax == InvalidCommandId || ent->cmax == new_ent->cmax);
3275 /* update mapping */
3276 new_ent->cmin = ent->cmin;
3277 new_ent->cmax = ent->cmax;
3278 new_ent->combocid = ent->combocid;
3282 CloseTransientFile(fd);
3287 * Check whether the TransactionOid 'xid' is in the pre-sorted array 'xip'.
3290 TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num)
3292 return bsearch(&xid, xip, num,
3293 sizeof(TransactionId), xidComparator) != NULL;
3297 * qsort() comparator for sorting RewriteMappingFiles in LSN order.
3300 file_sort_by_lsn(const void *a_p, const void *b_p)
3302 RewriteMappingFile *a = *(RewriteMappingFile **) a_p;
3303 RewriteMappingFile *b = *(RewriteMappingFile **) b_p;
3305 if (a->lsn < b->lsn)
3307 else if (a->lsn > b->lsn)
3313 * Apply any existing logical remapping files if there are any targeted at our
3314 * transaction for relid.
3317 UpdateLogicalMappings(HTAB *tuplecid_data, Oid relid, Snapshot snapshot)
3320 struct dirent *mapping_de;
3323 RewriteMappingFile **files_a;
3325 Oid dboid = IsSharedRelation(relid) ? InvalidOid : MyDatabaseId;
3327 mapping_dir = AllocateDir("pg_logical/mappings");
3328 while ((mapping_de = ReadDir(mapping_dir, "pg_logical/mappings")) != NULL)
3332 TransactionId f_mapped_xid;
3333 TransactionId f_create_xid;
3337 RewriteMappingFile *f;
3339 if (strcmp(mapping_de->d_name, ".") == 0 ||
3340 strcmp(mapping_de->d_name, "..") == 0)
3343 /* Ignore files that aren't ours */
3344 if (strncmp(mapping_de->d_name, "map-", 4) != 0)
3347 if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
3348 &f_dboid, &f_relid, &f_hi, &f_lo,
3349 &f_mapped_xid, &f_create_xid) != 6)
3350 elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
3352 f_lsn = ((uint64) f_hi) << 32 | f_lo;
3354 /* mapping for another database */
3355 if (f_dboid != dboid)
3358 /* mapping for another relation */
3359 if (f_relid != relid)
3362 /* did the creating transaction abort? */
3363 if (!TransactionIdDidCommit(f_create_xid))
3366 /* not for our transaction */
3367 if (!TransactionIdInArray(f_mapped_xid, snapshot->subxip, snapshot->subxcnt))
3370 /* ok, relevant, queue for apply */
3371 f = palloc(sizeof(RewriteMappingFile));
3373 strcpy(f->fname, mapping_de->d_name);
3374 files = lappend(files, f);
3376 FreeDir(mapping_dir);
3378 /* build array we can easily sort */
3379 files_a = palloc(list_length(files) * sizeof(RewriteMappingFile *));
3381 foreach(file, files)
3383 files_a[off++] = lfirst(file);
3386 /* sort files so we apply them in LSN order */
3387 qsort(files_a, list_length(files), sizeof(RewriteMappingFile *),
3390 for (off = 0; off < list_length(files); off++)
3392 RewriteMappingFile *f = files_a[off];
3394 elog(DEBUG1, "applying mapping: \"%s\" in %u", f->fname,
3395 snapshot->subxip[0]);
3396 ApplyLogicalMappingFile(tuplecid_data, relid, f->fname);
3402 * Lookup cmin/cmax of a tuple, during logical decoding where we can't rely on
3406 ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data,
3408 HeapTuple htup, Buffer buffer,
3409 CommandId *cmin, CommandId *cmax)
3411 ReorderBufferTupleCidKey key;
3412 ReorderBufferTupleCidEnt *ent;
3414 BlockNumber blockno;
3415 bool updated_mapping = false;
3417 /* be careful about padding */
3418 memset(&key, 0, sizeof(key));
3420 Assert(!BufferIsLocal(buffer));
3423 * get relfilenode from the buffer, no convenient way to access it other
3426 BufferGetTag(buffer, &key.relnode, &forkno, &blockno);
3428 /* tuples can only be in the main fork */
3429 Assert(forkno == MAIN_FORKNUM);
3430 Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self));
3432 ItemPointerCopy(&htup->t_self,
3436 ent = (ReorderBufferTupleCidEnt *)
3437 hash_search(tuplecid_data,
3443 * failed to find a mapping, check whether the table was rewritten and
3444 * apply mapping if so, but only do that once - there can be no new
3445 * mappings while we are in here since we have to hold a lock on the
3448 if (ent == NULL && !updated_mapping)
3450 UpdateLogicalMappings(tuplecid_data, htup->t_tableOid, snapshot);
3451 /* now check but don't update for a mapping again */
3452 updated_mapping = true;
3455 else if (ent == NULL)