PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
reorderbuffer.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * reorderbuffer.c
4  * PostgreSQL logical replay/reorder buffer management
5  *
6  *
7  * Copyright (c) 2012-2016, PostgreSQL Global Development Group
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/replication/reorderbuffer.c
12  *
13  * NOTES
14  * This module gets handed individual pieces of transactions in the order
15  * they are written to the WAL and is responsible to reassemble them into
16  * toplevel transaction sized pieces. When a transaction is completely
17  * reassembled - signalled by reading the transaction commit record - it
18  * will then call the output plugin (c.f. ReorderBufferCommit()) with the
19  * individual changes. The output plugins rely on snapshots built by
20  * snapbuild.c which hands them to us.
21  *
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.
32  *
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
37  * chunks.
38  *
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
45  * details.
46  * -------------------------------------------------------------------------
47  */
48 #include "postgres.h"
49 
50 #include <unistd.h>
51 #include <sys/stat.h>
52 
53 #include "access/rewriteheap.h"
54 #include "access/transam.h"
55 #include "access/tuptoaster.h"
56 #include "access/xact.h"
57 #include "access/xlog_internal.h"
58 #include "catalog/catalog.h"
59 #include "lib/binaryheap.h"
60 #include "miscadmin.h"
61 #include "replication/logical.h"
63 #include "replication/slot.h"
64 #include "replication/snapbuild.h" /* just for SnapBuildSnapDecRefcount */
65 #include "storage/bufmgr.h"
66 #include "storage/fd.h"
67 #include "storage/sinval.h"
68 #include "utils/builtins.h"
69 #include "utils/combocid.h"
70 #include "utils/memdebug.h"
71 #include "utils/memutils.h"
72 #include "utils/rel.h"
73 #include "utils/relfilenodemap.h"
74 #include "utils/tqual.h"
75 
76 
77 /* entry for a hash table we use to map from xid to our transaction state */
79 {
83 
84 /* data structures for (relfilenode, ctid) => (cmin, cmax) mapping */
86 {
90 
92 {
96  CommandId combocid; /* just for debugging */
98 
99 /* k-way in-order change iteration support structures */
101 {
105  int fd;
108 
110 {
114  ReorderBufferIterTXNEntry entries[FLEXIBLE_ARRAY_MEMBER];
116 
117 /* toast datastructures */
118 typedef struct ReorderBufferToastEnt
119 {
120  Oid chunk_id; /* toast_table.chunk_id */
121  int32 last_chunk_seq; /* toast_table.chunk_seq of the last chunk we
122  * have seen */
123  Size num_chunks; /* number of chunks we've already seen */
124  Size size; /* combined size of chunks seen */
125  dlist_head chunks; /* linked list of chunks */
126  struct varlena *reconstructed; /* reconstructed varlena now pointed
127  * to in main tup */
129 
130 /* Disk serialization support datastructures */
132 {
135  /* data follows */
137 
138 /*
139  * Maximum number of changes kept in memory, per transaction. After that,
140  * changes are spooled to disk.
141  *
142  * The current value should be sufficient to decode the entire transaction
143  * without hitting disk in OLTP workloads, while starting to spool to disk in
144  * other workloads reasonably fast.
145  *
146  * At some point in the future it probably makes sense to have a more elaborate
147  * resource management here, but it's not entirely clear what that would look
148  * like.
149  */
150 static const Size max_changes_in_memory = 4096;
151 
152 /*
153  * We use a very simple form of a slab allocator for frequently allocated
154  * objects, simply keeping a fixed number in a linked list when unused,
155  * instead pfree()ing them. Without that in many workloads aset.c becomes a
156  * major bottleneck, especially when spilling to disk while decoding batch
157  * workloads.
158  */
159 static const Size max_cached_changes = 4096 * 2;
160 static const Size max_cached_tuplebufs = 4096 * 2; /* ~8MB */
161 static const Size max_cached_transactions = 512;
162 
163 
164 /* ---------------------------------------
165  * primary reorderbuffer support routines
166  * ---------------------------------------
167  */
171  TransactionId xid, bool create, bool *is_new,
172  XLogRecPtr lsn, bool create_as_top);
173 
174 static void AssertTXNLsnOrder(ReorderBuffer *rb);
175 
176 /* ---------------------------------------
177  * support functions for lsn-order iterating over the ->changes of a
178  * transaction and its subtransactions
179  *
180  * used for iteration over the k-way heap merge of a transaction and its
181  * subtransactions
182  * ---------------------------------------
183  */
185 static ReorderBufferChange *
190 
191 /*
192  * ---------------------------------------
193  * Disk serialization support functions
194  * ---------------------------------------
195  */
199  int fd, ReorderBufferChange *change);
201  int *fd, XLogSegNo *segno);
203  char *change);
205 
206 static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap);
208  ReorderBufferTXN *txn, CommandId cid);
209 
210 /* ---------------------------------------
211  * toast reassembly support
212  * ---------------------------------------
213  */
217  Relation relation, ReorderBufferChange *change);
219  Relation relation, ReorderBufferChange *change);
220 
221 
222 /*
223  * Allocate a new ReorderBuffer
224  */
227 {
228  ReorderBuffer *buffer;
229  HASHCTL hash_ctl;
230  MemoryContext new_ctx;
231 
232  /* allocate memory in own context, to have better accountability */
234  "ReorderBuffer",
238 
239  buffer =
240  (ReorderBuffer *) MemoryContextAlloc(new_ctx, sizeof(ReorderBuffer));
241 
242  memset(&hash_ctl, 0, sizeof(hash_ctl));
243 
244  buffer->context = new_ctx;
245 
246  hash_ctl.keysize = sizeof(TransactionId);
247  hash_ctl.entrysize = sizeof(ReorderBufferTXNByIdEnt);
248  hash_ctl.hcxt = buffer->context;
249 
250  buffer->by_txn = hash_create("ReorderBufferByXid", 1000, &hash_ctl,
252 
254  buffer->by_txn_last_txn = NULL;
255 
256  buffer->nr_cached_transactions = 0;
257  buffer->nr_cached_changes = 0;
258  buffer->nr_cached_tuplebufs = 0;
259 
260  buffer->outbuf = NULL;
261  buffer->outbufsize = 0;
262 
264 
265  dlist_init(&buffer->toplevel_by_lsn);
267  dlist_init(&buffer->cached_changes);
268  slist_init(&buffer->cached_tuplebufs);
269 
270  return buffer;
271 }
272 
273 /*
274  * Free a ReorderBuffer
275  */
276 void
278 {
279  MemoryContext context = rb->context;
280 
281  /*
282  * We free separately allocated data by entirely scrapping reorderbuffer's
283  * memory context.
284  */
285  MemoryContextDelete(context);
286 }
287 
288 /*
289  * Get an unused, possibly preallocated, ReorderBufferTXN.
290  */
291 static ReorderBufferTXN *
293 {
294  ReorderBufferTXN *txn;
295 
296  /* check the slab cache */
297  if (rb->nr_cached_transactions > 0)
298  {
300  txn = (ReorderBufferTXN *)
303  }
304  else
305  {
306  txn = (ReorderBufferTXN *)
308  }
309 
310  memset(txn, 0, sizeof(ReorderBufferTXN));
311 
312  dlist_init(&txn->changes);
313  dlist_init(&txn->tuplecids);
314  dlist_init(&txn->subtxns);
315 
316  return txn;
317 }
318 
319 /*
320  * Free a ReorderBufferTXN.
321  *
322  * Deallocation might be delayed for efficiency purposes, for details check
323  * the comments above max_cached_changes's definition.
324  */
325 static void
327 {
328  /* clean the lookup cache if we were cached (quite likely) */
329  if (rb->by_txn_last_xid == txn->xid)
330  {
332  rb->by_txn_last_txn = NULL;
333  }
334 
335  /* free data that's contained */
336 
337  if (txn->tuplecid_hash != NULL)
338  {
340  txn->tuplecid_hash = NULL;
341  }
342 
343  if (txn->invalidations)
344  {
345  pfree(txn->invalidations);
346  txn->invalidations = NULL;
347  }
348 
349  /* check whether to put into the slab cache */
351  {
355  VALGRIND_MAKE_MEM_DEFINED(&txn->node, sizeof(txn->node));
356  }
357  else
358  {
359  pfree(txn);
360  }
361 }
362 
363 /*
364  * Get an unused, possibly preallocated, ReorderBufferChange.
365  */
368 {
369  ReorderBufferChange *change;
370 
371  /* check the slab cache */
372  if (rb->nr_cached_changes)
373  {
374  rb->nr_cached_changes--;
375  change = (ReorderBufferChange *)
378  }
379  else
380  {
381  change = (ReorderBufferChange *)
383  }
384 
385  memset(change, 0, sizeof(ReorderBufferChange));
386  return change;
387 }
388 
389 /*
390  * Free an ReorderBufferChange.
391  *
392  * Deallocation might be delayed for efficiency purposes, for details check
393  * the comments above max_cached_changes's definition.
394  */
395 void
397 {
398  /* free contained data */
399  switch (change->action)
400  {
405  if (change->data.tp.newtuple)
406  {
407  ReorderBufferReturnTupleBuf(rb, change->data.tp.newtuple);
408  change->data.tp.newtuple = NULL;
409  }
410 
411  if (change->data.tp.oldtuple)
412  {
413  ReorderBufferReturnTupleBuf(rb, change->data.tp.oldtuple);
414  change->data.tp.oldtuple = NULL;
415  }
416  break;
418  if (change->data.msg.prefix != NULL)
419  pfree(change->data.msg.prefix);
420  change->data.msg.prefix = NULL;
421  if (change->data.msg.message != NULL)
422  pfree(change->data.msg.message);
423  change->data.msg.message = NULL;
424  break;
426  if (change->data.snapshot)
427  {
428  ReorderBufferFreeSnap(rb, change->data.snapshot);
429  change->data.snapshot = NULL;
430  }
431  break;
432  /* no data in addition to the struct itself */
436  break;
437  }
438 
439  /* check whether to put into the slab cache */
441  {
442  rb->nr_cached_changes++;
443  dlist_push_head(&rb->cached_changes, &change->node);
445  VALGRIND_MAKE_MEM_DEFINED(&change->node, sizeof(change->node));
446  }
447  else
448  {
449  pfree(change);
450  }
451 }
452 
453 
454 /*
455  * Get an unused, possibly preallocated, ReorderBufferTupleBuf fitting at
456  * least a tuple of size tuple_len (excluding header overhead).
457  */
460 {
461  ReorderBufferTupleBuf *tuple;
462  Size alloc_len;
463 
464  alloc_len = tuple_len + SizeofHeapTupleHeader;
465 
466  /*
467  * Most tuples are below MaxHeapTupleSize, so we use a slab allocator for
468  * those. Thus always allocate at least MaxHeapTupleSize. Note that tuples
469  * tuples generated for oldtuples can be bigger, as they don't have
470  * out-of-line toast columns.
471  */
472  if (alloc_len < MaxHeapTupleSize)
473  alloc_len = MaxHeapTupleSize;
474 
475 
476  /* if small enough, check the slab cache */
477  if (alloc_len <= MaxHeapTupleSize && rb->nr_cached_tuplebufs)
478  {
479  rb->nr_cached_tuplebufs--;
483 #ifdef USE_ASSERT_CHECKING
484  memset(&tuple->tuple, 0xa9, sizeof(HeapTupleData));
486 #endif
487  tuple->tuple.t_data = ReorderBufferTupleBufData(tuple);
488 #ifdef USE_ASSERT_CHECKING
489  memset(tuple->tuple.t_data, 0xa8, tuple->alloc_tuple_size);
491 #endif
492  }
493  else
494  {
495  tuple = (ReorderBufferTupleBuf *)
497  sizeof(ReorderBufferTupleBuf) +
498  MAXIMUM_ALIGNOF + alloc_len);
499  tuple->alloc_tuple_size = alloc_len;
500  tuple->tuple.t_data = ReorderBufferTupleBufData(tuple);
501  }
502 
503  return tuple;
504 }
505 
506 /*
507  * Free an ReorderBufferTupleBuf.
508  *
509  * Deallocation might be delayed for efficiency purposes, for details check
510  * the comments above max_cached_changes's definition.
511  */
512 void
514 {
515  /* check whether to put into the slab cache, oversized tuples never are */
516  if (tuple->alloc_tuple_size == MaxHeapTupleSize &&
518  {
519  rb->nr_cached_tuplebufs++;
520  slist_push_head(&rb->cached_tuplebufs, &tuple->node);
523  VALGRIND_MAKE_MEM_DEFINED(&tuple->node, sizeof(tuple->node));
525  }
526  else
527  {
528  pfree(tuple);
529  }
530 }
531 
532 /*
533  * Return the ReorderBufferTXN from the given buffer, specified by Xid.
534  * If create is true, and a transaction doesn't already exist, create it
535  * (with the given LSN, and as top transaction if that's specified);
536  * when this happens, is_new is set to true.
537  */
538 static ReorderBufferTXN *
540  bool *is_new, XLogRecPtr lsn, bool create_as_top)
541 {
542  ReorderBufferTXN *txn;
544  bool found;
545 
547  Assert(!create || lsn != InvalidXLogRecPtr);
548 
549  /*
550  * Check the one-entry lookup cache first
551  */
553  rb->by_txn_last_xid == xid)
554  {
555  txn = rb->by_txn_last_txn;
556 
557  if (txn != NULL)
558  {
559  /* found it, and it's valid */
560  if (is_new)
561  *is_new = false;
562  return txn;
563  }
564 
565  /*
566  * cached as non-existent, and asked not to create? Then nothing else
567  * to do.
568  */
569  if (!create)
570  return NULL;
571  /* otherwise fall through to create it */
572  }
573 
574  /*
575  * If the cache wasn't hit or it yielded an "does-not-exist" and we want
576  * to create an entry.
577  */
578 
579  /* search the lookup table */
580  ent = (ReorderBufferTXNByIdEnt *)
581  hash_search(rb->by_txn,
582  (void *) &xid,
583  create ? HASH_ENTER : HASH_FIND,
584  &found);
585  if (found)
586  txn = ent->txn;
587  else if (create)
588  {
589  /* initialize the new entry, if creation was requested */
590  Assert(ent != NULL);
591 
592  ent->txn = ReorderBufferGetTXN(rb);
593  ent->txn->xid = xid;
594  txn = ent->txn;
595  txn->first_lsn = lsn;
597 
598  if (create_as_top)
599  {
600  dlist_push_tail(&rb->toplevel_by_lsn, &txn->node);
601  AssertTXNLsnOrder(rb);
602  }
603  }
604  else
605  txn = NULL; /* not found and not asked to create */
606 
607  /* update cache */
608  rb->by_txn_last_xid = xid;
609  rb->by_txn_last_txn = txn;
610 
611  if (is_new)
612  *is_new = !found;
613 
614  Assert(!create || txn != NULL);
615  return txn;
616 }
617 
618 /*
619  * Queue a change into a transaction so it can be replayed upon commit.
620  */
621 void
623  ReorderBufferChange *change)
624 {
625  ReorderBufferTXN *txn;
626 
627  txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
628 
629  change->lsn = lsn;
630  Assert(InvalidXLogRecPtr != lsn);
631  dlist_push_tail(&txn->changes, &change->node);
632  txn->nentries++;
633  txn->nentries_mem++;
634 
636 }
637 
638 /*
639  * Queue message into a transaction so it can be processed upon commit.
640  */
641 void
643  Snapshot snapshot, XLogRecPtr lsn,
644  bool transactional, const char *prefix,
645  Size message_size, const char *message)
646 {
647  if (transactional)
648  {
649  MemoryContext oldcontext;
650  ReorderBufferChange *change;
651 
653 
654  oldcontext = MemoryContextSwitchTo(rb->context);
655 
656  change = ReorderBufferGetChange(rb);
658  change->data.msg.prefix = pstrdup(prefix);
659  change->data.msg.message_size = message_size;
660  change->data.msg.message = palloc(message_size);
661  memcpy(change->data.msg.message, message, message_size);
662 
663  ReorderBufferQueueChange(rb, xid, lsn, change);
664 
665  MemoryContextSwitchTo(oldcontext);
666  }
667  else
668  {
669  ReorderBufferTXN *txn = NULL;
670  volatile Snapshot snapshot_now = snapshot;
671 
672  if (xid != InvalidTransactionId)
673  txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
674 
675  /* setup snapshot to allow catalog access */
676  SetupHistoricSnapshot(snapshot_now, NULL);
677  PG_TRY();
678  {
679  rb->message(rb, txn, lsn, false, prefix, message_size, message);
680 
682  }
683  PG_CATCH();
684  {
686  PG_RE_THROW();
687  }
688  PG_END_TRY();
689  }
690 }
691 
692 
693 static void
695 {
696 #ifdef USE_ASSERT_CHECKING
697  dlist_iter iter;
698  XLogRecPtr prev_first_lsn = InvalidXLogRecPtr;
699 
700  dlist_foreach(iter, &rb->toplevel_by_lsn)
701  {
702  ReorderBufferTXN *cur_txn;
703 
704  cur_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
705  Assert(cur_txn->first_lsn != InvalidXLogRecPtr);
706 
707  if (cur_txn->end_lsn != InvalidXLogRecPtr)
708  Assert(cur_txn->first_lsn <= cur_txn->end_lsn);
709 
710  if (prev_first_lsn != InvalidXLogRecPtr)
711  Assert(prev_first_lsn < cur_txn->first_lsn);
712 
713  Assert(!cur_txn->is_known_as_subxact);
714  prev_first_lsn = cur_txn->first_lsn;
715  }
716 #endif
717 }
718 
721 {
722  ReorderBufferTXN *txn;
723 
725  return NULL;
726 
727  AssertTXNLsnOrder(rb);
728 
730 
733  return txn;
734 }
735 
736 void
738 {
740 }
741 
742 void
744  TransactionId subxid, XLogRecPtr lsn)
745 {
746  ReorderBufferTXN *txn;
747  ReorderBufferTXN *subtxn;
748  bool new_top;
749  bool new_sub;
750 
751  txn = ReorderBufferTXNByXid(rb, xid, true, &new_top, lsn, true);
752  subtxn = ReorderBufferTXNByXid(rb, subxid, true, &new_sub, lsn, false);
753 
754  if (new_sub)
755  {
756  /*
757  * we assign subtransactions to top level transaction even if we don't
758  * have data for it yet, assignment records frequently reference xids
759  * that have not yet produced any records. Knowing those aren't top
760  * level xids allows us to make processing cheaper in some places.
761  */
762  dlist_push_tail(&txn->subtxns, &subtxn->node);
763  txn->nsubtxns++;
764  }
765  else if (!subtxn->is_known_as_subxact)
766  {
767  subtxn->is_known_as_subxact = true;
768  Assert(subtxn->nsubtxns == 0);
769 
770  /* remove from lsn order list of top-level transactions */
771  dlist_delete(&subtxn->node);
772 
773  /* add to toplevel transaction */
774  dlist_push_tail(&txn->subtxns, &subtxn->node);
775  txn->nsubtxns++;
776  }
777  else if (new_top)
778  {
779  elog(ERROR, "existing subxact assigned to unknown toplevel xact");
780  }
781 }
782 
783 /*
784  * Associate a subtransaction with its toplevel transaction at commit
785  * time. There may be no further changes added after this.
786  */
787 void
789  TransactionId subxid, XLogRecPtr commit_lsn,
790  XLogRecPtr end_lsn)
791 {
792  ReorderBufferTXN *txn;
793  ReorderBufferTXN *subtxn;
794 
795  subtxn = ReorderBufferTXNByXid(rb, subxid, false, NULL,
796  InvalidXLogRecPtr, false);
797 
798  /*
799  * No need to do anything if that subtxn didn't contain any changes
800  */
801  if (!subtxn)
802  return;
803 
804  txn = ReorderBufferTXNByXid(rb, xid, false, NULL, commit_lsn, true);
805 
806  if (txn == NULL)
807  elog(ERROR, "subxact logged without previous toplevel record");
808 
809  /*
810  * Pass the our base snapshot to the parent transaction if it doesn't have
811  * one, or ours is older. That can happen if there are no changes in the
812  * toplevel transaction but in one of the child transactions. This allows
813  * the parent to simply use it's base snapshot initially.
814  */
815  if (txn->base_snapshot == NULL ||
816  txn->base_snapshot_lsn > subtxn->base_snapshot_lsn)
817  {
818  txn->base_snapshot = subtxn->base_snapshot;
819  txn->base_snapshot_lsn = subtxn->base_snapshot_lsn;
820  subtxn->base_snapshot = NULL;
822  }
823 
824  subtxn->final_lsn = commit_lsn;
825  subtxn->end_lsn = end_lsn;
826 
827  if (!subtxn->is_known_as_subxact)
828  {
829  subtxn->is_known_as_subxact = true;
830  Assert(subtxn->nsubtxns == 0);
831 
832  /* remove from lsn order list of top-level transactions */
833  dlist_delete(&subtxn->node);
834 
835  /* add to subtransaction list */
836  dlist_push_tail(&txn->subtxns, &subtxn->node);
837  txn->nsubtxns++;
838  }
839 }
840 
841 
842 /*
843  * Support for efficiently iterating over a transaction's and its
844  * subtransactions' changes.
845  *
846  * We do by doing a k-way merge between transactions/subtransactions. For that
847  * we model the current heads of the different transactions as a binary heap
848  * so we easily know which (sub-)transaction has the change with the smallest
849  * lsn next.
850  *
851  * We assume the changes in individual transactions are already sorted by LSN.
852  */
853 
854 /*
855  * Binary heap comparison function.
856  */
857 static int
859 {
861  XLogRecPtr pos_a = state->entries[DatumGetInt32(a)].lsn;
862  XLogRecPtr pos_b = state->entries[DatumGetInt32(b)].lsn;
863 
864  if (pos_a < pos_b)
865  return 1;
866  else if (pos_a == pos_b)
867  return 0;
868  return -1;
869 }
870 
871 /*
872  * Allocate & initialize an iterator which iterates in lsn order over a
873  * transaction and all its subtransactions.
874  */
877 {
878  Size nr_txns = 0;
880  dlist_iter cur_txn_i;
881  int32 off;
882 
883  /*
884  * Calculate the size of our heap: one element for every transaction that
885  * contains changes. (Besides the transactions already in the reorder
886  * buffer, we count the one we were directly passed.)
887  */
888  if (txn->nentries > 0)
889  nr_txns++;
890 
891  dlist_foreach(cur_txn_i, &txn->subtxns)
892  {
893  ReorderBufferTXN *cur_txn;
894 
895  cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
896 
897  if (cur_txn->nentries > 0)
898  nr_txns++;
899  }
900 
901  /*
902  * TODO: Consider adding fastpath for the rather common nr_txns=1 case, no
903  * need to allocate/build a heap then.
904  */
905 
906  /* allocate iteration state */
907  state = (ReorderBufferIterTXNState *)
909  sizeof(ReorderBufferIterTXNState) +
910  sizeof(ReorderBufferIterTXNEntry) * nr_txns);
911 
912  state->nr_txns = nr_txns;
913  dlist_init(&state->old_change);
914 
915  for (off = 0; off < state->nr_txns; off++)
916  {
917  state->entries[off].fd = -1;
918  state->entries[off].segno = 0;
919  }
920 
921  /* allocate heap */
922  state->heap = binaryheap_allocate(state->nr_txns,
924  state);
925 
926  /*
927  * Now insert items into the binary heap, in an unordered fashion. (We
928  * will run a heap assembly step at the end; this is more efficient.)
929  */
930 
931  off = 0;
932 
933  /* add toplevel transaction if it contains changes */
934  if (txn->nentries > 0)
935  {
936  ReorderBufferChange *cur_change;
937 
938  if (txn->nentries != txn->nentries_mem)
939  ReorderBufferRestoreChanges(rb, txn, &state->entries[off].fd,
940  &state->entries[off].segno);
941 
942  cur_change = dlist_head_element(ReorderBufferChange, node,
943  &txn->changes);
944 
945  state->entries[off].lsn = cur_change->lsn;
946  state->entries[off].change = cur_change;
947  state->entries[off].txn = txn;
948 
950  }
951 
952  /* add subtransactions if they contain changes */
953  dlist_foreach(cur_txn_i, &txn->subtxns)
954  {
955  ReorderBufferTXN *cur_txn;
956 
957  cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
958 
959  if (cur_txn->nentries > 0)
960  {
961  ReorderBufferChange *cur_change;
962 
963  if (txn->nentries != txn->nentries_mem)
964  ReorderBufferRestoreChanges(rb, cur_txn,
965  &state->entries[off].fd,
966  &state->entries[off].segno);
967 
968  cur_change = dlist_head_element(ReorderBufferChange, node,
969  &cur_txn->changes);
970 
971  state->entries[off].lsn = cur_change->lsn;
972  state->entries[off].change = cur_change;
973  state->entries[off].txn = cur_txn;
974 
976  }
977  }
978 
979  /* assemble a valid binary heap */
980  binaryheap_build(state->heap);
981 
982  return state;
983 }
984 
985 /*
986  * Return the next change when iterating over a transaction and its
987  * subtransactions.
988  *
989  * Returns NULL when no further changes exist.
990  */
991 static ReorderBufferChange *
993 {
994  ReorderBufferChange *change;
996  int32 off;
997 
998  /* nothing there anymore */
999  if (state->heap->bh_size == 0)
1000  return NULL;
1001 
1002  off = DatumGetInt32(binaryheap_first(state->heap));
1003  entry = &state->entries[off];
1004 
1005  /* free memory we might have "leaked" in the previous *Next call */
1006  if (!dlist_is_empty(&state->old_change))
1007  {
1008  change = dlist_container(ReorderBufferChange, node,
1009  dlist_pop_head_node(&state->old_change));
1010  ReorderBufferReturnChange(rb, change);
1011  Assert(dlist_is_empty(&state->old_change));
1012  }
1013 
1014  change = entry->change;
1015 
1016  /*
1017  * update heap with information about which transaction has the next
1018  * relevant change in LSN order
1019  */
1020 
1021  /* there are in-memory changes */
1022  if (dlist_has_next(&entry->txn->changes, &entry->change->node))
1023  {
1024  dlist_node *next = dlist_next_node(&entry->txn->changes, &change->node);
1025  ReorderBufferChange *next_change =
1026  dlist_container(ReorderBufferChange, node, next);
1027 
1028  /* txn stays the same */
1029  state->entries[off].lsn = next_change->lsn;
1030  state->entries[off].change = next_change;
1031 
1033  return change;
1034  }
1035 
1036  /* try to load changes from disk */
1037  if (entry->txn->nentries != entry->txn->nentries_mem)
1038  {
1039  /*
1040  * Ugly: restoring changes will reuse *Change records, thus delete the
1041  * current one from the per-tx list and only free in the next call.
1042  */
1043  dlist_delete(&change->node);
1044  dlist_push_tail(&state->old_change, &change->node);
1045 
1046  if (ReorderBufferRestoreChanges(rb, entry->txn, &entry->fd,
1047  &state->entries[off].segno))
1048  {
1049  /* successfully restored changes from disk */
1050  ReorderBufferChange *next_change =
1052  &entry->txn->changes);
1053 
1054  elog(DEBUG2, "restored %u/%u changes from disk",
1055  (uint32) entry->txn->nentries_mem,
1056  (uint32) entry->txn->nentries);
1057 
1058  Assert(entry->txn->nentries_mem);
1059  /* txn stays the same */
1060  state->entries[off].lsn = next_change->lsn;
1061  state->entries[off].change = next_change;
1063 
1064  return change;
1065  }
1066  }
1067 
1068  /* ok, no changes there anymore, remove */
1069  binaryheap_remove_first(state->heap);
1070 
1071  return change;
1072 }
1073 
1074 /*
1075  * Deallocate the iterator
1076  */
1077 static void
1080 {
1081  int32 off;
1082 
1083  for (off = 0; off < state->nr_txns; off++)
1084  {
1085  if (state->entries[off].fd != -1)
1086  CloseTransientFile(state->entries[off].fd);
1087  }
1088 
1089  /* free memory we might have "leaked" in the last *Next call */
1090  if (!dlist_is_empty(&state->old_change))
1091  {
1092  ReorderBufferChange *change;
1093 
1094  change = dlist_container(ReorderBufferChange, node,
1095  dlist_pop_head_node(&state->old_change));
1096  ReorderBufferReturnChange(rb, change);
1097  Assert(dlist_is_empty(&state->old_change));
1098  }
1099 
1100  binaryheap_free(state->heap);
1101  pfree(state);
1102 }
1103 
1104 /*
1105  * Cleanup the contents of a transaction, usually after the transaction
1106  * committed or aborted.
1107  */
1108 static void
1110 {
1111  bool found;
1112  dlist_mutable_iter iter;
1113 
1114  /* cleanup subtransactions & their changes */
1115  dlist_foreach_modify(iter, &txn->subtxns)
1116  {
1117  ReorderBufferTXN *subtxn;
1118 
1119  subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
1120 
1121  /*
1122  * Subtransactions are always associated to the toplevel TXN, even if
1123  * they originally were happening inside another subtxn, so we won't
1124  * ever recurse more than one level deep here.
1125  */
1126  Assert(subtxn->is_known_as_subxact);
1127  Assert(subtxn->nsubtxns == 0);
1128 
1129  ReorderBufferCleanupTXN(rb, subtxn);
1130  }
1131 
1132  /* cleanup changes in the toplevel txn */
1133  dlist_foreach_modify(iter, &txn->changes)
1134  {
1135  ReorderBufferChange *change;
1136 
1137  change = dlist_container(ReorderBufferChange, node, iter.cur);
1138 
1139  ReorderBufferReturnChange(rb, change);
1140  }
1141 
1142  /*
1143  * Cleanup the tuplecids we stored for decoding catalog snapshot access.
1144  * They are always stored in the toplevel transaction.
1145  */
1146  dlist_foreach_modify(iter, &txn->tuplecids)
1147  {
1148  ReorderBufferChange *change;
1149 
1150  change = dlist_container(ReorderBufferChange, node, iter.cur);
1152  ReorderBufferReturnChange(rb, change);
1153  }
1154 
1155  if (txn->base_snapshot != NULL)
1156  {
1158  txn->base_snapshot = NULL;
1160  }
1161 
1162  /* delete from list of known subxacts */
1163  if (txn->is_known_as_subxact)
1164  {
1165  /* NB: nsubxacts count of parent will be too high now */
1166  dlist_delete(&txn->node);
1167  }
1168  /* delete from LSN ordered list of toplevel TXNs */
1169  else
1170  {
1171  dlist_delete(&txn->node);
1172  }
1173 
1174  /* now remove reference from buffer */
1175  hash_search(rb->by_txn,
1176  (void *) &txn->xid,
1177  HASH_REMOVE,
1178  &found);
1179  Assert(found);
1180 
1181  /* remove entries spilled to disk */
1182  if (txn->nentries != txn->nentries_mem)
1183  ReorderBufferRestoreCleanup(rb, txn);
1184 
1185  /* deallocate */
1186  ReorderBufferReturnTXN(rb, txn);
1187 }
1188 
1189 /*
1190  * Build a hash with a (relfilenode, ctid) -> (cmin, cmax) mapping for use by
1191  * tqual.c's HeapTupleSatisfiesHistoricMVCC.
1192  */
1193 static void
1195 {
1196  dlist_iter iter;
1197  HASHCTL hash_ctl;
1198 
1199  if (!txn->has_catalog_changes || dlist_is_empty(&txn->tuplecids))
1200  return;
1201 
1202  memset(&hash_ctl, 0, sizeof(hash_ctl));
1203 
1204  hash_ctl.keysize = sizeof(ReorderBufferTupleCidKey);
1205  hash_ctl.entrysize = sizeof(ReorderBufferTupleCidEnt);
1206  hash_ctl.hcxt = rb->context;
1207 
1208  /*
1209  * create the hash with the exact number of to-be-stored tuplecids from
1210  * the start
1211  */
1212  txn->tuplecid_hash =
1213  hash_create("ReorderBufferTupleCid", txn->ntuplecids, &hash_ctl,
1215 
1216  dlist_foreach(iter, &txn->tuplecids)
1217  {
1220  bool found;
1221  ReorderBufferChange *change;
1222 
1223  change = dlist_container(ReorderBufferChange, node, iter.cur);
1224 
1226 
1227  /* be careful about padding */
1228  memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
1229 
1230  key.relnode = change->data.tuplecid.node;
1231 
1232  ItemPointerCopy(&change->data.tuplecid.tid,
1233  &key.tid);
1234 
1235  ent = (ReorderBufferTupleCidEnt *)
1237  (void *) &key,
1239  &found);
1240  if (!found)
1241  {
1242  ent->cmin = change->data.tuplecid.cmin;
1243  ent->cmax = change->data.tuplecid.cmax;
1244  ent->combocid = change->data.tuplecid.combocid;
1245  }
1246  else
1247  {
1248  Assert(ent->cmin == change->data.tuplecid.cmin);
1249  Assert(ent->cmax == InvalidCommandId ||
1250  ent->cmax == change->data.tuplecid.cmax);
1251 
1252  /*
1253  * if the tuple got valid in this transaction and now got deleted
1254  * we already have a valid cmin stored. The cmax will be
1255  * InvalidCommandId though.
1256  */
1257  ent->cmax = change->data.tuplecid.cmax;
1258  }
1259  }
1260 }
1261 
1262 /*
1263  * Copy a provided snapshot so we can modify it privately. This is needed so
1264  * that catalog modifying transactions can look into intermediate catalog
1265  * states.
1266  */
1267 static Snapshot
1269  ReorderBufferTXN *txn, CommandId cid)
1270 {
1271  Snapshot snap;
1272  dlist_iter iter;
1273  int i = 0;
1274  Size size;
1275 
1276  size = sizeof(SnapshotData) +
1277  sizeof(TransactionId) * orig_snap->xcnt +
1278  sizeof(TransactionId) * (txn->nsubtxns + 1);
1279 
1280  snap = MemoryContextAllocZero(rb->context, size);
1281  memcpy(snap, orig_snap, sizeof(SnapshotData));
1282 
1283  snap->copied = true;
1284  snap->active_count = 1; /* mark as active so nobody frees it */
1285  snap->regd_count = 0;
1286  snap->xip = (TransactionId *) (snap + 1);
1287 
1288  memcpy(snap->xip, orig_snap->xip, sizeof(TransactionId) * snap->xcnt);
1289 
1290  /*
1291  * snap->subxip contains all txids that belong to our transaction which we
1292  * need to check via cmin/cmax. Thats why we store the toplevel
1293  * transaction in there as well.
1294  */
1295  snap->subxip = snap->xip + snap->xcnt;
1296  snap->subxip[i++] = txn->xid;
1297 
1298  /*
1299  * nsubxcnt isn't decreased when subtransactions abort, so count manually.
1300  * Since it's an upper boundary it is safe to use it for the allocation
1301  * above.
1302  */
1303  snap->subxcnt = 1;
1304 
1305  dlist_foreach(iter, &txn->subtxns)
1306  {
1307  ReorderBufferTXN *sub_txn;
1308 
1309  sub_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
1310  snap->subxip[i++] = sub_txn->xid;
1311  snap->subxcnt++;
1312  }
1313 
1314  /* sort so we can bsearch() later */
1315  qsort(snap->subxip, snap->subxcnt, sizeof(TransactionId), xidComparator);
1316 
1317  /* store the specified current CommandId */
1318  snap->curcid = cid;
1319 
1320  return snap;
1321 }
1322 
1323 /*
1324  * Free a previously ReorderBufferCopySnap'ed snapshot
1325  */
1326 static void
1328 {
1329  if (snap->copied)
1330  pfree(snap);
1331  else
1333 }
1334 
1335 /*
1336  * Perform the replay of a transaction and it's non-aborted subtransactions.
1337  *
1338  * Subtransactions previously have to be processed by
1339  * ReorderBufferCommitChild(), even if previously assigned to the toplevel
1340  * transaction with ReorderBufferAssignChild.
1341  *
1342  * We currently can only decode a transaction's contents in when their commit
1343  * record is read because that's currently the only place where we know about
1344  * cache invalidations. Thus, once a toplevel commit is read, we iterate over
1345  * the top and subtransactions (using a k-way merge) and replay the changes in
1346  * lsn order.
1347  */
1348 void
1350  XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
1351  TimestampTz commit_time,
1352  RepOriginId origin_id, XLogRecPtr origin_lsn)
1353 {
1354  ReorderBufferTXN *txn;
1355  volatile Snapshot snapshot_now;
1356  volatile CommandId command_id = FirstCommandId;
1357  bool using_subtxn;
1358  ReorderBufferIterTXNState *volatile iterstate = NULL;
1359 
1360  txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1361  false);
1362 
1363  /* unknown transaction, nothing to replay */
1364  if (txn == NULL)
1365  return;
1366 
1367  txn->final_lsn = commit_lsn;
1368  txn->end_lsn = end_lsn;
1369  txn->commit_time = commit_time;
1370  txn->origin_id = origin_id;
1371  txn->origin_lsn = origin_lsn;
1372 
1373  /* serialize the last bunch of changes if we need start earlier anyway */
1374  if (txn->nentries_mem != txn->nentries)
1375  ReorderBufferSerializeTXN(rb, txn);
1376 
1377  /*
1378  * If this transaction didn't have any real changes in our database, it's
1379  * OK not to have a snapshot. Note that ReorderBufferCommitChild will have
1380  * transferred its snapshot to this transaction if it had one and the
1381  * toplevel tx didn't.
1382  */
1383  if (txn->base_snapshot == NULL)
1384  {
1385  Assert(txn->ninvalidations == 0);
1386  ReorderBufferCleanupTXN(rb, txn);
1387  return;
1388  }
1389 
1390  snapshot_now = txn->base_snapshot;
1391 
1392  /* build data to be able to lookup the CommandIds of catalog tuples */
1394 
1395  /* setup the initial snapshot */
1396  SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1397 
1398  /*
1399  * Decoding needs access to syscaches et al., which in turn use
1400  * heavyweight locks and such. Thus we need to have enough state around to
1401  * keep track of those. The easiest way is to simply use a transaction
1402  * internally. That also allows us to easily enforce that nothing writes
1403  * to the database by checking for xid assignments.
1404  *
1405  * When we're called via the SQL SRF there's already a transaction
1406  * started, so start an explicit subtransaction there.
1407  */
1408  using_subtxn = IsTransactionOrTransactionBlock();
1409 
1410  PG_TRY();
1411  {
1412  ReorderBufferChange *change;
1413  ReorderBufferChange *specinsert = NULL;
1414 
1415  if (using_subtxn)
1416  BeginInternalSubTransaction("replay");
1417  else
1419 
1420  rb->begin(rb, txn);
1421 
1422  iterstate = ReorderBufferIterTXNInit(rb, txn);
1423  while ((change = ReorderBufferIterTXNNext(rb, iterstate)) != NULL)
1424  {
1425  Relation relation = NULL;
1426  Oid reloid;
1427 
1428  switch (change->action)
1429  {
1431 
1432  /*
1433  * Confirmation for speculative insertion arrived. Simply
1434  * use as a normal record. It'll be cleaned up at the end
1435  * of INSERT processing.
1436  */
1437  Assert(specinsert->data.tp.oldtuple == NULL);
1438  change = specinsert;
1440 
1441  /* intentionally fall through */
1445  Assert(snapshot_now);
1446 
1447  reloid = RelidByRelfilenode(change->data.tp.relnode.spcNode,
1448  change->data.tp.relnode.relNode);
1449 
1450  /*
1451  * Catalog tuple without data, emitted while catalog was
1452  * in the process of being rewritten.
1453  */
1454  if (reloid == InvalidOid &&
1455  change->data.tp.newtuple == NULL &&
1456  change->data.tp.oldtuple == NULL)
1457  goto change_done;
1458  else if (reloid == InvalidOid)
1459  elog(ERROR, "could not map filenode \"%s\" to relation OID",
1460  relpathperm(change->data.tp.relnode,
1461  MAIN_FORKNUM));
1462 
1463  relation = RelationIdGetRelation(reloid);
1464 
1465  if (relation == NULL)
1466  elog(ERROR, "could not open relation with OID %u (for filenode \"%s\")",
1467  reloid,
1468  relpathperm(change->data.tp.relnode,
1469  MAIN_FORKNUM));
1470 
1471  if (!RelationIsLogicallyLogged(relation))
1472  goto change_done;
1473 
1474  /*
1475  * For now ignore sequence changes entirely. Most of the
1476  * time they don't log changes using records we
1477  * understand, so it doesn't make sense to handle the few
1478  * cases we do.
1479  */
1480  if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
1481  goto change_done;
1482 
1483  /* user-triggered change */
1484  if (!IsToastRelation(relation))
1485  {
1486  ReorderBufferToastReplace(rb, txn, relation, change);
1487  rb->apply_change(rb, txn, relation, change);
1488 
1489  /*
1490  * Only clear reassembled toast chunks if we're sure
1491  * they're not required anymore. The creator of the
1492  * tuple tells us.
1493  */
1494  if (change->data.tp.clear_toast_afterwards)
1495  ReorderBufferToastReset(rb, txn);
1496  }
1497  /* we're not interested in toast deletions */
1498  else if (change->action == REORDER_BUFFER_CHANGE_INSERT)
1499  {
1500  /*
1501  * Need to reassemble the full toasted Datum in
1502  * memory, to ensure the chunks don't get reused till
1503  * we're done remove it from the list of this
1504  * transaction's changes. Otherwise it will get
1505  * freed/reused while restoring spooled data from
1506  * disk.
1507  */
1508  dlist_delete(&change->node);
1509  ReorderBufferToastAppendChunk(rb, txn, relation,
1510  change);
1511  }
1512 
1513  change_done:
1514 
1515  /*
1516  * Either speculative insertion was confirmed, or it was
1517  * unsuccessful and the record isn't needed anymore.
1518  */
1519  if (specinsert != NULL)
1520  {
1521  ReorderBufferReturnChange(rb, specinsert);
1522  specinsert = NULL;
1523  }
1524 
1525  if (relation != NULL)
1526  {
1527  RelationClose(relation);
1528  relation = NULL;
1529  }
1530  break;
1531 
1533 
1534  /*
1535  * Speculative insertions are dealt with by delaying the
1536  * processing of the insert until the confirmation record
1537  * arrives. For that we simply unlink the record from the
1538  * chain, so it does not get freed/reused while restoring
1539  * spooled data from disk.
1540  *
1541  * This is safe in the face of concurrent catalog changes
1542  * because the relevant relation can't be changed between
1543  * speculative insertion and confirmation due to
1544  * CheckTableNotInUse() and locking.
1545  */
1546 
1547  /* clear out a pending (and thus failed) speculation */
1548  if (specinsert != NULL)
1549  {
1550  ReorderBufferReturnChange(rb, specinsert);
1551  specinsert = NULL;
1552  }
1553 
1554  /* and memorize the pending insertion */
1555  dlist_delete(&change->node);
1556  specinsert = change;
1557  break;
1558 
1560  rb->message(rb, txn, change->lsn, true,
1561  change->data.msg.prefix,
1562  change->data.msg.message_size,
1563  change->data.msg.message);
1564  break;
1565 
1567  /* get rid of the old */
1568  TeardownHistoricSnapshot(false);
1569 
1570  if (snapshot_now->copied)
1571  {
1572  ReorderBufferFreeSnap(rb, snapshot_now);
1573  snapshot_now =
1574  ReorderBufferCopySnap(rb, change->data.snapshot,
1575  txn, command_id);
1576  }
1577 
1578  /*
1579  * Restored from disk, need to be careful not to double
1580  * free. We could introduce refcounting for that, but for
1581  * now this seems infrequent enough not to care.
1582  */
1583  else if (change->data.snapshot->copied)
1584  {
1585  snapshot_now =
1586  ReorderBufferCopySnap(rb, change->data.snapshot,
1587  txn, command_id);
1588  }
1589  else
1590  {
1591  snapshot_now = change->data.snapshot;
1592  }
1593 
1594 
1595  /* and continue with the new one */
1596  SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1597  break;
1598 
1600  Assert(change->data.command_id != InvalidCommandId);
1601 
1602  if (command_id < change->data.command_id)
1603  {
1604  command_id = change->data.command_id;
1605 
1606  if (!snapshot_now->copied)
1607  {
1608  /* we don't use the global one anymore */
1609  snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
1610  txn, command_id);
1611  }
1612 
1613  snapshot_now->curcid = command_id;
1614 
1615  TeardownHistoricSnapshot(false);
1616  SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1617 
1618  /*
1619  * Every time the CommandId is incremented, we could
1620  * see new catalog contents, so execute all
1621  * invalidations.
1622  */
1624  }
1625 
1626  break;
1627 
1629  elog(ERROR, "tuplecid value in changequeue");
1630  break;
1631  }
1632  }
1633 
1634  /*
1635  * There's a speculative insertion remaining, just clean in up, it
1636  * can't have been successful, otherwise we'd gotten a confirmation
1637  * record.
1638  */
1639  if (specinsert)
1640  {
1641  ReorderBufferReturnChange(rb, specinsert);
1642  specinsert = NULL;
1643  }
1644 
1645  /* clean up the iterator */
1646  ReorderBufferIterTXNFinish(rb, iterstate);
1647  iterstate = NULL;
1648 
1649  /* call commit callback */
1650  rb->commit(rb, txn, commit_lsn);
1651 
1652  /* this is just a sanity check against bad output plugin behaviour */
1654  elog(ERROR, "output plugin used XID %u",
1656 
1657  /* cleanup */
1658  TeardownHistoricSnapshot(false);
1659 
1660  /*
1661  * Aborting the current (sub-)transaction as a whole has the right
1662  * semantics. We want all locks acquired in here to be released, not
1663  * reassigned to the parent and we do not want any database access
1664  * have persistent effects.
1665  */
1667 
1668  /* make sure there's no cache pollution */
1670 
1671  if (using_subtxn)
1673 
1674  if (snapshot_now->copied)
1675  ReorderBufferFreeSnap(rb, snapshot_now);
1676 
1677  /* remove potential on-disk data, and deallocate */
1678  ReorderBufferCleanupTXN(rb, txn);
1679  }
1680  PG_CATCH();
1681  {
1682  /* TODO: Encapsulate cleanup from the PG_TRY and PG_CATCH blocks */
1683  if (iterstate)
1684  ReorderBufferIterTXNFinish(rb, iterstate);
1685 
1687 
1688  /*
1689  * Force cache invalidation to happen outside of a valid transaction
1690  * to prevent catalog access as we just caught an error.
1691  */
1693 
1694  /* make sure there's no cache pollution */
1696 
1697  if (using_subtxn)
1699 
1700  if (snapshot_now->copied)
1701  ReorderBufferFreeSnap(rb, snapshot_now);
1702 
1703  /* remove potential on-disk data, and deallocate */
1704  ReorderBufferCleanupTXN(rb, txn);
1705 
1706  PG_RE_THROW();
1707  }
1708  PG_END_TRY();
1709 }
1710 
1711 /*
1712  * Abort a transaction that possibly has previous changes. Needs to be first
1713  * called for subtransactions and then for the toplevel xid.
1714  *
1715  * NB: Transactions handled here have to have actively aborted (i.e. have
1716  * produced an abort record). Implicitly aborted transactions are handled via
1717  * ReorderBufferAbortOld(); transactions we're just not interesteded in, but
1718  * which have committed are handled in ReorderBufferForget().
1719  *
1720  * This function purges this transaction and its contents from memory and
1721  * disk.
1722  */
1723 void
1725 {
1726  ReorderBufferTXN *txn;
1727 
1728  txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1729  false);
1730 
1731  /* unknown, nothing to remove */
1732  if (txn == NULL)
1733  return;
1734 
1735  /* cosmetic... */
1736  txn->final_lsn = lsn;
1737 
1738  /* remove potential on-disk data, and deallocate */
1739  ReorderBufferCleanupTXN(rb, txn);
1740 }
1741 
1742 /*
1743  * Abort all transactions that aren't actually running anymore because the
1744  * server restarted.
1745  *
1746  * NB: These really have to be transactions that have aborted due to a server
1747  * crash/immediate restart, as we don't deal with invalidations here.
1748  */
1749 void
1751 {
1752  dlist_mutable_iter it;
1753 
1754  /*
1755  * Iterate through all (potential) toplevel TXNs and abort all that are
1756  * older than what possibly can be running. Once we've found the first
1757  * that is alive we stop, there might be some that acquired an xid earlier
1758  * but started writing later, but it's unlikely and they will cleaned up
1759  * in a later call to ReorderBufferAbortOld().
1760  */
1762  {
1763  ReorderBufferTXN *txn;
1764 
1765  txn = dlist_container(ReorderBufferTXN, node, it.cur);
1766 
1767  if (TransactionIdPrecedes(txn->xid, oldestRunningXid))
1768  {
1769  elog(DEBUG1, "aborting old transaction %u", txn->xid);
1770 
1771  /* remove potential on-disk data, and deallocate this tx */
1772  ReorderBufferCleanupTXN(rb, txn);
1773  }
1774  else
1775  return;
1776  }
1777 }
1778 
1779 /*
1780  * Forget the contents of a transaction if we aren't interested in it's
1781  * contents. Needs to be first called for subtransactions and then for the
1782  * toplevel xid.
1783  *
1784  * This is significantly different to ReorderBufferAbort() because
1785  * transactions that have committed need to be treated differenly from aborted
1786  * ones since they may have modified the catalog.
1787  *
1788  * Note that this is only allowed to be called in the moment a transaction
1789  * commit has just been read, not earlier; otherwise later records referring
1790  * to this xid might re-create the transaction incompletely.
1791  */
1792 void
1794 {
1795  ReorderBufferTXN *txn;
1796 
1797  txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1798  false);
1799 
1800  /* unknown, nothing to forget */
1801  if (txn == NULL)
1802  return;
1803 
1804  /* cosmetic... */
1805  txn->final_lsn = lsn;
1806 
1807  /*
1808  * Process cache invalidation messages if there are any. Even if we're not
1809  * interested in the transaction's contents, it could have manipulated the
1810  * catalog and we need to update the caches according to that.
1811  */
1812  if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
1814  txn->invalidations);
1815  else
1816  Assert(txn->ninvalidations == 0);
1817 
1818  /* remove potential on-disk data, and deallocate */
1819  ReorderBufferCleanupTXN(rb, txn);
1820 }
1821 
1822 /*
1823  * Execute invalidations happening outside the context of a decoded
1824  * transaction. That currently happens either for xid-less commits
1825  * (c.f. RecordTransactionCommit()) or for invalidations in uninteresting
1826  * transactions (via ReorderBufferForget()).
1827  */
1828 void
1830  SharedInvalidationMessage *invalidations)
1831 {
1832  bool use_subtxn = IsTransactionOrTransactionBlock();
1833  int i;
1834 
1835  if (use_subtxn)
1836  BeginInternalSubTransaction("replay");
1837 
1838  /*
1839  * Force invalidations to happen outside of a valid transaction - that way
1840  * entries will just be marked as invalid without accessing the catalog.
1841  * That's advantageous because we don't need to setup the full state
1842  * necessary for catalog access.
1843  */
1844  if (use_subtxn)
1846 
1847  for (i = 0; i < ninvalidations; i++)
1848  LocalExecuteInvalidationMessage(&invalidations[i]);
1849 
1850  if (use_subtxn)
1852 }
1853 
1854 /*
1855  * Tell reorderbuffer about an xid seen in the WAL stream. Has to be called at
1856  * least once for every xid in XLogRecord->xl_xid (other places in records
1857  * may, but do not have to be passed through here).
1858  *
1859  * Reorderbuffer keeps some datastructures about transactions in LSN order,
1860  * for efficiency. To do that it has to know about when transactions are seen
1861  * first in the WAL. As many types of records are not actually interesting for
1862  * logical decoding, they do not necessarily pass though here.
1863  */
1864 void
1866 {
1867  /* many records won't have an xid assigned, centralize check here */
1868  if (xid != InvalidTransactionId)
1869  ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1870 }
1871 
1872 /*
1873  * Add a new snapshot to this transaction that may only used after lsn 'lsn'
1874  * because the previous snapshot doesn't describe the catalog correctly for
1875  * following rows.
1876  */
1877 void
1879  XLogRecPtr lsn, Snapshot snap)
1880 {
1882 
1883  change->data.snapshot = snap;
1885 
1886  ReorderBufferQueueChange(rb, xid, lsn, change);
1887 }
1888 
1889 /*
1890  * Setup the base snapshot of a transaction. The base snapshot is the snapshot
1891  * that is used to decode all changes until either this transaction modifies
1892  * the catalog or another catalog modifying transaction commits.
1893  *
1894  * Needs to be called before any changes are added with
1895  * ReorderBufferQueueChange().
1896  */
1897 void
1899  XLogRecPtr lsn, Snapshot snap)
1900 {
1901  ReorderBufferTXN *txn;
1902  bool is_new;
1903 
1904  txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true);
1905  Assert(txn->base_snapshot == NULL);
1906  Assert(snap != NULL);
1907 
1908  txn->base_snapshot = snap;
1909  txn->base_snapshot_lsn = lsn;
1910 }
1911 
1912 /*
1913  * Access the catalog with this CommandId at this point in the changestream.
1914  *
1915  * May only be called for command ids > 1
1916  */
1917 void
1919  XLogRecPtr lsn, CommandId cid)
1920 {
1922 
1923  change->data.command_id = cid;
1925 
1926  ReorderBufferQueueChange(rb, xid, lsn, change);
1927 }
1928 
1929 
1930 /*
1931  * Add new (relfilenode, tid) -> (cmin, cmax) mappings.
1932  */
1933 void
1935  XLogRecPtr lsn, RelFileNode node,
1936  ItemPointerData tid, CommandId cmin,
1937  CommandId cmax, CommandId combocid)
1938 {
1940  ReorderBufferTXN *txn;
1941 
1942  txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1943 
1944  change->data.tuplecid.node = node;
1945  change->data.tuplecid.tid = tid;
1946  change->data.tuplecid.cmin = cmin;
1947  change->data.tuplecid.cmax = cmax;
1948  change->data.tuplecid.combocid = combocid;
1949  change->lsn = lsn;
1951 
1952  dlist_push_tail(&txn->tuplecids, &change->node);
1953  txn->ntuplecids++;
1954 }
1955 
1956 /*
1957  * Setup the invalidation of the toplevel transaction.
1958  *
1959  * This needs to be done before ReorderBufferCommit is called!
1960  */
1961 void
1963  XLogRecPtr lsn, Size nmsgs,
1965 {
1966  ReorderBufferTXN *txn;
1967 
1968  txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1969 
1970  if (txn->ninvalidations != 0)
1971  elog(ERROR, "only ever add one set of invalidations");
1972 
1973  Assert(nmsgs > 0);
1974 
1975  txn->ninvalidations = nmsgs;
1978  sizeof(SharedInvalidationMessage) * nmsgs);
1979  memcpy(txn->invalidations, msgs,
1980  sizeof(SharedInvalidationMessage) * nmsgs);
1981 }
1982 
1983 /*
1984  * Apply all invalidations we know. Possibly we only need parts at this point
1985  * in the changestream but we don't know which those are.
1986  */
1987 static void
1989 {
1990  int i;
1991 
1992  for (i = 0; i < txn->ninvalidations; i++)
1994 }
1995 
1996 /*
1997  * Mark a transaction as containing catalog changes
1998  */
1999 void
2001  XLogRecPtr lsn)
2002 {
2003  ReorderBufferTXN *txn;
2004 
2005  txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
2006 
2007  txn->has_catalog_changes = true;
2008 }
2009 
2010 /*
2011  * Query whether a transaction is already *known* to contain catalog
2012  * changes. This can be wrong until directly before the commit!
2013  */
2014 bool
2016 {
2017  ReorderBufferTXN *txn;
2018 
2019  txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
2020  false);
2021  if (txn == NULL)
2022  return false;
2023 
2024  return txn->has_catalog_changes;
2025 }
2026 
2027 /*
2028  * Have we already added the first snapshot?
2029  */
2030 bool
2032 {
2033  ReorderBufferTXN *txn;
2034 
2035  txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
2036  false);
2037 
2038  /* transaction isn't known yet, ergo no snapshot */
2039  if (txn == NULL)
2040  return false;
2041 
2042  /*
2043  * TODO: It would be a nice improvement if we would check the toplevel
2044  * transaction in subtransactions, but we'd need to keep track of a bit
2045  * more state.
2046  */
2047  return txn->base_snapshot != NULL;
2048 }
2049 
2050 
2051 /*
2052  * ---------------------------------------
2053  * Disk serialization support
2054  * ---------------------------------------
2055  */
2056 
2057 /*
2058  * Ensure the IO buffer is >= sz.
2059  */
2060 static void
2062 {
2063  if (!rb->outbufsize)
2064  {
2065  rb->outbuf = MemoryContextAlloc(rb->context, sz);
2066  rb->outbufsize = sz;
2067  }
2068  else if (rb->outbufsize < sz)
2069  {
2070  rb->outbuf = repalloc(rb->outbuf, sz);
2071  rb->outbufsize = sz;
2072  }
2073 }
2074 
2075 /*
2076  * Check whether the transaction tx should spill its data to disk.
2077  */
2078 static void
2080 {
2081  /*
2082  * TODO: improve accounting so we cheaply can take subtransactions into
2083  * account here.
2084  */
2085  if (txn->nentries_mem >= max_changes_in_memory)
2086  {
2087  ReorderBufferSerializeTXN(rb, txn);
2088  Assert(txn->nentries_mem == 0);
2089  }
2090 }
2091 
2092 /*
2093  * Spill data of a large transaction (and its subtransactions) to disk.
2094  */
2095 static void
2097 {
2098  dlist_iter subtxn_i;
2099  dlist_mutable_iter change_i;
2100  int fd = -1;
2101  XLogSegNo curOpenSegNo = 0;
2102  Size spilled = 0;
2103  char path[MAXPGPATH];
2104 
2105  elog(DEBUG2, "spill %u changes in XID %u to disk",
2106  (uint32) txn->nentries_mem, txn->xid);
2107 
2108  /* do the same to all child TXs */
2109  dlist_foreach(subtxn_i, &txn->subtxns)
2110  {
2111  ReorderBufferTXN *subtxn;
2112 
2113  subtxn = dlist_container(ReorderBufferTXN, node, subtxn_i.cur);
2114  ReorderBufferSerializeTXN(rb, subtxn);
2115  }
2116 
2117  /* serialize changestream */
2118  dlist_foreach_modify(change_i, &txn->changes)
2119  {
2120  ReorderBufferChange *change;
2121 
2122  change = dlist_container(ReorderBufferChange, node, change_i.cur);
2123 
2124  /*
2125  * store in segment in which it belongs by start lsn, don't split over
2126  * multiple segments tho
2127  */
2128  if (fd == -1 || !XLByteInSeg(change->lsn, curOpenSegNo))
2129  {
2130  XLogRecPtr recptr;
2131 
2132  if (fd != -1)
2133  CloseTransientFile(fd);
2134 
2135  XLByteToSeg(change->lsn, curOpenSegNo);
2136  XLogSegNoOffsetToRecPtr(curOpenSegNo, 0, recptr);
2137 
2138  /*
2139  * No need to care about TLIs here, only used during a single run,
2140  * so each LSN only maps to a specific WAL record.
2141  */
2142  sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2144  (uint32) (recptr >> 32), (uint32) recptr);
2145 
2146  /* open segment, create it if necessary */
2147  fd = OpenTransientFile(path,
2148  O_CREAT | O_WRONLY | O_APPEND | PG_BINARY,
2149  S_IRUSR | S_IWUSR);
2150 
2151  if (fd < 0)
2152  ereport(ERROR,
2154  errmsg("could not open file \"%s\": %m",
2155  path)));
2156  }
2157 
2158  ReorderBufferSerializeChange(rb, txn, fd, change);
2159  dlist_delete(&change->node);
2160  ReorderBufferReturnChange(rb, change);
2161 
2162  spilled++;
2163  }
2164 
2165  Assert(spilled == txn->nentries_mem);
2166  Assert(dlist_is_empty(&txn->changes));
2167  txn->nentries_mem = 0;
2168 
2169  if (fd != -1)
2170  CloseTransientFile(fd);
2171 }
2172 
2173 /*
2174  * Serialize individual change to disk.
2175  */
2176 static void
2178  int fd, ReorderBufferChange *change)
2179 {
2180  ReorderBufferDiskChange *ondisk;
2181  Size sz = sizeof(ReorderBufferDiskChange);
2182 
2184 
2185  ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2186  memcpy(&ondisk->change, change, sizeof(ReorderBufferChange));
2187 
2188  switch (change->action)
2189  {
2190  /* fall through these, they're all similar enough */
2195  {
2196  char *data;
2197  ReorderBufferTupleBuf *oldtup,
2198  *newtup;
2199  Size oldlen = 0;
2200  Size newlen = 0;
2201 
2202  oldtup = change->data.tp.oldtuple;
2203  newtup = change->data.tp.newtuple;
2204 
2205  if (oldtup)
2206  {
2207  sz += sizeof(HeapTupleData);
2208  oldlen = oldtup->tuple.t_len;
2209  sz += oldlen;
2210  }
2211 
2212  if (newtup)
2213  {
2214  sz += sizeof(HeapTupleData);
2215  newlen = newtup->tuple.t_len;
2216  sz += newlen;
2217  }
2218 
2219  /* make sure we have enough space */
2221 
2222  data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2223  /* might have been reallocated above */
2224  ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2225 
2226  if (oldlen)
2227  {
2228  memcpy(data, &oldtup->tuple, sizeof(HeapTupleData));
2229  data += sizeof(HeapTupleData);
2230 
2231  memcpy(data, oldtup->tuple.t_data, oldlen);
2232  data += oldlen;
2233  }
2234 
2235  if (newlen)
2236  {
2237  memcpy(data, &newtup->tuple, sizeof(HeapTupleData));
2238  data += sizeof(HeapTupleData);
2239 
2240  memcpy(data, newtup->tuple.t_data, newlen);
2241  data += newlen;
2242  }
2243  break;
2244  }
2246  {
2247  char *data;
2248  Size prefix_size = strlen(change->data.msg.prefix) + 1;
2249 
2250  sz += prefix_size + change->data.msg.message_size +
2251  sizeof(Size) + sizeof(Size);
2253 
2254  data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2255 
2256  /* write the prefix including the size */
2257  memcpy(data, &prefix_size, sizeof(Size));
2258  data += sizeof(Size);
2259  memcpy(data, change->data.msg.prefix,
2260  prefix_size);
2261  data += prefix_size;
2262 
2263  /* write the message including the size */
2264  memcpy(data, &change->data.msg.message_size, sizeof(Size));
2265  data += sizeof(Size);
2266  memcpy(data, change->data.msg.message,
2267  change->data.msg.message_size);
2268  data += change->data.msg.message_size;
2269 
2270  break;
2271  }
2273  {
2274  Snapshot snap;
2275  char *data;
2276 
2277  snap = change->data.snapshot;
2278 
2279  sz += sizeof(SnapshotData) +
2280  sizeof(TransactionId) * snap->xcnt +
2281  sizeof(TransactionId) * snap->subxcnt
2282  ;
2283 
2284  /* make sure we have enough space */
2286  data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2287  /* might have been reallocated above */
2288  ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2289 
2290  memcpy(data, snap, sizeof(SnapshotData));
2291  data += sizeof(SnapshotData);
2292 
2293  if (snap->xcnt)
2294  {
2295  memcpy(data, snap->xip,
2296  sizeof(TransactionId) * snap->xcnt);
2297  data += sizeof(TransactionId) * snap->xcnt;
2298  }
2299 
2300  if (snap->subxcnt)
2301  {
2302  memcpy(data, snap->subxip,
2303  sizeof(TransactionId) * snap->subxcnt);
2304  data += sizeof(TransactionId) * snap->subxcnt;
2305  }
2306  break;
2307  }
2311  /* ReorderBufferChange contains everything important */
2312  break;
2313  }
2314 
2315  ondisk->size = sz;
2316 
2317  if (write(fd, rb->outbuf, ondisk->size) != ondisk->size)
2318  {
2319  CloseTransientFile(fd);
2320  ereport(ERROR,
2322  errmsg("could not write to data file for XID %u: %m",
2323  txn->xid)));
2324  }
2325 
2326  Assert(ondisk->change.action == change->action);
2327 }
2328 
2329 /*
2330  * Restore a number of changes spilled to disk back into memory.
2331  */
2332 static Size
2334  int *fd, XLogSegNo *segno)
2335 {
2336  Size restored = 0;
2337  XLogSegNo last_segno;
2338  dlist_mutable_iter cleanup_iter;
2339 
2342 
2343  /* free current entries, so we have memory for more */
2344  dlist_foreach_modify(cleanup_iter, &txn->changes)
2345  {
2347  dlist_container(ReorderBufferChange, node, cleanup_iter.cur);
2348 
2349  dlist_delete(&cleanup->node);
2350  ReorderBufferReturnChange(rb, cleanup);
2351  }
2352  txn->nentries_mem = 0;
2353  Assert(dlist_is_empty(&txn->changes));
2354 
2355  XLByteToSeg(txn->final_lsn, last_segno);
2356 
2357  while (restored < max_changes_in_memory && *segno <= last_segno)
2358  {
2359  int readBytes;
2360  ReorderBufferDiskChange *ondisk;
2361 
2362  if (*fd == -1)
2363  {
2364  XLogRecPtr recptr;
2365  char path[MAXPGPATH];
2366 
2367  /* first time in */
2368  if (*segno == 0)
2369  {
2370  XLByteToSeg(txn->first_lsn, *segno);
2371  }
2372 
2373  Assert(*segno != 0 || dlist_is_empty(&txn->changes));
2374  XLogSegNoOffsetToRecPtr(*segno, 0, recptr);
2375 
2376  /*
2377  * No need to care about TLIs here, only used during a single run,
2378  * so each LSN only maps to a specific WAL record.
2379  */
2380  sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2382  (uint32) (recptr >> 32), (uint32) recptr);
2383 
2384  *fd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
2385  if (*fd < 0 && errno == ENOENT)
2386  {
2387  *fd = -1;
2388  (*segno)++;
2389  continue;
2390  }
2391  else if (*fd < 0)
2392  ereport(ERROR,
2394  errmsg("could not open file \"%s\": %m",
2395  path)));
2396 
2397  }
2398 
2399  /*
2400  * Read the statically sized part of a change which has information
2401  * about the total size. If we couldn't read a record, we're at the
2402  * end of this file.
2403  */
2405  readBytes = read(*fd, rb->outbuf, sizeof(ReorderBufferDiskChange));
2406 
2407  /* eof */
2408  if (readBytes == 0)
2409  {
2410  CloseTransientFile(*fd);
2411  *fd = -1;
2412  (*segno)++;
2413  continue;
2414  }
2415  else if (readBytes < 0)
2416  ereport(ERROR,
2418  errmsg("could not read from reorderbuffer spill file: %m")));
2419  else if (readBytes != sizeof(ReorderBufferDiskChange))
2420  ereport(ERROR,
2422  errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2423  readBytes,
2424  (uint32) sizeof(ReorderBufferDiskChange))));
2425 
2426  ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2427 
2429  sizeof(ReorderBufferDiskChange) + ondisk->size);
2430  ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2431 
2432  readBytes = read(*fd, rb->outbuf + sizeof(ReorderBufferDiskChange),
2433  ondisk->size - sizeof(ReorderBufferDiskChange));
2434 
2435  if (readBytes < 0)
2436  ereport(ERROR,
2438  errmsg("could not read from reorderbuffer spill file: %m")));
2439  else if (readBytes != ondisk->size - sizeof(ReorderBufferDiskChange))
2440  ereport(ERROR,
2442  errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2443  readBytes,
2444  (uint32) (ondisk->size - sizeof(ReorderBufferDiskChange)))));
2445 
2446  /*
2447  * ok, read a full change from disk, now restore it into proper
2448  * in-memory format
2449  */
2450  ReorderBufferRestoreChange(rb, txn, rb->outbuf);
2451  restored++;
2452  }
2453 
2454  return restored;
2455 }
2456 
2457 /*
2458  * Convert change from its on-disk format to in-memory format and queue it onto
2459  * the TXN's ->changes list.
2460  *
2461  * Note: although "data" is declared char*, at entry it points to a
2462  * maxalign'd buffer, making it safe in most of this function to assume
2463  * that the pointed-to data is suitably aligned for direct access.
2464  */
2465 static void
2467  char *data)
2468 {
2469  ReorderBufferDiskChange *ondisk;
2470  ReorderBufferChange *change;
2471 
2472  ondisk = (ReorderBufferDiskChange *) data;
2473 
2474  change = ReorderBufferGetChange(rb);
2475 
2476  /* copy static part */
2477  memcpy(change, &ondisk->change, sizeof(ReorderBufferChange));
2478 
2479  data += sizeof(ReorderBufferDiskChange);
2480 
2481  /* restore individual stuff */
2482  switch (change->action)
2483  {
2484  /* fall through these, they're all similar enough */
2489  if (change->data.tp.oldtuple)
2490  {
2491  uint32 tuplelen = ((HeapTuple) data)->t_len;
2492 
2493  change->data.tp.oldtuple =
2495 
2496  /* restore ->tuple */
2497  memcpy(&change->data.tp.oldtuple->tuple, data,
2498  sizeof(HeapTupleData));
2499  data += sizeof(HeapTupleData);
2500 
2501  /* reset t_data pointer into the new tuplebuf */
2502  change->data.tp.oldtuple->tuple.t_data =
2503  ReorderBufferTupleBufData(change->data.tp.oldtuple);
2504 
2505  /* restore tuple data itself */
2506  memcpy(change->data.tp.oldtuple->tuple.t_data, data, tuplelen);
2507  data += tuplelen;
2508  }
2509 
2510  if (change->data.tp.newtuple)
2511  {
2512  /* here, data might not be suitably aligned! */
2513  uint32 tuplelen;
2514 
2515  memcpy(&tuplelen, data + offsetof(HeapTupleData, t_len),
2516  sizeof(uint32));
2517 
2518  change->data.tp.newtuple =
2520 
2521  /* restore ->tuple */
2522  memcpy(&change->data.tp.newtuple->tuple, data,
2523  sizeof(HeapTupleData));
2524  data += sizeof(HeapTupleData);
2525 
2526  /* reset t_data pointer into the new tuplebuf */
2527  change->data.tp.newtuple->tuple.t_data =
2528  ReorderBufferTupleBufData(change->data.tp.newtuple);
2529 
2530  /* restore tuple data itself */
2531  memcpy(change->data.tp.newtuple->tuple.t_data, data, tuplelen);
2532  data += tuplelen;
2533  }
2534 
2535  break;
2537  {
2538  Size prefix_size;
2539 
2540  /* read prefix */
2541  memcpy(&prefix_size, data, sizeof(Size));
2542  data += sizeof(Size);
2543  change->data.msg.prefix = MemoryContextAlloc(rb->context,
2544  prefix_size);
2545  memcpy(change->data.msg.prefix, data, prefix_size);
2546  Assert(change->data.msg.prefix[prefix_size - 1] == '\0');
2547  data += prefix_size;
2548 
2549  /* read the messsage */
2550  memcpy(&change->data.msg.message_size, data, sizeof(Size));
2551  data += sizeof(Size);
2552  change->data.msg.message = MemoryContextAlloc(rb->context,
2553  change->data.msg.message_size);
2554  memcpy(change->data.msg.message, data,
2555  change->data.msg.message_size);
2556  data += change->data.msg.message_size;
2557 
2558  break;
2559  }
2561  {
2562  Snapshot oldsnap;
2563  Snapshot newsnap;
2564  Size size;
2565 
2566  oldsnap = (Snapshot) data;
2567 
2568  size = sizeof(SnapshotData) +
2569  sizeof(TransactionId) * oldsnap->xcnt +
2570  sizeof(TransactionId) * (oldsnap->subxcnt + 0);
2571 
2572  change->data.snapshot = MemoryContextAllocZero(rb->context, size);
2573 
2574  newsnap = change->data.snapshot;
2575 
2576  memcpy(newsnap, data, size);
2577  newsnap->xip = (TransactionId *)
2578  (((char *) newsnap) + sizeof(SnapshotData));
2579  newsnap->subxip = newsnap->xip + newsnap->xcnt;
2580  newsnap->copied = true;
2581  break;
2582  }
2583  /* the base struct contains all the data, easy peasy */
2587  break;
2588  }
2589 
2590  dlist_push_tail(&txn->changes, &change->node);
2591  txn->nentries_mem++;
2592 }
2593 
2594 /*
2595  * Remove all on-disk stored for the passed in transaction.
2596  */
2597 static void
2599 {
2600  XLogSegNo first;
2601  XLogSegNo cur;
2602  XLogSegNo last;
2603 
2606 
2607  XLByteToSeg(txn->first_lsn, first);
2608  XLByteToSeg(txn->final_lsn, last);
2609 
2610  /* iterate over all possible filenames, and delete them */
2611  for (cur = first; cur <= last; cur++)
2612  {
2613  char path[MAXPGPATH];
2614  XLogRecPtr recptr;
2615 
2616  XLogSegNoOffsetToRecPtr(cur, 0, recptr);
2617 
2618  sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2620  (uint32) (recptr >> 32), (uint32) recptr);
2621  if (unlink(path) != 0 && errno != ENOENT)
2622  ereport(ERROR,
2624  errmsg("could not remove file \"%s\": %m", path)));
2625  }
2626 }
2627 
2628 /*
2629  * Delete all data spilled to disk after we've restarted/crashed. It will be
2630  * recreated when the respective slots are reused.
2631  */
2632 void
2634 {
2635  DIR *logical_dir;
2636  struct dirent *logical_de;
2637 
2638  DIR *spill_dir;
2639  struct dirent *spill_de;
2640 
2641  logical_dir = AllocateDir("pg_replslot");
2642  while ((logical_de = ReadDir(logical_dir, "pg_replslot")) != NULL)
2643  {
2644  struct stat statbuf;
2645  char path[MAXPGPATH];
2646 
2647  if (strcmp(logical_de->d_name, ".") == 0 ||
2648  strcmp(logical_de->d_name, "..") == 0)
2649  continue;
2650 
2651  /* if it cannot be a slot, skip the directory */
2652  if (!ReplicationSlotValidateName(logical_de->d_name, DEBUG2))
2653  continue;
2654 
2655  /*
2656  * ok, has to be a surviving logical slot, iterate and delete
2657  * everythign starting with xid-*
2658  */
2659  sprintf(path, "pg_replslot/%s", logical_de->d_name);
2660 
2661  /* we're only creating directories here, skip if it's not our's */
2662  if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
2663  continue;
2664 
2665  spill_dir = AllocateDir(path);
2666  while ((spill_de = ReadDir(spill_dir, path)) != NULL)
2667  {
2668  if (strcmp(spill_de->d_name, ".") == 0 ||
2669  strcmp(spill_de->d_name, "..") == 0)
2670  continue;
2671 
2672  /* only look at names that can be ours */
2673  if (strncmp(spill_de->d_name, "xid", 3) == 0)
2674  {
2675  sprintf(path, "pg_replslot/%s/%s", logical_de->d_name,
2676  spill_de->d_name);
2677 
2678  if (unlink(path) != 0)
2679  ereport(PANIC,
2681  errmsg("could not remove file \"%s\": %m",
2682  path)));
2683  }
2684  }
2685  FreeDir(spill_dir);
2686  }
2687  FreeDir(logical_dir);
2688 }
2689 
2690 /* ---------------------------------------
2691  * toast reassembly support
2692  * ---------------------------------------
2693  */
2694 
2695 /*
2696  * Initialize per tuple toast reconstruction support.
2697  */
2698 static void
2700 {
2701  HASHCTL hash_ctl;
2702 
2703  Assert(txn->toast_hash == NULL);
2704 
2705  memset(&hash_ctl, 0, sizeof(hash_ctl));
2706  hash_ctl.keysize = sizeof(Oid);
2707  hash_ctl.entrysize = sizeof(ReorderBufferToastEnt);
2708  hash_ctl.hcxt = rb->context;
2709  txn->toast_hash = hash_create("ReorderBufferToastHash", 5, &hash_ctl,
2711 }
2712 
2713 /*
2714  * Per toast-chunk handling for toast reconstruction
2715  *
2716  * Appends a toast chunk so we can reconstruct it when the tuple "owning" the
2717  * toasted Datum comes along.
2718  */
2719 static void
2721  Relation relation, ReorderBufferChange *change)
2722 {
2723  ReorderBufferToastEnt *ent;
2724  ReorderBufferTupleBuf *newtup;
2725  bool found;
2726  int32 chunksize;
2727  bool isnull;
2728  Pointer chunk;
2729  TupleDesc desc = RelationGetDescr(relation);
2730  Oid chunk_id;
2731  int32 chunk_seq;
2732 
2733  if (txn->toast_hash == NULL)
2734  ReorderBufferToastInitHash(rb, txn);
2735 
2736  Assert(IsToastRelation(relation));
2737 
2738  newtup = change->data.tp.newtuple;
2739  chunk_id = DatumGetObjectId(fastgetattr(&newtup->tuple, 1, desc, &isnull));
2740  Assert(!isnull);
2741  chunk_seq = DatumGetInt32(fastgetattr(&newtup->tuple, 2, desc, &isnull));
2742  Assert(!isnull);
2743 
2744  ent = (ReorderBufferToastEnt *)
2745  hash_search(txn->toast_hash,
2746  (void *) &chunk_id,
2747  HASH_ENTER,
2748  &found);
2749 
2750  if (!found)
2751  {
2752  Assert(ent->chunk_id == chunk_id);
2753  ent->num_chunks = 0;
2754  ent->last_chunk_seq = 0;
2755  ent->size = 0;
2756  ent->reconstructed = NULL;
2757  dlist_init(&ent->chunks);
2758 
2759  if (chunk_seq != 0)
2760  elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq 0",
2761  chunk_seq, chunk_id);
2762  }
2763  else if (found && chunk_seq != ent->last_chunk_seq + 1)
2764  elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq %d",
2765  chunk_seq, chunk_id, ent->last_chunk_seq + 1);
2766 
2767  chunk = DatumGetPointer(fastgetattr(&newtup->tuple, 3, desc, &isnull));
2768  Assert(!isnull);
2769 
2770  /* calculate size so we can allocate the right size at once later */
2771  if (!VARATT_IS_EXTENDED(chunk))
2772  chunksize = VARSIZE(chunk) - VARHDRSZ;
2773  else if (VARATT_IS_SHORT(chunk))
2774  /* could happen due to heap_form_tuple doing its thing */
2775  chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT;
2776  else
2777  elog(ERROR, "unexpected type of toast chunk");
2778 
2779  ent->size += chunksize;
2780  ent->last_chunk_seq = chunk_seq;
2781  ent->num_chunks++;
2782  dlist_push_tail(&ent->chunks, &change->node);
2783 }
2784 
2785 /*
2786  * Rejigger change->newtuple to point to in-memory toast tuples instead to
2787  * on-disk toast tuples that may not longer exist (think DROP TABLE or VACUUM).
2788  *
2789  * We cannot replace unchanged toast tuples though, so those will still point
2790  * to on-disk toast data.
2791  */
2792 static void
2794  Relation relation, ReorderBufferChange *change)
2795 {
2796  TupleDesc desc;
2797  int natt;
2798  Datum *attrs;
2799  bool *isnull;
2800  bool *free;
2801  HeapTuple tmphtup;
2802  Relation toast_rel;
2803  TupleDesc toast_desc;
2804  MemoryContext oldcontext;
2805  ReorderBufferTupleBuf *newtup;
2806 
2807  /* no toast tuples changed */
2808  if (txn->toast_hash == NULL)
2809  return;
2810 
2811  oldcontext = MemoryContextSwitchTo(rb->context);
2812 
2813  /* we should only have toast tuples in an INSERT or UPDATE */
2814  Assert(change->data.tp.newtuple);
2815 
2816  desc = RelationGetDescr(relation);
2817 
2818  toast_rel = RelationIdGetRelation(relation->rd_rel->reltoastrelid);
2819  toast_desc = RelationGetDescr(toast_rel);
2820 
2821  /* should we allocate from stack instead? */
2822  attrs = palloc0(sizeof(Datum) * desc->natts);
2823  isnull = palloc0(sizeof(bool) * desc->natts);
2824  free = palloc0(sizeof(bool) * desc->natts);
2825 
2826  newtup = change->data.tp.newtuple;
2827 
2828  heap_deform_tuple(&newtup->tuple, desc, attrs, isnull);
2829 
2830  for (natt = 0; natt < desc->natts; natt++)
2831  {
2832  Form_pg_attribute attr = desc->attrs[natt];
2833  ReorderBufferToastEnt *ent;
2834  struct varlena *varlena;
2835 
2836  /* va_rawsize is the size of the original datum -- including header */
2837  struct varatt_external toast_pointer;
2838  struct varatt_indirect redirect_pointer;
2839  struct varlena *new_datum = NULL;
2840  struct varlena *reconstructed;
2841  dlist_iter it;
2842  Size data_done = 0;
2843 
2844  /* system columns aren't toasted */
2845  if (attr->attnum < 0)
2846  continue;
2847 
2848  if (attr->attisdropped)
2849  continue;
2850 
2851  /* not a varlena datatype */
2852  if (attr->attlen != -1)
2853  continue;
2854 
2855  /* no data */
2856  if (isnull[natt])
2857  continue;
2858 
2859  /* ok, we know we have a toast datum */
2860  varlena = (struct varlena *) DatumGetPointer(attrs[natt]);
2861 
2862  /* no need to do anything if the tuple isn't external */
2863  if (!VARATT_IS_EXTERNAL(varlena))
2864  continue;
2865 
2866  VARATT_EXTERNAL_GET_POINTER(toast_pointer, varlena);
2867 
2868  /*
2869  * Check whether the toast tuple changed, replace if so.
2870  */
2871  ent = (ReorderBufferToastEnt *)
2872  hash_search(txn->toast_hash,
2873  (void *) &toast_pointer.va_valueid,
2874  HASH_FIND,
2875  NULL);
2876  if (ent == NULL)
2877  continue;
2878 
2879  new_datum =
2880  (struct varlena *) palloc0(INDIRECT_POINTER_SIZE);
2881 
2882  free[natt] = true;
2883 
2884  reconstructed = palloc0(toast_pointer.va_rawsize);
2885 
2886  ent->reconstructed = reconstructed;
2887 
2888  /* stitch toast tuple back together from its parts */
2889  dlist_foreach(it, &ent->chunks)
2890  {
2891  bool isnull;
2892  ReorderBufferChange *cchange;
2893  ReorderBufferTupleBuf *ctup;
2894  Pointer chunk;
2895 
2896  cchange = dlist_container(ReorderBufferChange, node, it.cur);
2897  ctup = cchange->data.tp.newtuple;
2898  chunk = DatumGetPointer(
2899  fastgetattr(&ctup->tuple, 3, toast_desc, &isnull));
2900 
2901  Assert(!isnull);
2902  Assert(!VARATT_IS_EXTERNAL(chunk));
2903  Assert(!VARATT_IS_SHORT(chunk));
2904 
2905  memcpy(VARDATA(reconstructed) + data_done,
2906  VARDATA(chunk),
2907  VARSIZE(chunk) - VARHDRSZ);
2908  data_done += VARSIZE(chunk) - VARHDRSZ;
2909  }
2910  Assert(data_done == toast_pointer.va_extsize);
2911 
2912  /* make sure its marked as compressed or not */
2913  if (VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer))
2914  SET_VARSIZE_COMPRESSED(reconstructed, data_done + VARHDRSZ);
2915  else
2916  SET_VARSIZE(reconstructed, data_done + VARHDRSZ);
2917 
2918  memset(&redirect_pointer, 0, sizeof(redirect_pointer));
2919  redirect_pointer.pointer = reconstructed;
2920 
2922  memcpy(VARDATA_EXTERNAL(new_datum), &redirect_pointer,
2923  sizeof(redirect_pointer));
2924 
2925  attrs[natt] = PointerGetDatum(new_datum);
2926  }
2927 
2928  /*
2929  * Build tuple in separate memory & copy tuple back into the tuplebuf
2930  * passed to the output plugin. We can't directly heap_fill_tuple() into
2931  * the tuplebuf because attrs[] will point back into the current content.
2932  */
2933  tmphtup = heap_form_tuple(desc, attrs, isnull);
2934  Assert(newtup->tuple.t_len <= MaxHeapTupleSize);
2935  Assert(ReorderBufferTupleBufData(newtup) == newtup->tuple.t_data);
2936 
2937  memcpy(newtup->tuple.t_data, tmphtup->t_data, tmphtup->t_len);
2938  newtup->tuple.t_len = tmphtup->t_len;
2939 
2940  /*
2941  * free resources we won't further need, more persistent stuff will be
2942  * free'd in ReorderBufferToastReset().
2943  */
2944  RelationClose(toast_rel);
2945  pfree(tmphtup);
2946  for (natt = 0; natt < desc->natts; natt++)
2947  {
2948  if (free[natt])
2949  pfree(DatumGetPointer(attrs[natt]));
2950  }
2951  pfree(attrs);
2952  pfree(free);
2953  pfree(isnull);
2954 
2955  MemoryContextSwitchTo(oldcontext);
2956 }
2957 
2958 /*
2959  * Free all resources allocated for toast reconstruction.
2960  */
2961 static void
2963 {
2964  HASH_SEQ_STATUS hstat;
2965  ReorderBufferToastEnt *ent;
2966 
2967  if (txn->toast_hash == NULL)
2968  return;
2969 
2970  /* sequentially walk over the hash and free everything */
2971  hash_seq_init(&hstat, txn->toast_hash);
2972  while ((ent = (ReorderBufferToastEnt *) hash_seq_search(&hstat)) != NULL)
2973  {
2974  dlist_mutable_iter it;
2975 
2976  if (ent->reconstructed != NULL)
2977  pfree(ent->reconstructed);
2978 
2979  dlist_foreach_modify(it, &ent->chunks)
2980  {
2981  ReorderBufferChange *change =
2983 
2984  dlist_delete(&change->node);
2985  ReorderBufferReturnChange(rb, change);
2986  }
2987  }
2988 
2989  hash_destroy(txn->toast_hash);
2990  txn->toast_hash = NULL;
2991 }
2992 
2993 
2994 /* ---------------------------------------
2995  * Visibility support for logical decoding
2996  *
2997  *
2998  * Lookup actual cmin/cmax values when using decoding snapshot. We can't
2999  * always rely on stored cmin/cmax values because of two scenarios:
3000  *
3001  * * A tuple got changed multiple times during a single transaction and thus
3002  * has got a combocid. Combocid's are only valid for the duration of a
3003  * single transaction.
3004  * * A tuple with a cmin but no cmax (and thus no combocid) got
3005  * deleted/updated in another transaction than the one which created it
3006  * which we are looking at right now. As only one of cmin, cmax or combocid
3007  * is actually stored in the heap we don't have access to the value we
3008  * need anymore.
3009  *
3010  * To resolve those problems we have a per-transaction hash of (cmin,
3011  * cmax) tuples keyed by (relfilenode, ctid) which contains the actual
3012  * (cmin, cmax) values. That also takes care of combocids by simply
3013  * not caring about them at all. As we have the real cmin/cmax values
3014  * combocids aren't interesting.
3015  *
3016  * As we only care about catalog tuples here the overhead of this
3017  * hashtable should be acceptable.
3018  *
3019  * Heap rewrites complicate this a bit, check rewriteheap.c for
3020  * details.
3021  * -------------------------------------------------------------------------
3022  */
3023 
3024 /* struct for qsort()ing mapping files by lsn somewhat efficiently */
3025 typedef struct RewriteMappingFile
3026 {
3030 
3031 #if NOT_USED
3032 static void
3033 DisplayMapping(HTAB *tuplecid_data)
3034 {
3035  HASH_SEQ_STATUS hstat;
3037 
3038  hash_seq_init(&hstat, tuplecid_data);
3039  while ((ent = (ReorderBufferTupleCidEnt *) hash_seq_search(&hstat)) != NULL)
3040  {
3041  elog(DEBUG3, "mapping: node: %u/%u/%u tid: %u/%u cmin: %u, cmax: %u",
3042  ent->key.relnode.dbNode,
3043  ent->key.relnode.spcNode,
3044  ent->key.relnode.relNode,
3046  ent->key.tid.ip_posid,
3047  ent->cmin,
3048  ent->cmax
3049  );
3050  }
3051 }
3052 #endif
3053 
3054 /*
3055  * Apply a single mapping file to tuplecid_data.
3056  *
3057  * The mapping file has to have been verified to be a) committed b) for our
3058  * transaction c) applied in LSN order.
3059  */
3060 static void
3061 ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname)
3062 {
3063  char path[MAXPGPATH];
3064  int fd;
3065  int readBytes;
3067 
3068  sprintf(path, "pg_logical/mappings/%s", fname);
3069  fd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
3070  if (fd < 0)
3071  ereport(ERROR,
3072  (errmsg("could not open file \"%s\": %m", path)));
3073 
3074  while (true)
3075  {
3078  ReorderBufferTupleCidEnt *new_ent;
3079  bool found;
3080 
3081  /* be careful about padding */
3082  memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
3083 
3084  /* read all mappings till the end of the file */
3085  readBytes = read(fd, &map, sizeof(LogicalRewriteMappingData));
3086 
3087  if (readBytes < 0)
3088  ereport(ERROR,
3090  errmsg("could not read file \"%s\": %m",
3091  path)));
3092  else if (readBytes == 0) /* EOF */
3093  break;
3094  else if (readBytes != sizeof(LogicalRewriteMappingData))
3095  ereport(ERROR,
3097  errmsg("could not read from file \"%s\": read %d instead of %d bytes",
3098  path, readBytes,
3099  (int32) sizeof(LogicalRewriteMappingData))));
3100 
3101  key.relnode = map.old_node;
3102  ItemPointerCopy(&map.old_tid,
3103  &key.tid);
3104 
3105 
3106  ent = (ReorderBufferTupleCidEnt *)
3107  hash_search(tuplecid_data,
3108  (void *) &key,
3109  HASH_FIND,
3110  NULL);
3111 
3112  /* no existing mapping, no need to update */
3113  if (!ent)
3114  continue;
3115 
3116  key.relnode = map.new_node;
3117  ItemPointerCopy(&map.new_tid,
3118  &key.tid);
3119 
3120  new_ent = (ReorderBufferTupleCidEnt *)
3121  hash_search(tuplecid_data,
3122  (void *) &key,
3123  HASH_ENTER,
3124  &found);
3125 
3126  if (found)
3127  {
3128  /*
3129  * Make sure the existing mapping makes sense. We sometime update
3130  * old records that did not yet have a cmax (e.g. pg_class' own
3131  * entry while rewriting it) during rewrites, so allow that.
3132  */
3133  Assert(ent->cmin == InvalidCommandId || ent->cmin == new_ent->cmin);
3134  Assert(ent->cmax == InvalidCommandId || ent->cmax == new_ent->cmax);
3135  }
3136  else
3137  {
3138  /* update mapping */
3139  new_ent->cmin = ent->cmin;
3140  new_ent->cmax = ent->cmax;
3141  new_ent->combocid = ent->combocid;
3142  }
3143  }
3144 }
3145 
3146 
3147 /*
3148  * Check whether the TransactionOId 'xid' is in the pre-sorted array 'xip'.
3149  */
3150 static bool
3152 {
3153  return bsearch(&xid, xip, num,
3154  sizeof(TransactionId), xidComparator) != NULL;
3155 }
3156 
3157 /*
3158  * qsort() comparator for sorting RewriteMappingFiles in LSN order.
3159  */
3160 static int
3161 file_sort_by_lsn(const void *a_p, const void *b_p)
3162 {
3163  RewriteMappingFile *a = *(RewriteMappingFile **) a_p;
3164  RewriteMappingFile *b = *(RewriteMappingFile **) b_p;
3165 
3166  if (a->lsn < b->lsn)
3167  return -1;
3168  else if (a->lsn > b->lsn)
3169  return 1;
3170  return 0;
3171 }
3172 
3173 /*
3174  * Apply any existing logical remapping files if there are any targeted at our
3175  * transaction for relid.
3176  */
3177 static void
3179 {
3180  DIR *mapping_dir;
3181  struct dirent *mapping_de;
3182  List *files = NIL;
3183  ListCell *file;
3184  RewriteMappingFile **files_a;
3185  size_t off;
3186  Oid dboid = IsSharedRelation(relid) ? InvalidOid : MyDatabaseId;
3187 
3188  mapping_dir = AllocateDir("pg_logical/mappings");
3189  while ((mapping_de = ReadDir(mapping_dir, "pg_logical/mappings")) != NULL)
3190  {
3191  Oid f_dboid;
3192  Oid f_relid;
3193  TransactionId f_mapped_xid;
3194  TransactionId f_create_xid;
3195  XLogRecPtr f_lsn;
3196  uint32 f_hi,
3197  f_lo;
3198  RewriteMappingFile *f;
3199 
3200  if (strcmp(mapping_de->d_name, ".") == 0 ||
3201  strcmp(mapping_de->d_name, "..") == 0)
3202  continue;
3203 
3204  /* Ignore files that aren't ours */
3205  if (strncmp(mapping_de->d_name, "map-", 4) != 0)
3206  continue;
3207 
3208  if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
3209  &f_dboid, &f_relid, &f_hi, &f_lo,
3210  &f_mapped_xid, &f_create_xid) != 6)
3211  elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
3212 
3213  f_lsn = ((uint64) f_hi) << 32 | f_lo;
3214 
3215  /* mapping for another database */
3216  if (f_dboid != dboid)
3217  continue;
3218 
3219  /* mapping for another relation */
3220  if (f_relid != relid)
3221  continue;
3222 
3223  /* did the creating transaction abort? */
3224  if (!TransactionIdDidCommit(f_create_xid))
3225  continue;
3226 
3227  /* not for our transaction */
3228  if (!TransactionIdInArray(f_mapped_xid, snapshot->subxip, snapshot->subxcnt))
3229  continue;
3230 
3231  /* ok, relevant, queue for apply */
3232  f = palloc(sizeof(RewriteMappingFile));
3233  f->lsn = f_lsn;
3234  strcpy(f->fname, mapping_de->d_name);
3235  files = lappend(files, f);
3236  }
3237  FreeDir(mapping_dir);
3238 
3239  /* build array we can easily sort */
3240  files_a = palloc(list_length(files) * sizeof(RewriteMappingFile *));
3241  off = 0;
3242  foreach(file, files)
3243  {
3244  files_a[off++] = lfirst(file);
3245  }
3246 
3247  /* sort files so we apply them in LSN order */
3248  qsort(files_a, list_length(files), sizeof(RewriteMappingFile *),
3250 
3251  for (off = 0; off < list_length(files); off++)
3252  {
3253  RewriteMappingFile *f = files_a[off];
3254 
3255  elog(DEBUG1, "applying mapping: \"%s\" in %u", f->fname,
3256  snapshot->subxip[0]);
3257  ApplyLogicalMappingFile(tuplecid_data, relid, f->fname);
3258  pfree(f);
3259  }
3260 }
3261 
3262 /*
3263  * Lookup cmin/cmax of a tuple, during logical decoding where we can't rely on
3264  * combocids.
3265  */
3266 bool
3268  Snapshot snapshot,
3269  HeapTuple htup, Buffer buffer,
3270  CommandId *cmin, CommandId *cmax)
3271 {
3274  ForkNumber forkno;
3275  BlockNumber blockno;
3276  bool updated_mapping = false;
3277 
3278  /* be careful about padding */
3279  memset(&key, 0, sizeof(key));
3280 
3281  Assert(!BufferIsLocal(buffer));
3282 
3283  /*
3284  * get relfilenode from the buffer, no convenient way to access it other
3285  * than that.
3286  */
3287  BufferGetTag(buffer, &key.relnode, &forkno, &blockno);
3288 
3289  /* tuples can only be in the main fork */
3290  Assert(forkno == MAIN_FORKNUM);
3291  Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self));
3292 
3293  ItemPointerCopy(&htup->t_self,
3294  &key.tid);
3295 
3296 restart:
3297  ent = (ReorderBufferTupleCidEnt *)
3298  hash_search(tuplecid_data,
3299  (void *) &key,
3300  HASH_FIND,
3301  NULL);
3302 
3303  /*
3304  * failed to find a mapping, check whether the table was rewritten and
3305  * apply mapping if so, but only do that once - there can be no new
3306  * mappings while we are in here since we have to hold a lock on the
3307  * relation.
3308  */
3309  if (ent == NULL && !updated_mapping)
3310  {
3311  UpdateLogicalMappings(tuplecid_data, htup->t_tableOid, snapshot);
3312  /* now check but don't update for a mapping again */
3313  updated_mapping = true;
3314  goto restart;
3315  }
3316  else if (ent == NULL)
3317  return false;
3318 
3319  if (cmin)
3320  *cmin = ent->cmin;
3321  if (cmax)
3322  *cmax = ent->cmax;
3323  return true;
3324 }
static void ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
XLogRecPtr first_lsn
bool ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
#define NIL
Definition: pg_list.h:69
uint32 CommandId
Definition: c.h:407
void ReorderBufferReturnChange(ReorderBuffer *rb, ReorderBufferChange *change)
TimestampTz commit_time
#define BlockIdGetBlockNumber(blockId)
Definition: block.h:115
struct ReorderBufferToastEnt ReorderBufferToastEnt
void AbortCurrentTransaction(void)
Definition: xact.c:2982
ReorderBufferIterTXNEntry entries[FLEXIBLE_ARRAY_MEMBER]
#define SizeofHeapTupleHeader
Definition: htup_details.h:170
bool IsToastRelation(Relation relation)
Definition: catalog.c:134
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:795
dlist_head cached_changes
void ReorderBufferQueueMessage(ReorderBuffer *rb, TransactionId xid, Snapshot snapshot, XLogRecPtr lsn, bool transactional, const char *prefix, Size message_size, const char *message)
#define relpathperm(rnode, forknum)
Definition: relpath.h:67
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
Snapshot base_snapshot
ReorderBufferApplyChangeCB apply_change
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:203
HeapTupleData * HeapTuple
Definition: htup.h:70
#define DEBUG1
Definition: elog.h:25
#define VALGRIND_MAKE_MEM_DEFINED(addr, size)
Definition: memdebug.h:26
dlist_node * cur
Definition: ilist.h:180
static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change)
RepOriginId origin_id
void StartupReorderBuffer(void)
#define VARDATA(PTR)
Definition: postgres.h:305
#define fastgetattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:694
static int32 next
Definition: blutils.c:205
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
static const Size max_cached_tuplebufs
void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid)
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
uint32 TransactionId
Definition: c.h:393
void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
bool copied
Definition: snapshot.h:93
void ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid, XLogRecPtr commit_lsn, XLogRecPtr end_lsn, TimestampTz commit_time, RepOriginId origin_id, XLogRecPtr origin_lsn)
MemoryContext hcxt
Definition: hsearch.h:78
#define DatumGetInt32(X)
Definition: postgres.h:480
#define RelationGetDescr(relation)
Definition: rel.h:351
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
#define VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer)
Definition: tuptoaster.h:111
#define DEBUG3
Definition: elog.h:23
#define write(a, b, c)
Definition: win32.h:19
#define VARHDRSZ_SHORT
Definition: postgres.h:269
TransactionId by_txn_last_xid
#define VARSIZE(PTR)
Definition: postgres.h:306
#define VALGRIND_MAKE_MEM_UNDEFINED(addr, size)
Definition: memdebug.h:28
#define PointerGetDatum(X)
Definition: postgres.h:564
ReorderBufferTXN * txn
static bool TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num)
#define VARHDRSZ
Definition: c.h:440
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
XLogRecPtr current_restart_decoding_lsn
#define DatumGetObjectId(X)
Definition: postgres.h:508
char * pstrdup(const char *in)
Definition: mcxt.c:1168
static ReorderBufferTXN * ReorderBufferGetTXN(ReorderBuffer *rb)
static void dlist_push_tail(dlist_head *head, dlist_node *node)
Definition: ilist.h:317
Oid RelidByRelfilenode(Oid reltablespace, Oid relfilenode)
Form_pg_attribute * attrs
Definition: tupdesc.h:74
void ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, Snapshot snap)
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void ReorderBufferFree(ReorderBuffer *rb)
static void slist_push_head(slist_head *head, slist_node *node)
Definition: ilist.h:574
uint16 RepOriginId
Definition: xlogdefs.h:51
Size entrysize
Definition: hsearch.h:73
struct cursor * cur
Definition: ecpg.c:28
char fname[MAXPGPATH]
int32 va_rawsize
Definition: postgres.h:70
struct ReorderBufferChange::@51::@53 msg
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4318
void binaryheap_replace_first(binaryheap *heap, Datum d)
Definition: binaryheap.c:204
void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, RelFileNode node, ItemPointerData tid, CommandId cmin, CommandId cmax, CommandId combocid)
static void ReorderBufferIterTXNFinish(ReorderBuffer *rb, ReorderBufferIterTXNState *state)
uint32 BlockNumber
Definition: block.h:31
void TeardownHistoricSnapshot(bool is_error)
Definition: snapmgr.c:1870
ReorderBufferCommitCB commit
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:692
ReorderBufferChange * ReorderBufferGetChange(ReorderBuffer *rb)
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:498
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:887
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
ReplicationSlotPersistentData data
Definition: slot.h:114
static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn, int *fd, XLogSegNo *segno)
struct ReorderBufferTupleCidKey ReorderBufferTupleCidKey
struct SnapshotData * Snapshot
Definition: snapshot.h:22
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
XLogRecPtr base_snapshot_lsn
Definition: dirent.h:9
uint32 regd_count
Definition: snapshot.h:107
#define PANIC
Definition: elog.h:53
enum ReorderBufferChangeType action
Definition: reorderbuffer.h:77
void binaryheap_add_unordered(binaryheap *heap, Datum d)
Definition: binaryheap.c:110
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define VARDATA_EXTERNAL(PTR)
Definition: postgres.h:313
#define PG_BINARY
Definition: c.h:1018
int natts
Definition: tupdesc.h:73
XLogRecPtr origin_lsn
#define ALLOCSET_DEFAULT_MINSIZE
Definition: memutils.h:142
static void ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname)
signed int int32
Definition: c.h:253
static int file_sort_by_lsn(const void *a_p, const void *b_p)
#define XLogSegNoOffsetToRecPtr(segno, offset, dest)
Definition: xlog_internal.h:95
#define FirstCommandId
Definition: c.h:409
void ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr)
HeapTupleHeader t_data
Definition: htup.h:67
#define VARATT_IS_EXTERNAL(PTR)
Definition: postgres.h:316
struct ReorderBufferChange::@51::@54 tuplecid
bool ReplicationSlotValidateName(const char *name, int elevel)
Definition: slot.c:175
static dlist_node * dlist_next_node(dlist_head *head, dlist_node *node)
Definition: ilist.h:421
Definition: dynahash.c:193
struct ReorderBufferChange::@51::@52 tp
#define ReorderBufferTupleBufData(p)
Definition: reorderbuffer.h:36
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
double TimestampTz
Definition: timestamp.h:51
void pfree(void *pointer)
Definition: mcxt.c:995
static void slist_init(slist_head *head)
Definition: ilist.h:554
char * Pointer
Definition: c.h:242
Size nr_cached_transactions
Definition: dirent.c:25
#define ERROR
Definition: elog.h:43
Size nr_cached_changes
BlockIdData ip_blkid
Definition: itemptr.h:39
#define VARATT_IS_SHORT(PTR)
Definition: postgres.h:327
dlist_head changes
Datum binaryheap_first(binaryheap *heap)
Definition: binaryheap.c:159
#define MAXPGPATH
ItemPointerData t_self
Definition: htup.h:65
ReorderBufferTupleCidKey key
Definition: reorderbuffer.c:93
#define DEBUG2
Definition: elog.h:24
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:414
void ReorderBufferImmediateInvalidation(ReorderBuffer *rb, uint32 ninvalidations, SharedInvalidationMessage *invalidations)
uint32 t_len
Definition: htup.h:64
#define MaxHeapTupleSize
Definition: htup_details.h:536
struct varlena * reconstructed
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4153
#define SET_VARTAG_EXTERNAL(PTR, tag)
Definition: postgres.h:334
uint64 XLogSegNo
Definition: xlogdefs.h:34
static const Size max_cached_changes
int OpenTransientFile(FileName fileName, int fileFlags, int fileMode)
Definition: fd.c:2016
int errcode_for_file_access(void)
Definition: elog.c:598
HeapTupleData tuple
Definition: reorderbuffer.h:27
struct SnapshotData SnapshotData
dlist_head cached_transactions
TransactionId GetCurrentTransactionIdIfAny(void)
Definition: xact.c:431
#define InvalidTransactionId
Definition: transam.h:31
static const Size max_cached_transactions
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
bool ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
unsigned int uint32
Definition: c.h:265
XLogRecPtr final_lsn
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2207
Oid t_tableOid
Definition: htup.h:66
void RelationClose(Relation relation)
Definition: relcache.c:1851
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
ReorderBufferMessageCB message
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
int bh_size
Definition: binaryheap.h:32
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
TransactionId * xip
Definition: snapshot.h:76
static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap, ReorderBufferTXN *txn, CommandId cid)
#define VARSIZE_SHORT(PTR)
Definition: postgres.h:308
ForkNumber
Definition: relpath.h:24
static slist_node * slist_pop_head_node(slist_head *head)
Definition: ilist.h:596
List * lappend(List *list, void *datum)
Definition: list.c:128
static HTAB * tuplecid_data
Definition: snapmgr.c:171
int CloseTransientFile(int fd)
Definition: fd.c:2177
static void ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
struct ReorderBufferTupleCidEnt ReorderBufferTupleCidEnt
void ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid, TransactionId subxid, XLogRecPtr lsn)
#define INDIRECT_POINTER_SIZE
Definition: tuptoaster.h:102
static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn, char *change)
#define dlist_head_element(type, membername, lhead)
Definition: ilist.h:487
#define HASH_BLOBS
Definition: hsearch.h:88
ReorderBufferChange * change
static int ReorderBufferIterCompare(Datum a, Datum b, void *arg)
MemoryContext context
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid, TransactionId subxid, XLogRecPtr commit_lsn, XLogRecPtr end_lsn)
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:436
void * palloc0(Size size)
Definition: mcxt.c:923
static bool dlist_has_next(dlist_head *head, dlist_node *node)
Definition: ilist.h:402
#define InvalidCommandId
Definition: c.h:410
uintptr_t Datum
Definition: postgres.h:374
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:301
ReorderBufferTXN * by_txn_last_txn
static void ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
static void cleanup(void)
Definition: bootstrap.c:845
dlist_head toplevel_by_lsn
struct RewriteMappingFile RewriteMappingFile
Oid MyDatabaseId
Definition: globals.c:76
TransactionId xid
static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change)
bool IsSharedRelation(Oid relationId)
Definition: catalog.c:218
Size keysize
Definition: hsearch.h:72
dlist_node * cur
Definition: ilist.h:161
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:787
static void AssertTXNLsnOrder(ReorderBuffer *rb)
void ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, Snapshot snap)
#define InvalidOid
Definition: postgres_ext.h:36
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
CommandId curcid
Definition: snapshot.h:95
struct ReorderBufferIterTXNState ReorderBufferIterTXNState
static void ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn)
struct ReorderBufferDiskChange ReorderBufferDiskChange
void binaryheap_build(binaryheap *heap)
Definition: binaryheap.c:126
#define free(a)
Definition: header.h:60
struct ReorderBufferIterTXNEntry ReorderBufferIterTXNEntry
#define PG_CATCH()
Definition: elog.h:292
ReplicationSlot * MyReplicationSlot
Definition: slot.c:94
#define XLByteToSeg(xlrp, logSegNo)
ItemPointerData new_tid
Definition: rewriteheap.h:40
#define NULL
Definition: c.h:226
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:667
#define lfirst(lc)
Definition: pg_list.h:106
ReorderBufferTXN * ReorderBufferGetOldestTXN(ReorderBuffer *rb)
static void ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn, int fd, ReorderBufferChange *change)
static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn)
Definition: regguts.h:313
union ReorderBufferChange::@51 data
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2273
static ReorderBufferChange * ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state)
#define VARATT_EXTERNAL_GET_POINTER(toast_pointer, attr)
Definition: tuptoaster.h:121
int32 va_extsize
Definition: postgres.h:71
XLogRecPtr end_lsn
void StartTransactionCommand(void)
Definition: xact.c:2673
void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, Size nmsgs, SharedInvalidationMessage *msgs)
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
size_t Size
Definition: c.h:352
void binaryheap_free(binaryheap *heap)
Definition: binaryheap.c:69
SharedInvalidationMessage * invalidations
static int list_length(const List *l)
Definition: pg_list.h:89
void BeginInternalSubTransaction(char *name)
Definition: xact.c:4049
#define BufferIsLocal(buffer)
Definition: buf.h:37
void ReorderBufferReturnTupleBuf(ReorderBuffer *rb, ReorderBufferTupleBuf *tuple)
#define PG_RE_THROW()
Definition: elog.h:313
ReorderBuffer * ReorderBufferAllocate(void)
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1355
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1024
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1345
static void ReorderBufferSerializeReserve(ReorderBuffer *rb, Size sz)
struct varlena * pointer
Definition: postgres.h:87
void ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, ReorderBufferChange *change)
void SnapBuildSnapDecRefcount(Snapshot snap)
Definition: snapbuild.c:399
#define LOGICAL_REWRITE_FORMAT
Definition: rewriteheap.h:54
dlist_head subtxns
binaryheap * binaryheap_allocate(int capacity, binaryheap_comparator compare, void *arg)
Definition: binaryheap.c:33
#define VARATT_IS_EXTENDED(PTR)
Definition: postgres.h:328
#define DatumGetPointer(X)
Definition: postgres.h:557
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:867
Size nr_cached_tuplebufs
void LocalExecuteInvalidationMessage(SharedInvalidationMessage *msg)
Definition: inval.c:538
#define Int32GetDatum(X)
Definition: postgres.h:487
static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
static ReorderBufferTXN * ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create, bool *is_new, XLogRecPtr lsn, bool create_as_top)
uint32 xcnt
Definition: snapshot.h:77
void * palloc(Size size)
Definition: mcxt.c:894
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void UpdateLogicalMappings(HTAB *tuplecid_data, Oid relid, Snapshot snapshot)
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:752
static void ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
ReorderBufferTXN * txn
Definition: reorderbuffer.c:81
void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
static dlist_node * dlist_pop_head_node(dlist_head *head)
Definition: ilist.h:368
void SetupHistoricSnapshot(Snapshot historic_snapshot, HTAB *tuplecids)
Definition: snapmgr.c:1854
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:143
int i
XLogRecPtr restart_decoding_lsn
#define NameStr(name)
Definition: c.h:494
#define SET_VARSIZE_COMPRESSED(PTR, len)
Definition: postgres.h:332
void * arg
Datum binaryheap_remove_first(binaryheap *heap)
Definition: binaryheap.c:174
static const Size max_changes_in_memory
Definition: c.h:434
#define ALLOCSET_DEFAULT_MAXSIZE
Definition: memutils.h:144
struct ReorderBufferTXNByIdEnt ReorderBufferTXNByIdEnt
void ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:330
char d_name[MAX_PATH]
Definition: dirent.h:14
#define elog
Definition: elog.h:218
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:70
static void ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
#define qsort(a, b, c, d)
Definition: port.h:438
#define TransactionIdIsValid(xid)
Definition: transam.h:41
ReorderBufferChange change
ReorderBufferBeginCB begin
static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
void BufferGetTag(Buffer buffer, RelFileNode *rnode, ForkNumber *forknum, BlockNumber *blknum)
Definition: bufmgr.c:2609
#define PG_TRY()
Definition: elog.h:283
#define XLByteInSeg(xlrp, logSegNo)
static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap)
void ReorderBufferProcessXid(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
#define RELKIND_SEQUENCE
Definition: pg_class.h:158
#define lstat(path, sb)
Definition: win32.h:272
Definition: pg_list.h:45
int Buffer
Definition: buf.h:23
OffsetNumber ip_posid
Definition: itemptr.h:40
static ReorderBufferIterTXNState * ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn)
Relation RelationIdGetRelation(Oid relationId)
Definition: relcache.c:1762
#define PG_END_TRY()
Definition: elog.h:299
#define read(a, b, c)
Definition: win32.h:18
int FreeDir(DIR *dir)
Definition: fd.c:2316
struct HeapTupleData HeapTupleData
#define offsetof(type, field)
Definition: c.h:547
dlist_head tuplecids
slist_head cached_tuplebufs
#define ItemPointerCopy(fromPointer, toPointer)
Definition: itemptr.h:124
TransactionId * subxip
Definition: snapshot.h:88
uint32 active_count
Definition: snapshot.h:106
int xidComparator(const void *arg1, const void *arg2)
Definition: xid.c:141
int32 subxcnt
Definition: snapshot.h:89
void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, CommandId cid)
ReorderBufferTupleBuf * ReorderBufferGetTupleBuf(ReorderBuffer *rb, Size tuple_len)
bool ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data, Snapshot snapshot, HeapTuple htup, Buffer buffer, CommandId *cmin, CommandId *cmax)
ItemPointerData old_tid
Definition: rewriteheap.h:39