PostgreSQL Source Code  git master
rewriteheap.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * rewriteheap.c
4  * Support functions to rewrite tables.
5  *
6  * These functions provide a facility to completely rewrite a heap, while
7  * preserving visibility information and update chains.
8  *
9  * INTERFACE
10  *
11  * The caller is responsible for creating the new heap, all catalog
12  * changes, supplying the tuples to be written to the new heap, and
13  * rebuilding indexes. The caller must hold AccessExclusiveLock on the
14  * target table, because we assume no one else is writing into it.
15  *
16  * To use the facility:
17  *
18  * begin_heap_rewrite
19  * while (fetch next tuple)
20  * {
21  * if (tuple is dead)
22  * rewrite_heap_dead_tuple
23  * else
24  * {
25  * // do any transformations here if required
26  * rewrite_heap_tuple
27  * }
28  * }
29  * end_heap_rewrite
30  *
31  * The contents of the new relation shouldn't be relied on until after
32  * end_heap_rewrite is called.
33  *
34  *
35  * IMPLEMENTATION
36  *
37  * This would be a fairly trivial affair, except that we need to maintain
38  * the ctid chains that link versions of an updated tuple together.
39  * Since the newly stored tuples will have tids different from the original
40  * ones, if we just copied t_ctid fields to the new table the links would
41  * be wrong. When we are required to copy a (presumably recently-dead or
42  * delete-in-progress) tuple whose ctid doesn't point to itself, we have
43  * to substitute the correct ctid instead.
44  *
45  * For each ctid reference from A -> B, we might encounter either A first
46  * or B first. (Note that a tuple in the middle of a chain is both A and B
47  * of different pairs.)
48  *
49  * If we encounter A first, we'll store the tuple in the unresolved_tups
50  * hash table. When we later encounter B, we remove A from the hash table,
51  * fix the ctid to point to the new location of B, and insert both A and B
52  * to the new heap.
53  *
54  * If we encounter B first, we can insert B to the new heap right away.
55  * We then add an entry to the old_new_tid_map hash table showing B's
56  * original tid (in the old heap) and new tid (in the new heap).
57  * When we later encounter A, we get the new location of B from the table,
58  * and can write A immediately with the correct ctid.
59  *
60  * Entries in the hash tables can be removed as soon as the later tuple
61  * is encountered. That helps to keep the memory usage down. At the end,
62  * both tables are usually empty; we should have encountered both A and B
63  * of each pair. However, it's possible for A to be RECENTLY_DEAD and B
64  * entirely DEAD according to HeapTupleSatisfiesVacuum, because the test
65  * for deadness using OldestXmin is not exact. In such a case we might
66  * encounter B first, and skip it, and find A later. Then A would be added
67  * to unresolved_tups, and stay there until end of the rewrite. Since
68  * this case is very unusual, we don't worry about the memory usage.
69  *
70  * Using in-memory hash tables means that we use some memory for each live
71  * update chain in the table, from the time we find one end of the
72  * reference until we find the other end. That shouldn't be a problem in
73  * practice, but if you do something like an UPDATE without a where-clause
74  * on a large table, and then run CLUSTER in the same transaction, you
75  * could run out of memory. It doesn't seem worthwhile to add support for
76  * spill-to-disk, as there shouldn't be that many RECENTLY_DEAD tuples in a
77  * table under normal circumstances. Furthermore, in the typical scenario
78  * of CLUSTERing on an unchanging key column, we'll see all the versions
79  * of a given tuple together anyway, and so the peak memory usage is only
80  * proportional to the number of RECENTLY_DEAD versions of a single row, not
81  * in the whole table. Note that if we do fail halfway through a CLUSTER,
82  * the old table is still valid, so failure is not catastrophic.
83  *
84  * We can't use the normal heap_insert function to insert into the new
85  * heap, because heap_insert overwrites the visibility information.
86  * We use a special-purpose raw_heap_insert function instead, which
87  * is optimized for bulk inserting a lot of tuples, knowing that we have
88  * exclusive access to the heap. raw_heap_insert builds new pages in
89  * local storage. When a page is full, or at the end of the process,
90  * we insert it to WAL as a single record and then write it to disk
91  * directly through smgr. Note, however, that any data sent to the new
92  * heap's TOAST table will go through the normal bufmgr.
93  *
94  *
95  * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
96  * Portions Copyright (c) 1994-5, Regents of the University of California
97  *
98  * IDENTIFICATION
99  * src/backend/access/heap/rewriteheap.c
100  *
101  *-------------------------------------------------------------------------
102  */
103 #include "postgres.h"
104 
105 #include <unistd.h>
106 
107 #include "access/heapam.h"
108 #include "access/heapam_xlog.h"
109 #include "access/heaptoast.h"
110 #include "access/rewriteheap.h"
111 #include "access/transam.h"
112 #include "access/xact.h"
113 #include "access/xloginsert.h"
114 #include "catalog/catalog.h"
115 #include "common/file_utils.h"
116 #include "lib/ilist.h"
117 #include "miscadmin.h"
118 #include "pgstat.h"
119 #include "replication/logical.h"
120 #include "replication/slot.h"
121 #include "storage/bufmgr.h"
122 #include "storage/fd.h"
123 #include "storage/procarray.h"
124 #include "storage/smgr.h"
125 #include "utils/memutils.h"
126 #include "utils/rel.h"
127 
128 /*
129  * State associated with a rewrite operation. This is opaque to the user
130  * of the rewrite facility.
131  */
132 typedef struct RewriteStateData
133 {
134  Relation rs_old_rel; /* source heap */
135  Relation rs_new_rel; /* destination heap */
136  Page rs_buffer; /* page currently being built */
137  BlockNumber rs_blockno; /* block where page will go */
138  bool rs_buffer_valid; /* T if any tuples in buffer */
139  bool rs_logical_rewrite; /* do we need to do logical rewriting */
140  TransactionId rs_oldest_xmin; /* oldest xmin used by caller to determine
141  * tuple visibility */
142  TransactionId rs_freeze_xid; /* Xid that will be used as freeze cutoff
143  * point */
144  TransactionId rs_logical_xmin; /* Xid that will be used as cutoff point
145  * for logical rewrites */
146  MultiXactId rs_cutoff_multi; /* MultiXactId that will be used as cutoff
147  * point for multixacts */
148  MemoryContext rs_cxt; /* for hash tables and entries and tuples in
149  * them */
150  XLogRecPtr rs_begin_lsn; /* XLogInsertLsn when starting the rewrite */
151  HTAB *rs_unresolved_tups; /* unmatched A tuples */
152  HTAB *rs_old_new_tid_map; /* unmatched B tuples */
153  HTAB *rs_logical_mappings; /* logical remapping files */
154  uint32 rs_num_rewrite_mappings; /* # in memory mappings */
156 
157 /*
158  * The lookup keys for the hash tables are tuple TID and xmin (we must check
159  * both to avoid false matches from dead tuples). Beware that there is
160  * probably some padding space in this struct; it must be zeroed out for
161  * correct hashtable operation.
162  */
163 typedef struct
164 {
165  TransactionId xmin; /* tuple xmin */
166  ItemPointerData tid; /* tuple location in old heap */
167 } TidHashKey;
168 
169 /*
170  * Entry structures for the hash tables
171  */
172 typedef struct
173 {
174  TidHashKey key; /* expected xmin/old location of B tuple */
175  ItemPointerData old_tid; /* A's location in the old heap */
176  HeapTuple tuple; /* A's tuple contents */
178 
180 
181 typedef struct
182 {
183  TidHashKey key; /* actual xmin/old location of B tuple */
184  ItemPointerData new_tid; /* where we put it in the new heap */
186 
188 
189 /*
190  * In-Memory data for an xid that might need logical remapping entries
191  * to be logged.
192  */
193 typedef struct RewriteMappingFile
194 {
195  TransactionId xid; /* xid that might need to see the row */
196  int vfd; /* fd of mappings file */
197  off_t off; /* how far have we written yet */
198  dclist_head mappings; /* list of in-memory mappings */
199  char path[MAXPGPATH]; /* path, for error messages */
201 
202 /*
203  * A single In-Memory logical rewrite mapping, hanging off
204  * RewriteMappingFile->mappings.
205  */
207 {
208  LogicalRewriteMappingData map; /* map between old and new location of the
209  * tuple */
212 
213 
214 /* prototypes for internal functions */
215 static void raw_heap_insert(RewriteState state, HeapTuple tup);
216 
217 /* internal logical remapping prototypes */
221 
222 
223 /*
224  * Begin a rewrite of a table
225  *
226  * old_heap old, locked heap relation tuples will be read from
227  * new_heap new, locked heap relation to insert tuples to
228  * oldest_xmin xid used by the caller to determine which tuples are dead
229  * freeze_xid xid before which tuples will be frozen
230  * cutoff_multi multixact before which multis will be removed
231  *
232  * Returns an opaque RewriteState, allocated in current memory context,
233  * to be used in subsequent calls to the other functions.
234  */
236 begin_heap_rewrite(Relation old_heap, Relation new_heap, TransactionId oldest_xmin,
237  TransactionId freeze_xid, MultiXactId cutoff_multi)
238 {
240  MemoryContext rw_cxt;
241  MemoryContext old_cxt;
242  HASHCTL hash_ctl;
243 
244  /*
245  * To ease cleanup, make a separate context that will contain the
246  * RewriteState struct itself plus all subsidiary data.
247  */
249  "Table rewrite",
251  old_cxt = MemoryContextSwitchTo(rw_cxt);
252 
253  /* Create and fill in the state struct */
254  state = palloc0(sizeof(RewriteStateData));
255 
256  state->rs_old_rel = old_heap;
257  state->rs_new_rel = new_heap;
258  state->rs_buffer = (Page) palloc_aligned(BLCKSZ, PG_IO_ALIGN_SIZE, 0);
259  /* new_heap needn't be empty, just locked */
260  state->rs_blockno = RelationGetNumberOfBlocks(new_heap);
261  state->rs_buffer_valid = false;
262  state->rs_oldest_xmin = oldest_xmin;
263  state->rs_freeze_xid = freeze_xid;
264  state->rs_cutoff_multi = cutoff_multi;
265  state->rs_cxt = rw_cxt;
266 
267  /* Initialize hash tables used to track update chains */
268  hash_ctl.keysize = sizeof(TidHashKey);
269  hash_ctl.entrysize = sizeof(UnresolvedTupData);
270  hash_ctl.hcxt = state->rs_cxt;
271 
272  state->rs_unresolved_tups =
273  hash_create("Rewrite / Unresolved ctids",
274  128, /* arbitrary initial size */
275  &hash_ctl,
277 
278  hash_ctl.entrysize = sizeof(OldToNewMappingData);
279 
280  state->rs_old_new_tid_map =
281  hash_create("Rewrite / Old to new tid map",
282  128, /* arbitrary initial size */
283  &hash_ctl,
285 
286  MemoryContextSwitchTo(old_cxt);
287 
289 
290  return state;
291 }
292 
293 /*
294  * End a rewrite.
295  *
296  * state and any other resources are freed.
297  */
298 void
300 {
301  HASH_SEQ_STATUS seq_status;
302  UnresolvedTup unresolved;
303 
304  /*
305  * Write any remaining tuples in the UnresolvedTups table. If we have any
306  * left, they should in fact be dead, but let's err on the safe side.
307  */
308  hash_seq_init(&seq_status, state->rs_unresolved_tups);
309 
310  while ((unresolved = hash_seq_search(&seq_status)) != NULL)
311  {
312  ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
313  raw_heap_insert(state, unresolved->tuple);
314  }
315 
316  /* Write the last page, if any */
317  if (state->rs_buffer_valid)
318  {
319  if (RelationNeedsWAL(state->rs_new_rel))
320  log_newpage(&state->rs_new_rel->rd_locator,
321  MAIN_FORKNUM,
322  state->rs_blockno,
323  state->rs_buffer,
324  true);
325 
326  PageSetChecksumInplace(state->rs_buffer, state->rs_blockno);
327 
329  state->rs_blockno, state->rs_buffer, true);
330  }
331 
332  /*
333  * When we WAL-logged rel pages, we must nonetheless fsync them. The
334  * reason is the same as in storage.c's RelationCopyStorage(): we're
335  * writing data that's not in shared buffers, and so a CHECKPOINT
336  * occurring during the rewriteheap operation won't have fsync'd data we
337  * wrote before the checkpoint.
338  */
339  if (RelationNeedsWAL(state->rs_new_rel))
341 
343 
344  /* Deleting the context frees everything */
345  MemoryContextDelete(state->rs_cxt);
346 }
347 
348 /*
349  * Add a tuple to the new heap.
350  *
351  * Visibility information is copied from the original tuple, except that
352  * we "freeze" very-old tuples. Note that since we scribble on new_tuple,
353  * it had better be temp storage not a pointer to the original tuple.
354  *
355  * state opaque state as returned by begin_heap_rewrite
356  * old_tuple original tuple in the old heap
357  * new_tuple new, rewritten tuple to be inserted to new heap
358  */
359 void
361  HeapTuple old_tuple, HeapTuple new_tuple)
362 {
363  MemoryContext old_cxt;
364  ItemPointerData old_tid;
365  TidHashKey hashkey;
366  bool found;
367  bool free_new;
368 
369  old_cxt = MemoryContextSwitchTo(state->rs_cxt);
370 
371  /*
372  * Copy the original tuple's visibility information into new_tuple.
373  *
374  * XXX we might later need to copy some t_infomask2 bits, too? Right now,
375  * we intentionally clear the HOT status bits.
376  */
377  memcpy(&new_tuple->t_data->t_choice.t_heap,
378  &old_tuple->t_data->t_choice.t_heap,
379  sizeof(HeapTupleFields));
380 
381  new_tuple->t_data->t_infomask &= ~HEAP_XACT_MASK;
382  new_tuple->t_data->t_infomask2 &= ~HEAP2_XACT_MASK;
383  new_tuple->t_data->t_infomask |=
384  old_tuple->t_data->t_infomask & HEAP_XACT_MASK;
385 
386  /*
387  * While we have our hands on the tuple, we may as well freeze any
388  * eligible xmin or xmax, so that future VACUUM effort can be saved.
389  */
390  heap_freeze_tuple(new_tuple->t_data,
391  state->rs_old_rel->rd_rel->relfrozenxid,
392  state->rs_old_rel->rd_rel->relminmxid,
393  state->rs_freeze_xid,
394  state->rs_cutoff_multi);
395 
396  /*
397  * Invalid ctid means that ctid should point to the tuple itself. We'll
398  * override it later if the tuple is part of an update chain.
399  */
400  ItemPointerSetInvalid(&new_tuple->t_data->t_ctid);
401 
402  /*
403  * If the tuple has been updated, check the old-to-new mapping hash table.
404  */
405  if (!((old_tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
406  HeapTupleHeaderIsOnlyLocked(old_tuple->t_data)) &&
408  !(ItemPointerEquals(&(old_tuple->t_self),
409  &(old_tuple->t_data->t_ctid))))
410  {
411  OldToNewMapping mapping;
412 
413  memset(&hashkey, 0, sizeof(hashkey));
414  hashkey.xmin = HeapTupleHeaderGetUpdateXid(old_tuple->t_data);
415  hashkey.tid = old_tuple->t_data->t_ctid;
416 
417  mapping = (OldToNewMapping)
418  hash_search(state->rs_old_new_tid_map, &hashkey,
419  HASH_FIND, NULL);
420 
421  if (mapping != NULL)
422  {
423  /*
424  * We've already copied the tuple that t_ctid points to, so we can
425  * set the ctid of this tuple to point to the new location, and
426  * insert it right away.
427  */
428  new_tuple->t_data->t_ctid = mapping->new_tid;
429 
430  /* We don't need the mapping entry anymore */
431  hash_search(state->rs_old_new_tid_map, &hashkey,
432  HASH_REMOVE, &found);
433  Assert(found);
434  }
435  else
436  {
437  /*
438  * We haven't seen the tuple t_ctid points to yet. Stash this
439  * tuple into unresolved_tups to be written later.
440  */
441  UnresolvedTup unresolved;
442 
443  unresolved = hash_search(state->rs_unresolved_tups, &hashkey,
444  HASH_ENTER, &found);
445  Assert(!found);
446 
447  unresolved->old_tid = old_tuple->t_self;
448  unresolved->tuple = heap_copytuple(new_tuple);
449 
450  /*
451  * We can't do anything more now, since we don't know where the
452  * tuple will be written.
453  */
454  MemoryContextSwitchTo(old_cxt);
455  return;
456  }
457  }
458 
459  /*
460  * Now we will write the tuple, and then check to see if it is the B tuple
461  * in any new or known pair. When we resolve a known pair, we will be
462  * able to write that pair's A tuple, and then we have to check if it
463  * resolves some other pair. Hence, we need a loop here.
464  */
465  old_tid = old_tuple->t_self;
466  free_new = false;
467 
468  for (;;)
469  {
470  ItemPointerData new_tid;
471 
472  /* Insert the tuple and find out where it's put in new_heap */
473  raw_heap_insert(state, new_tuple);
474  new_tid = new_tuple->t_self;
475 
476  logical_rewrite_heap_tuple(state, old_tid, new_tuple);
477 
478  /*
479  * If the tuple is the updated version of a row, and the prior version
480  * wouldn't be DEAD yet, then we need to either resolve the prior
481  * version (if it's waiting in rs_unresolved_tups), or make an entry
482  * in rs_old_new_tid_map (so we can resolve it when we do see it). The
483  * previous tuple's xmax would equal this one's xmin, so it's
484  * RECENTLY_DEAD if and only if the xmin is not before OldestXmin.
485  */
486  if ((new_tuple->t_data->t_infomask & HEAP_UPDATED) &&
488  state->rs_oldest_xmin))
489  {
490  /*
491  * Okay, this is B in an update pair. See if we've seen A.
492  */
493  UnresolvedTup unresolved;
494 
495  memset(&hashkey, 0, sizeof(hashkey));
496  hashkey.xmin = HeapTupleHeaderGetXmin(new_tuple->t_data);
497  hashkey.tid = old_tid;
498 
499  unresolved = hash_search(state->rs_unresolved_tups, &hashkey,
500  HASH_FIND, NULL);
501 
502  if (unresolved != NULL)
503  {
504  /*
505  * We have seen and memorized the previous tuple already. Now
506  * that we know where we inserted the tuple its t_ctid points
507  * to, fix its t_ctid and insert it to the new heap.
508  */
509  if (free_new)
510  heap_freetuple(new_tuple);
511  new_tuple = unresolved->tuple;
512  free_new = true;
513  old_tid = unresolved->old_tid;
514  new_tuple->t_data->t_ctid = new_tid;
515 
516  /*
517  * We don't need the hash entry anymore, but don't free its
518  * tuple just yet.
519  */
520  hash_search(state->rs_unresolved_tups, &hashkey,
521  HASH_REMOVE, &found);
522  Assert(found);
523 
524  /* loop back to insert the previous tuple in the chain */
525  continue;
526  }
527  else
528  {
529  /*
530  * Remember the new tid of this tuple. We'll use it to set the
531  * ctid when we find the previous tuple in the chain.
532  */
533  OldToNewMapping mapping;
534 
535  mapping = hash_search(state->rs_old_new_tid_map, &hashkey,
536  HASH_ENTER, &found);
537  Assert(!found);
538 
539  mapping->new_tid = new_tid;
540  }
541  }
542 
543  /* Done with this (chain of) tuples, for now */
544  if (free_new)
545  heap_freetuple(new_tuple);
546  break;
547  }
548 
549  MemoryContextSwitchTo(old_cxt);
550 }
551 
552 /*
553  * Register a dead tuple with an ongoing rewrite. Dead tuples are not
554  * copied to the new table, but we still make note of them so that we
555  * can release some resources earlier.
556  *
557  * Returns true if a tuple was removed from the unresolved_tups table.
558  * This indicates that that tuple, previously thought to be "recently dead",
559  * is now known really dead and won't be written to the output.
560  */
561 bool
563 {
564  /*
565  * If we have already seen an earlier tuple in the update chain that
566  * points to this tuple, let's forget about that earlier tuple. It's in
567  * fact dead as well, our simple xmax < OldestXmin test in
568  * HeapTupleSatisfiesVacuum just wasn't enough to detect it. It happens
569  * when xmin of a tuple is greater than xmax, which sounds
570  * counter-intuitive but is perfectly valid.
571  *
572  * We don't bother to try to detect the situation the other way round,
573  * when we encounter the dead tuple first and then the recently dead one
574  * that points to it. If that happens, we'll have some unmatched entries
575  * in the UnresolvedTups hash table at the end. That can happen anyway,
576  * because a vacuum might have removed the dead tuple in the chain before
577  * us.
578  */
579  UnresolvedTup unresolved;
580  TidHashKey hashkey;
581  bool found;
582 
583  memset(&hashkey, 0, sizeof(hashkey));
584  hashkey.xmin = HeapTupleHeaderGetXmin(old_tuple->t_data);
585  hashkey.tid = old_tuple->t_self;
586 
587  unresolved = hash_search(state->rs_unresolved_tups, &hashkey,
588  HASH_FIND, NULL);
589 
590  if (unresolved != NULL)
591  {
592  /* Need to free the contained tuple as well as the hashtable entry */
593  heap_freetuple(unresolved->tuple);
594  hash_search(state->rs_unresolved_tups, &hashkey,
595  HASH_REMOVE, &found);
596  Assert(found);
597  return true;
598  }
599 
600  return false;
601 }
602 
603 /*
604  * Insert a tuple to the new relation. This has to track heap_insert
605  * and its subsidiary functions!
606  *
607  * t_self of the tuple is set to the new TID of the tuple. If t_ctid of the
608  * tuple is invalid on entry, it's replaced with the new TID as well (in
609  * the inserted data only, not in the caller's copy).
610  */
611 static void
613 {
614  Page page = state->rs_buffer;
615  Size pageFreeSpace,
616  saveFreeSpace;
617  Size len;
618  OffsetNumber newoff;
619  HeapTuple heaptup;
620 
621  /*
622  * If the new tuple is too big for storage or contains already toasted
623  * out-of-line attributes from some other relation, invoke the toaster.
624  *
625  * Note: below this point, heaptup is the data we actually intend to store
626  * into the relation; tup is the caller's original untoasted data.
627  */
628  if (state->rs_new_rel->rd_rel->relkind == RELKIND_TOASTVALUE)
629  {
630  /* toast table entries should never be recursively toasted */
632  heaptup = tup;
633  }
634  else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
635  {
637 
638  /*
639  * While rewriting the heap for VACUUM FULL / CLUSTER, make sure data
640  * for the TOAST table are not logically decoded. The main heap is
641  * WAL-logged as XLOG FPI records, which are not logically decoded.
642  */
644 
645  heaptup = heap_toast_insert_or_update(state->rs_new_rel, tup, NULL,
646  options);
647  }
648  else
649  heaptup = tup;
650 
651  len = MAXALIGN(heaptup->t_len); /* be conservative */
652 
653  /*
654  * If we're gonna fail for oversize tuple, do it right away
655  */
656  if (len > MaxHeapTupleSize)
657  ereport(ERROR,
658  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
659  errmsg("row is too big: size %zu, maximum size %zu",
660  len, MaxHeapTupleSize)));
661 
662  /* Compute desired extra freespace due to fillfactor option */
663  saveFreeSpace = RelationGetTargetPageFreeSpace(state->rs_new_rel,
665 
666  /* Now we can check to see if there's enough free space already. */
667  if (state->rs_buffer_valid)
668  {
669  pageFreeSpace = PageGetHeapFreeSpace(page);
670 
671  if (len + saveFreeSpace > pageFreeSpace)
672  {
673  /*
674  * Doesn't fit, so write out the existing page. It always
675  * contains a tuple. Hence, unlike RelationGetBufferForTuple(),
676  * enforce saveFreeSpace unconditionally.
677  */
678 
679  /* XLOG stuff */
680  if (RelationNeedsWAL(state->rs_new_rel))
681  log_newpage(&state->rs_new_rel->rd_locator,
682  MAIN_FORKNUM,
683  state->rs_blockno,
684  page,
685  true);
686 
687  /*
688  * Now write the page. We say skipFsync = true because there's no
689  * need for smgr to schedule an fsync for this write; we'll do it
690  * ourselves in end_heap_rewrite.
691  */
692  PageSetChecksumInplace(page, state->rs_blockno);
693 
695  state->rs_blockno, page, true);
696 
697  state->rs_blockno++;
698  state->rs_buffer_valid = false;
699  }
700  }
701 
702  if (!state->rs_buffer_valid)
703  {
704  /* Initialize a new empty page */
705  PageInit(page, BLCKSZ, 0);
706  state->rs_buffer_valid = true;
707  }
708 
709  /* And now we can insert the tuple into the page */
710  newoff = PageAddItem(page, (Item) heaptup->t_data, heaptup->t_len,
711  InvalidOffsetNumber, false, true);
712  if (newoff == InvalidOffsetNumber)
713  elog(ERROR, "failed to add tuple");
714 
715  /* Update caller's t_self to the actual position where it was stored */
716  ItemPointerSet(&(tup->t_self), state->rs_blockno, newoff);
717 
718  /*
719  * Insert the correct position into CTID of the stored tuple, too, if the
720  * caller didn't supply a valid CTID.
721  */
722  if (!ItemPointerIsValid(&tup->t_data->t_ctid))
723  {
724  ItemId newitemid;
725  HeapTupleHeader onpage_tup;
726 
727  newitemid = PageGetItemId(page, newoff);
728  onpage_tup = (HeapTupleHeader) PageGetItem(page, newitemid);
729 
730  onpage_tup->t_ctid = tup->t_self;
731  }
732 
733  /* If heaptup is a private copy, release it. */
734  if (heaptup != tup)
735  heap_freetuple(heaptup);
736 }
737 
738 /* ------------------------------------------------------------------------
739  * Logical rewrite support
740  *
741  * When doing logical decoding - which relies on using cmin/cmax of catalog
742  * tuples, via xl_heap_new_cid records - heap rewrites have to log enough
743  * information to allow the decoding backend to update its internal mapping
744  * of (relfilelocator,ctid) => (cmin, cmax) to be correct for the rewritten heap.
745  *
746  * For that, every time we find a tuple that's been modified in a catalog
747  * relation within the xmin horizon of any decoding slot, we log a mapping
748  * from the old to the new location.
749  *
750  * To deal with rewrites that abort the filename of a mapping file contains
751  * the xid of the transaction performing the rewrite, which then can be
752  * checked before being read in.
753  *
754  * For efficiency we don't immediately spill every single map mapping for a
755  * row to disk but only do so in batches when we've collected several of them
756  * in memory or when end_heap_rewrite() has been called.
757  *
758  * Crash-Safety: This module diverts from the usual patterns of doing WAL
759  * since it cannot rely on checkpoint flushing out all buffers and thus
760  * waiting for exclusive locks on buffers. Usually the XLogInsert() covering
761  * buffer modifications is performed while the buffer(s) that are being
762  * modified are exclusively locked guaranteeing that both the WAL record and
763  * the modified heap are on either side of the checkpoint. But since the
764  * mapping files we log aren't in shared_buffers that interlock doesn't work.
765  *
766  * Instead we simply write the mapping files out to disk, *before* the
767  * XLogInsert() is performed. That guarantees that either the XLogInsert() is
768  * inserted after the checkpoint's redo pointer or that the checkpoint (via
769  * CheckPointLogicalRewriteHeap()) has flushed the (partial) mapping file to
770  * disk. That leaves the tail end that has not yet been flushed open to
771  * corruption, which is solved by including the current offset in the
772  * xl_heap_rewrite_mapping records and truncating the mapping file to it
773  * during replay. Every time a rewrite is finished all generated mapping files
774  * are synced to disk.
775  *
776  * Note that if we were only concerned about crash safety we wouldn't have to
777  * deal with WAL logging at all - an fsync() at the end of a rewrite would be
778  * sufficient for crash safety. Any mapping that hasn't been safely flushed to
779  * disk has to be by an aborted (explicitly or via a crash) transaction and is
780  * ignored by virtue of the xid in its name being subject to a
781  * TransactionDidCommit() check. But we want to support having standbys via
782  * physical replication, both for availability and to do logical decoding
783  * there.
784  * ------------------------------------------------------------------------
785  */
786 
787 /*
788  * Do preparations for logging logical mappings during a rewrite if
789  * necessary. If we detect that we don't need to log anything we'll prevent
790  * any further action by the various logical rewrite functions.
791  */
792 static void
794 {
795  HASHCTL hash_ctl;
796  TransactionId logical_xmin;
797 
798  /*
799  * We only need to persist these mappings if the rewritten table can be
800  * accessed during logical decoding, if not, we can skip doing any
801  * additional work.
802  */
803  state->rs_logical_rewrite =
805 
806  if (!state->rs_logical_rewrite)
807  return;
808 
809  ProcArrayGetReplicationSlotXmin(NULL, &logical_xmin);
810 
811  /*
812  * If there are no logical slots in progress we don't need to do anything,
813  * there cannot be any remappings for relevant rows yet. The relation's
814  * lock protects us against races.
815  */
816  if (logical_xmin == InvalidTransactionId)
817  {
818  state->rs_logical_rewrite = false;
819  return;
820  }
821 
822  state->rs_logical_xmin = logical_xmin;
823  state->rs_begin_lsn = GetXLogInsertRecPtr();
824  state->rs_num_rewrite_mappings = 0;
825 
826  hash_ctl.keysize = sizeof(TransactionId);
827  hash_ctl.entrysize = sizeof(RewriteMappingFile);
828  hash_ctl.hcxt = state->rs_cxt;
829 
830  state->rs_logical_mappings =
831  hash_create("Logical rewrite mapping",
832  128, /* arbitrary initial size */
833  &hash_ctl,
835 }
836 
837 /*
838  * Flush all logical in-memory mappings to disk, but don't fsync them yet.
839  */
840 static void
842 {
843  HASH_SEQ_STATUS seq_status;
844  RewriteMappingFile *src;
845  dlist_mutable_iter iter;
846 
847  Assert(state->rs_logical_rewrite);
848 
849  /* no logical rewrite in progress, no need to iterate over mappings */
850  if (state->rs_num_rewrite_mappings == 0)
851  return;
852 
853  elog(DEBUG1, "flushing %u logical rewrite mapping entries",
854  state->rs_num_rewrite_mappings);
855 
856  hash_seq_init(&seq_status, state->rs_logical_mappings);
857  while ((src = (RewriteMappingFile *) hash_seq_search(&seq_status)) != NULL)
858  {
859  char *waldata;
860  char *waldata_start;
862  Oid dboid;
863  uint32 len;
864  int written;
865  uint32 num_mappings = dclist_count(&src->mappings);
866 
867  /* this file hasn't got any new mappings */
868  if (num_mappings == 0)
869  continue;
870 
871  if (state->rs_old_rel->rd_rel->relisshared)
872  dboid = InvalidOid;
873  else
874  dboid = MyDatabaseId;
875 
876  xlrec.num_mappings = num_mappings;
877  xlrec.mapped_rel = RelationGetRelid(state->rs_old_rel);
878  xlrec.mapped_xid = src->xid;
879  xlrec.mapped_db = dboid;
880  xlrec.offset = src->off;
881  xlrec.start_lsn = state->rs_begin_lsn;
882 
883  /* write all mappings consecutively */
884  len = num_mappings * sizeof(LogicalRewriteMappingData);
885  waldata_start = waldata = palloc(len);
886 
887  /*
888  * collect data we need to write out, but don't modify ondisk data yet
889  */
890  dclist_foreach_modify(iter, &src->mappings)
891  {
893 
894  pmap = dclist_container(RewriteMappingDataEntry, node, iter.cur);
895 
896  memcpy(waldata, &pmap->map, sizeof(pmap->map));
897  waldata += sizeof(pmap->map);
898 
899  /* remove from the list and free */
900  dclist_delete_from(&src->mappings, &pmap->node);
901  pfree(pmap);
902 
903  /* update bookkeeping */
904  state->rs_num_rewrite_mappings--;
905  }
906 
907  Assert(dclist_count(&src->mappings) == 0);
908  Assert(waldata == waldata_start + len);
909 
910  /*
911  * Note that we deviate from the usual WAL coding practices here,
912  * check the above "Logical rewrite support" comment for reasoning.
913  */
914  written = FileWrite(src->vfd, waldata_start, len, src->off,
915  WAIT_EVENT_LOGICAL_REWRITE_WRITE);
916  if (written != len)
917  ereport(ERROR,
919  errmsg("could not write to file \"%s\", wrote %d of %d: %m", src->path,
920  written, len)));
921  src->off += len;
922 
923  XLogBeginInsert();
924  XLogRegisterData((char *) (&xlrec), sizeof(xlrec));
925  XLogRegisterData(waldata_start, len);
926 
927  /* write xlog record */
928  XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_REWRITE);
929 
930  pfree(waldata_start);
931  }
932  Assert(state->rs_num_rewrite_mappings == 0);
933 }
934 
935 /*
936  * Logical remapping part of end_heap_rewrite().
937  */
938 static void
940 {
941  HASH_SEQ_STATUS seq_status;
942  RewriteMappingFile *src;
943 
944  /* done, no logical rewrite in progress */
945  if (!state->rs_logical_rewrite)
946  return;
947 
948  /* writeout remaining in-memory entries */
949  if (state->rs_num_rewrite_mappings > 0)
951 
952  /* Iterate over all mappings we have written and fsync the files. */
953  hash_seq_init(&seq_status, state->rs_logical_mappings);
954  while ((src = (RewriteMappingFile *) hash_seq_search(&seq_status)) != NULL)
955  {
956  if (FileSync(src->vfd, WAIT_EVENT_LOGICAL_REWRITE_SYNC) != 0)
959  errmsg("could not fsync file \"%s\": %m", src->path)));
960  FileClose(src->vfd);
961  }
962  /* memory context cleanup will deal with the rest */
963 }
964 
965 /*
966  * Log a single (old->new) mapping for 'xid'.
967  */
968 static void
971 {
972  RewriteMappingFile *src;
974  Oid relid;
975  bool found;
976 
977  relid = RelationGetRelid(state->rs_old_rel);
978 
979  /* look for existing mappings for this 'mapped' xid */
980  src = hash_search(state->rs_logical_mappings, &xid,
981  HASH_ENTER, &found);
982 
983  /*
984  * We haven't yet had the need to map anything for this xid, create
985  * per-xid data structures.
986  */
987  if (!found)
988  {
989  char path[MAXPGPATH];
990  Oid dboid;
991 
992  if (state->rs_old_rel->rd_rel->relisshared)
993  dboid = InvalidOid;
994  else
995  dboid = MyDatabaseId;
996 
997  snprintf(path, MAXPGPATH,
998  "pg_logical/mappings/" LOGICAL_REWRITE_FORMAT,
999  dboid, relid,
1000  LSN_FORMAT_ARGS(state->rs_begin_lsn),
1001  xid, GetCurrentTransactionId());
1002 
1003  dclist_init(&src->mappings);
1004  src->off = 0;
1005  memcpy(src->path, path, sizeof(path));
1006  src->vfd = PathNameOpenFile(path,
1007  O_CREAT | O_EXCL | O_WRONLY | PG_BINARY);
1008  if (src->vfd < 0)
1009  ereport(ERROR,
1011  errmsg("could not create file \"%s\": %m", path)));
1012  }
1013 
1014  pmap = MemoryContextAlloc(state->rs_cxt,
1015  sizeof(RewriteMappingDataEntry));
1016  memcpy(&pmap->map, map, sizeof(LogicalRewriteMappingData));
1017  dclist_push_tail(&src->mappings, &pmap->node);
1018  state->rs_num_rewrite_mappings++;
1019 
1020  /*
1021  * Write out buffer every time we've too many in-memory entries across all
1022  * mapping files.
1023  */
1024  if (state->rs_num_rewrite_mappings >= 1000 /* arbitrary number */ )
1026 }
1027 
1028 /*
1029  * Perform logical remapping for a tuple that's mapped from old_tid to
1030  * new_tuple->t_self by rewrite_heap_tuple() if necessary for the tuple.
1031  */
1032 static void
1034  HeapTuple new_tuple)
1035 {
1036  ItemPointerData new_tid = new_tuple->t_self;
1037  TransactionId cutoff = state->rs_logical_xmin;
1038  TransactionId xmin;
1039  TransactionId xmax;
1040  bool do_log_xmin = false;
1041  bool do_log_xmax = false;
1043 
1044  /* no logical rewrite in progress, we don't need to log anything */
1045  if (!state->rs_logical_rewrite)
1046  return;
1047 
1048  xmin = HeapTupleHeaderGetXmin(new_tuple->t_data);
1049  /* use *GetUpdateXid to correctly deal with multixacts */
1050  xmax = HeapTupleHeaderGetUpdateXid(new_tuple->t_data);
1051 
1052  /*
1053  * Log the mapping iff the tuple has been created recently.
1054  */
1055  if (TransactionIdIsNormal(xmin) && !TransactionIdPrecedes(xmin, cutoff))
1056  do_log_xmin = true;
1057 
1058  if (!TransactionIdIsNormal(xmax))
1059  {
1060  /*
1061  * no xmax is set, can't have any permanent ones, so this check is
1062  * sufficient
1063  */
1064  }
1065  else if (HEAP_XMAX_IS_LOCKED_ONLY(new_tuple->t_data->t_infomask))
1066  {
1067  /* only locked, we don't care */
1068  }
1069  else if (!TransactionIdPrecedes(xmax, cutoff))
1070  {
1071  /* tuple has been deleted recently, log */
1072  do_log_xmax = true;
1073  }
1074 
1075  /* if neither needs to be logged, we're done */
1076  if (!do_log_xmin && !do_log_xmax)
1077  return;
1078 
1079  /* fill out mapping information */
1080  map.old_locator = state->rs_old_rel->rd_locator;
1081  map.old_tid = old_tid;
1082  map.new_locator = state->rs_new_rel->rd_locator;
1083  map.new_tid = new_tid;
1084 
1085  /* ---
1086  * Now persist the mapping for the individual xids that are affected. We
1087  * need to log for both xmin and xmax if they aren't the same transaction
1088  * since the mapping files are per "affected" xid.
1089  * We don't muster all that much effort detecting whether xmin and xmax
1090  * are actually the same transaction, we just check whether the xid is the
1091  * same disregarding subtransactions. Logging too much is relatively
1092  * harmless and we could never do the check fully since subtransaction
1093  * data is thrown away during restarts.
1094  * ---
1095  */
1096  if (do_log_xmin)
1097  logical_rewrite_log_mapping(state, xmin, &map);
1098  /* separately log mapping for xmax unless it'd be redundant */
1099  if (do_log_xmax && !TransactionIdEquals(xmin, xmax))
1100  logical_rewrite_log_mapping(state, xmax, &map);
1101 }
1102 
1103 /*
1104  * Replay XLOG_HEAP2_REWRITE records
1105  */
1106 void
1108 {
1109  char path[MAXPGPATH];
1110  int fd;
1111  xl_heap_rewrite_mapping *xlrec;
1112  uint32 len;
1113  char *data;
1114 
1115  xlrec = (xl_heap_rewrite_mapping *) XLogRecGetData(r);
1116 
1117  snprintf(path, MAXPGPATH,
1118  "pg_logical/mappings/" LOGICAL_REWRITE_FORMAT,
1119  xlrec->mapped_db, xlrec->mapped_rel,
1120  LSN_FORMAT_ARGS(xlrec->start_lsn),
1121  xlrec->mapped_xid, XLogRecGetXid(r));
1122 
1123  fd = OpenTransientFile(path,
1124  O_CREAT | O_WRONLY | PG_BINARY);
1125  if (fd < 0)
1126  ereport(ERROR,
1128  errmsg("could not create file \"%s\": %m", path)));
1129 
1130  /*
1131  * Truncate all data that's not guaranteed to have been safely fsynced (by
1132  * previous record or by the last checkpoint).
1133  */
1134  pgstat_report_wait_start(WAIT_EVENT_LOGICAL_REWRITE_TRUNCATE);
1135  if (ftruncate(fd, xlrec->offset) != 0)
1136  ereport(ERROR,
1138  errmsg("could not truncate file \"%s\" to %u: %m",
1139  path, (uint32) xlrec->offset)));
1141 
1142  data = XLogRecGetData(r) + sizeof(*xlrec);
1143 
1144  len = xlrec->num_mappings * sizeof(LogicalRewriteMappingData);
1145 
1146  /* write out tail end of mapping file (again) */
1147  errno = 0;
1148  pgstat_report_wait_start(WAIT_EVENT_LOGICAL_REWRITE_MAPPING_WRITE);
1149  if (pg_pwrite(fd, data, len, xlrec->offset) != len)
1150  {
1151  /* if write didn't set errno, assume problem is no disk space */
1152  if (errno == 0)
1153  errno = ENOSPC;
1154  ereport(ERROR,
1156  errmsg("could not write to file \"%s\": %m", path)));
1157  }
1159 
1160  /*
1161  * Now fsync all previously written data. We could improve things and only
1162  * do this for the last write to a file, but the required bookkeeping
1163  * doesn't seem worth the trouble.
1164  */
1165  pgstat_report_wait_start(WAIT_EVENT_LOGICAL_REWRITE_MAPPING_SYNC);
1166  if (pg_fsync(fd) != 0)
1169  errmsg("could not fsync file \"%s\": %m", path)));
1171 
1172  if (CloseTransientFile(fd) != 0)
1173  ereport(ERROR,
1175  errmsg("could not close file \"%s\": %m", path)));
1176 }
1177 
1178 /* ---
1179  * Perform a checkpoint for logical rewrite mappings
1180  *
1181  * This serves two tasks:
1182  * 1) Remove all mappings not needed anymore based on the logical restart LSN
1183  * 2) Flush all remaining mappings to disk, so that replay after a checkpoint
1184  * only has to deal with the parts of a mapping that have been written out
1185  * after the checkpoint started.
1186  * ---
1187  */
1188 void
1190 {
1191  XLogRecPtr cutoff;
1192  XLogRecPtr redo;
1193  DIR *mappings_dir;
1194  struct dirent *mapping_de;
1195  char path[MAXPGPATH + 20];
1196 
1197  /*
1198  * We start of with a minimum of the last redo pointer. No new decoding
1199  * slot will start before that, so that's a safe upper bound for removal.
1200  */
1201  redo = GetRedoRecPtr();
1202 
1203  /* now check for the restart ptrs from existing slots */
1205 
1206  /* don't start earlier than the restart lsn */
1207  if (cutoff != InvalidXLogRecPtr && redo < cutoff)
1208  cutoff = redo;
1209 
1210  mappings_dir = AllocateDir("pg_logical/mappings");
1211  while ((mapping_de = ReadDir(mappings_dir, "pg_logical/mappings")) != NULL)
1212  {
1213  Oid dboid;
1214  Oid relid;
1215  XLogRecPtr lsn;
1216  TransactionId rewrite_xid;
1217  TransactionId create_xid;
1218  uint32 hi,
1219  lo;
1220  PGFileType de_type;
1221 
1222  if (strcmp(mapping_de->d_name, ".") == 0 ||
1223  strcmp(mapping_de->d_name, "..") == 0)
1224  continue;
1225 
1226  snprintf(path, sizeof(path), "pg_logical/mappings/%s", mapping_de->d_name);
1227  de_type = get_dirent_type(path, mapping_de, false, DEBUG1);
1228 
1229  if (de_type != PGFILETYPE_ERROR && de_type != PGFILETYPE_REG)
1230  continue;
1231 
1232  /* Skip over files that cannot be ours. */
1233  if (strncmp(mapping_de->d_name, "map-", 4) != 0)
1234  continue;
1235 
1236  if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
1237  &dboid, &relid, &hi, &lo, &rewrite_xid, &create_xid) != 6)
1238  elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
1239 
1240  lsn = ((uint64) hi) << 32 | lo;
1241 
1242  if (lsn < cutoff || cutoff == InvalidXLogRecPtr)
1243  {
1244  elog(DEBUG1, "removing logical rewrite file \"%s\"", path);
1245  if (unlink(path) < 0)
1246  ereport(ERROR,
1248  errmsg("could not remove file \"%s\": %m", path)));
1249  }
1250  else
1251  {
1252  /* on some operating systems fsyncing a file requires O_RDWR */
1253  int fd = OpenTransientFile(path, O_RDWR | PG_BINARY);
1254 
1255  /*
1256  * The file cannot vanish due to concurrency since this function
1257  * is the only one removing logical mappings and only one
1258  * checkpoint can be in progress at a time.
1259  */
1260  if (fd < 0)
1261  ereport(ERROR,
1263  errmsg("could not open file \"%s\": %m", path)));
1264 
1265  /*
1266  * We could try to avoid fsyncing files that either haven't
1267  * changed or have only been created since the checkpoint's start,
1268  * but it's currently not deemed worth the effort.
1269  */
1270  pgstat_report_wait_start(WAIT_EVENT_LOGICAL_REWRITE_CHECKPOINT_SYNC);
1271  if (pg_fsync(fd) != 0)
1274  errmsg("could not fsync file \"%s\": %m", path)));
1276 
1277  if (CloseTransientFile(fd) != 0)
1278  ereport(ERROR,
1280  errmsg("could not close file \"%s\": %m", path)));
1281  }
1282  }
1283  FreeDir(mappings_dir);
1284 
1285  /* persist directory entries to disk */
1286  fsync_fname("pg_logical/mappings", true);
1287 }
uint32 BlockNumber
Definition: block.h:31
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:227
Size PageGetHeapFreeSpace(Page page)
Definition: bufpage.c:991
void PageSetChecksumInplace(Page page, BlockNumber blkno)
Definition: bufpage.c:1542
void PageInit(Page page, Size pageSize, Size specialSize)
Definition: bufpage.c:42
Pointer Page
Definition: bufpage.h:78
static Item PageGetItem(Page page, ItemId itemId)
Definition: bufpage.h:351
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:240
#define PageAddItem(page, item, size, offsetNumber, overwrite, is_heap)
Definition: bufpage.h:468
unsigned int uint32
Definition: c.h:495
#define MAXALIGN(LEN)
Definition: c.h:800
#define PG_BINARY
Definition: c.h:1283
TransactionId MultiXactId
Definition: c.h:651
uint32 TransactionId
Definition: c.h:641
size_t Size
Definition: c.h:594
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:953
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:350
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1431
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1421
int errcode_for_file_access(void)
Definition: elog.c:881
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define DEBUG1
Definition: elog.h:30
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2854
int FreeDir(DIR *dir)
Definition: fd.c:2906
int FileSync(File file, uint32 wait_event_info)
Definition: fd.c:2242
int CloseTransientFile(int fd)
Definition: fd.c:2754
void FileClose(File file)
Definition: fd.c:1930
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:708
int data_sync_elevel(int elevel)
Definition: fd.c:3881
File PathNameOpenFile(const char *fileName, int fileFlags)
Definition: fd.c:1527
int FileWrite(File file, const void *buffer, size_t amount, off_t offset, uint32 wait_event_info)
Definition: fd.c:2144
int pg_fsync(int fd)
Definition: fd.c:361
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2578
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2788
PGFileType get_dirent_type(const char *path, const struct dirent *de, bool look_through_symlinks, int elevel)
Definition: file_utils.c:525
PGFileType
Definition: file_utils.h:19
@ PGFILETYPE_REG
Definition: file_utils.h:22
@ PGFILETYPE_ERROR
Definition: file_utils.h:20
Oid MyDatabaseId
Definition: globals.c:89
bool heap_freeze_tuple(HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId FreezeLimit, TransactionId MultiXactCutoff)
Definition: heapam.c:6915
#define HEAP_INSERT_SKIP_FSM
Definition: heapam.h:34
#define HEAP_INSERT_NO_LOGICAL
Definition: heapam.h:36
bool HeapTupleHeaderIsOnlyLocked(HeapTupleHeader tuple)
#define XLOG_HEAP2_REWRITE
Definition: heapam_xlog.h:53
HeapTuple heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup, int options)
Definition: heaptoast.c:96
#define TOAST_TUPLE_THRESHOLD
Definition: heaptoast.h:48
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:768
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1426
@ HASH_FIND
Definition: hsearch.h:113
@ HASH_REMOVE
Definition: hsearch.h:115
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define HEAP_XMAX_IS_LOCKED_ONLY(infomask)
Definition: htup_details.h:227
#define HeapTupleHeaderIndicatesMovedPartitions(tup)
Definition: htup_details.h:444
#define HEAP2_XACT_MASK
Definition: htup_details.h:279
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:309
#define HeapTupleHasExternal(tuple)
Definition: htup_details.h:671
#define HEAP_XACT_MASK
Definition: htup_details.h:215
#define HEAP_XMAX_INVALID
Definition: htup_details.h:208
#define HEAP_UPDATED
Definition: htup_details.h:210
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:361
#define MaxHeapTupleSize
Definition: htup_details.h:558
#define dclist_container(type, membername, ptr)
Definition: ilist.h:947
static void dclist_push_tail(dclist_head *head, dlist_node *node)
Definition: ilist.h:709
static uint32 dclist_count(const dclist_head *head)
Definition: ilist.h:932
static void dclist_delete_from(dclist_head *head, dlist_node *node)
Definition: ilist.h:763
static void dclist_init(dclist_head *head)
Definition: ilist.h:671
#define dclist_foreach_modify(iter, lhead)
Definition: ilist.h:973
Pointer Item
Definition: item.h:17
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:35
static void ItemPointerSet(ItemPointerData *pointer, BlockNumber blockNumber, OffsetNumber offNum)
Definition: itemptr.h:135
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition: itemptr.h:184
static bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition: itemptr.h:83
Assert(fmt[strlen(fmt) - 1] !='\n')
void pfree(void *pointer)
Definition: mcxt.c:1456
void * palloc0(Size size)
Definition: mcxt.c:1257
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1021
void * palloc_aligned(Size size, Size alignto, int flags)
Definition: mcxt.c:1446
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:403
void * palloc(Size size)
Definition: mcxt.c:1226
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
#define InvalidOffsetNumber
Definition: off.h:26
uint16 OffsetNumber
Definition: off.h:24
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
#define MAXPGPATH
#define PG_IO_ALIGN_SIZE
const void size_t len
const void * data
#define pg_pwrite
Definition: port.h:226
#define snprintf
Definition: port.h:238
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void ProcArrayGetReplicationSlotXmin(TransactionId *xmin, TransactionId *catalog_xmin)
Definition: procarray.c:3872
#define RelationGetRelid(relation)
Definition: rel.h:504
#define RelationGetTargetPageFreeSpace(relation, defaultff)
Definition: rel.h:377
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:572
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition: rel.h:685
#define RelationNeedsWAL(relation)
Definition: rel.h:629
#define HEAP_DEFAULT_FILLFACTOR
Definition: rel.h:348
@ MAIN_FORKNUM
Definition: relpath.h:50
struct RewriteMappingDataEntry RewriteMappingDataEntry
static void raw_heap_insert(RewriteState state, HeapTuple tup)
Definition: rewriteheap.c:612
void end_heap_rewrite(RewriteState state)
Definition: rewriteheap.c:299
bool rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
Definition: rewriteheap.c:562
UnresolvedTupData * UnresolvedTup
Definition: rewriteheap.c:179
RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap, TransactionId oldest_xmin, TransactionId freeze_xid, MultiXactId cutoff_multi)
Definition: rewriteheap.c:236
static void logical_rewrite_heap_tuple(RewriteState state, ItemPointerData old_tid, HeapTuple new_tuple)
Definition: rewriteheap.c:1033
static void logical_heap_rewrite_flush_mappings(RewriteState state)
Definition: rewriteheap.c:841
void heap_xlog_logical_rewrite(XLogReaderState *r)
Definition: rewriteheap.c:1107
static void logical_begin_heap_rewrite(RewriteState state)
Definition: rewriteheap.c:793
void CheckPointLogicalRewriteHeap(void)
Definition: rewriteheap.c:1189
struct RewriteMappingFile RewriteMappingFile
static void logical_end_heap_rewrite(RewriteState state)
Definition: rewriteheap.c:939
OldToNewMappingData * OldToNewMapping
Definition: rewriteheap.c:187
struct RewriteStateData RewriteStateData
void rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple, HeapTuple new_tuple)
Definition: rewriteheap.c:360
static void logical_rewrite_log_mapping(RewriteState state, TransactionId xid, LogicalRewriteMappingData *map)
Definition: rewriteheap.c:969
#define LOGICAL_REWRITE_FORMAT
Definition: rewriteheap.h:54
struct LogicalRewriteMappingData LogicalRewriteMappingData
XLogRecPtr ReplicationSlotsComputeLogicalRestartLSN(void)
Definition: slot.c:942
void smgrimmedsync(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:721
void smgrextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, const void *buffer, bool skipFsync)
Definition: smgr.c:498
Definition: dirent.c:26
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
Definition: dynahash.c:220
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
union HeapTupleHeaderData::@45 t_choice
ItemPointerData t_ctid
Definition: htup_details.h:161
HeapTupleFields t_heap
Definition: htup_details.h:157
ItemPointerData new_tid
Definition: rewriteheap.h:40
RelFileLocator old_locator
Definition: rewriteheap.h:37
ItemPointerData old_tid
Definition: rewriteheap.h:39
RelFileLocator new_locator
Definition: rewriteheap.h:38
ItemPointerData new_tid
Definition: rewriteheap.c:184
LogicalRewriteMappingData map
Definition: rewriteheap.c:208
char path[MAXPGPATH]
Definition: rewriteheap.c:199
TransactionId xid
Definition: rewriteheap.c:195
dclist_head mappings
Definition: rewriteheap.c:198
TransactionId rs_freeze_xid
Definition: rewriteheap.c:142
MemoryContext rs_cxt
Definition: rewriteheap.c:148
TransactionId rs_oldest_xmin
Definition: rewriteheap.c:140
HTAB * rs_logical_mappings
Definition: rewriteheap.c:153
Relation rs_new_rel
Definition: rewriteheap.c:135
HTAB * rs_unresolved_tups
Definition: rewriteheap.c:151
uint32 rs_num_rewrite_mappings
Definition: rewriteheap.c:154
Relation rs_old_rel
Definition: rewriteheap.c:134
TransactionId rs_logical_xmin
Definition: rewriteheap.c:144
HTAB * rs_old_new_tid_map
Definition: rewriteheap.c:152
XLogRecPtr rs_begin_lsn
Definition: rewriteheap.c:150
BlockNumber rs_blockno
Definition: rewriteheap.c:137
MultiXactId rs_cutoff_multi
Definition: rewriteheap.c:146
TransactionId xmin
Definition: rewriteheap.c:165
ItemPointerData tid
Definition: rewriteheap.c:166
TidHashKey key
Definition: rewriteheap.c:174
ItemPointerData old_tid
Definition: rewriteheap.c:175
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
dlist_node * cur
Definition: ilist.h:200
Definition: regguts.h:323
TransactionId mapped_xid
Definition: heapam_xlog.h:396
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
#define InvalidTransactionId
Definition: transam.h:31
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:88
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104
#define ftruncate(a, b)
Definition: win32_port.h:82
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:445
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:6051
XLogRecPtr GetXLogInsertRecPtr(void)
Definition: xlog.c:8923
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:351
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:461
XLogRecPtr log_newpage(RelFileLocator *rlocator, ForkNumber forknum, BlockNumber blkno, Page page, bool page_std)
Definition: xloginsert.c:1130
void XLogBeginInsert(void)
Definition: xloginsert.c:150
#define XLogRecGetData(decoder)
Definition: xlogreader.h:415
#define XLogRecGetXid(decoder)
Definition: xlogreader.h:412