PostgreSQL Source Code  git master
logical.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  * logical.c
3  * PostgreSQL logical decoding coordination
4  *
5  * Copyright (c) 2012-2024, PostgreSQL Global Development Group
6  *
7  * IDENTIFICATION
8  * src/backend/replication/logical/logical.c
9  *
10  * NOTES
11  * This file coordinates interaction between the various modules that
12  * together provide logical decoding, primarily by providing so
13  * called LogicalDecodingContexts. The goal is to encapsulate most of the
14  * internal complexity for consumers of logical decoding, so they can
15  * create and consume a changestream with a low amount of code. Builtin
16  * consumers are the walsender and SQL SRF interface, but it's possible to
17  * add further ones without changing core code, e.g. to consume changes in
18  * a bgworker.
19  *
20  * The idea is that a consumer provides three callbacks, one to read WAL,
21  * one to prepare a data write, and a final one for actually writing since
22  * their implementation depends on the type of consumer. Check
23  * logicalfuncs.c for an example implementation of a fairly simple consumer
24  * and an implementation of a WAL reading callback that's suitable for
25  * simple consumers.
26  *-------------------------------------------------------------------------
27  */
28 
29 #include "postgres.h"
30 
31 #include "access/xact.h"
32 #include "access/xlogutils.h"
33 #include "fmgr.h"
34 #include "miscadmin.h"
35 #include "pgstat.h"
36 #include "replication/decode.h"
37 #include "replication/logical.h"
39 #include "replication/slotsync.h"
40 #include "replication/snapbuild.h"
41 #include "storage/proc.h"
42 #include "storage/procarray.h"
43 #include "utils/builtins.h"
44 #include "utils/inval.h"
45 #include "utils/memutils.h"
46 
47 /* data for errcontext callback */
49 {
51  const char *callback_name;
54 
55 /* wrappers around output plugin callbacks */
56 static void output_plugin_error_callback(void *arg);
58  bool is_init);
60 static void begin_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn);
61 static void commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
62  XLogRecPtr commit_lsn);
64 static void prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
65  XLogRecPtr prepare_lsn);
67  XLogRecPtr commit_lsn);
69  XLogRecPtr prepare_end_lsn, TimestampTz prepare_time);
70 static void change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
71  Relation relation, ReorderBufferChange *change);
72 static void truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
73  int nrelations, Relation relations[], ReorderBufferChange *change);
74 static void message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
75  XLogRecPtr message_lsn, bool transactional,
76  const char *prefix, Size message_size, const char *message);
77 
78 /* streaming callbacks */
80  XLogRecPtr first_lsn);
82  XLogRecPtr last_lsn);
84  XLogRecPtr abort_lsn);
86  XLogRecPtr prepare_lsn);
88  XLogRecPtr commit_lsn);
90  Relation relation, ReorderBufferChange *change);
92  XLogRecPtr message_lsn, bool transactional,
93  const char *prefix, Size message_size, const char *message);
95  int nrelations, Relation relations[], ReorderBufferChange *change);
96 
97 /* callback to update txn's progress */
99  ReorderBufferTXN *txn,
100  XLogRecPtr lsn);
101 
102 static void LoadOutputPlugin(OutputPluginCallbacks *callbacks, const char *plugin);
103 
104 /*
105  * Make sure the current settings & environment are capable of doing logical
106  * decoding.
107  */
108 void
110 {
112 
113  /*
114  * NB: Adding a new requirement likely means that RestoreSlotFromDisk()
115  * needs the same check.
116  */
117 
119  ereport(ERROR,
120  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
121  errmsg("logical decoding requires wal_level >= logical")));
122 
123  if (MyDatabaseId == InvalidOid)
124  ereport(ERROR,
125  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
126  errmsg("logical decoding requires a database connection")));
127 
128  if (RecoveryInProgress())
129  {
130  /*
131  * This check may have race conditions, but whenever
132  * XLOG_PARAMETER_CHANGE indicates that wal_level has changed, we
133  * verify that there are no existing logical replication slots. And to
134  * avoid races around creating a new slot,
135  * CheckLogicalDecodingRequirements() is called once before creating
136  * the slot, and once when logical decoding is initially starting up.
137  */
139  ereport(ERROR,
140  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
141  errmsg("logical decoding on standby requires wal_level >= logical on the primary")));
142  }
143 }
144 
145 /*
146  * Helper function for CreateInitDecodingContext() and
147  * CreateDecodingContext() performing common tasks.
148  */
149 static LogicalDecodingContext *
150 StartupDecodingContext(List *output_plugin_options,
151  XLogRecPtr start_lsn,
152  TransactionId xmin_horizon,
153  bool need_full_snapshot,
154  bool fast_forward,
155  XLogReaderRoutine *xl_routine,
159 {
160  ReplicationSlot *slot;
162  old_context;
164 
165  /* shorter lines... */
166  slot = MyReplicationSlot;
167 
169  "Logical decoding context",
171  old_context = MemoryContextSwitchTo(context);
172  ctx = palloc0(sizeof(LogicalDecodingContext));
173 
174  ctx->context = context;
175 
176  /*
177  * (re-)load output plugins, so we detect a bad (removed) output plugin
178  * now.
179  */
180  if (!fast_forward)
182 
183  /*
184  * Now that the slot's xmin has been set, we can announce ourselves as a
185  * logical decoding backend which doesn't need to be checked individually
186  * when computing the xmin horizon because the xmin is enforced via
187  * replication slots.
188  *
189  * We can only do so if we're outside of a transaction (i.e. the case when
190  * streaming changes via walsender), otherwise an already setup
191  * snapshot/xid would end up being ignored. That's not a particularly
192  * bothersome restriction since the SQL interface can't be used for
193  * streaming anyway.
194  */
196  {
197  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
200  LWLockRelease(ProcArrayLock);
201  }
202 
203  ctx->slot = slot;
204 
205  ctx->reader = XLogReaderAllocate(wal_segment_size, NULL, xl_routine, ctx);
206  if (!ctx->reader)
207  ereport(ERROR,
208  (errcode(ERRCODE_OUT_OF_MEMORY),
209  errmsg("out of memory"),
210  errdetail("Failed while allocating a WAL reading processor.")));
211 
213  ctx->snapshot_builder =
214  AllocateSnapshotBuilder(ctx->reorder, xmin_horizon, start_lsn,
215  need_full_snapshot, slot->data.two_phase_at);
216 
217  ctx->reorder->private_data = ctx;
218 
219  /* wrap output plugin callbacks, so we can add error context information */
225 
226  /*
227  * To support streaming, we require start/stop/abort/commit/change
228  * callbacks. The message and truncate callbacks are optional, similar to
229  * regular output plugins. We however enable streaming when at least one
230  * of the methods is enabled so that we can easily identify missing
231  * methods.
232  *
233  * We decide it here, but only check it later in the wrappers.
234  */
235  ctx->streaming = (ctx->callbacks.stream_start_cb != NULL) ||
236  (ctx->callbacks.stream_stop_cb != NULL) ||
237  (ctx->callbacks.stream_abort_cb != NULL) ||
238  (ctx->callbacks.stream_commit_cb != NULL) ||
239  (ctx->callbacks.stream_change_cb != NULL) ||
240  (ctx->callbacks.stream_message_cb != NULL) ||
241  (ctx->callbacks.stream_truncate_cb != NULL);
242 
243  /*
244  * streaming callbacks
245  *
246  * stream_message and stream_truncate callbacks are optional, so we do not
247  * fail with ERROR when missing, but the wrappers simply do nothing. We
248  * must set the ReorderBuffer callbacks to something, otherwise the calls
249  * from there will crash (we don't want to move the checks there).
250  */
259 
260 
261  /*
262  * To support two-phase logical decoding, we require
263  * begin_prepare/prepare/commit-prepare/abort-prepare callbacks. The
264  * filter_prepare callback is optional. We however enable two-phase
265  * logical decoding when at least one of the methods is enabled so that we
266  * can easily identify missing methods.
267  *
268  * We decide it here, but only check it later in the wrappers.
269  */
270  ctx->twophase = (ctx->callbacks.begin_prepare_cb != NULL) ||
271  (ctx->callbacks.prepare_cb != NULL) ||
272  (ctx->callbacks.commit_prepared_cb != NULL) ||
273  (ctx->callbacks.rollback_prepared_cb != NULL) ||
274  (ctx->callbacks.stream_prepare_cb != NULL) ||
275  (ctx->callbacks.filter_prepare_cb != NULL);
276 
277  /*
278  * Callback to support decoding at prepare time.
279  */
284 
285  /*
286  * Callback to support updating progress during sending data of a
287  * transaction (and its subtransactions) to the output plugin.
288  */
290 
291  ctx->out = makeStringInfo();
292  ctx->prepare_write = prepare_write;
293  ctx->write = do_write;
294  ctx->update_progress = update_progress;
295 
296  ctx->output_plugin_options = output_plugin_options;
297 
298  ctx->fast_forward = fast_forward;
299 
300  MemoryContextSwitchTo(old_context);
301 
302  return ctx;
303 }
304 
305 /*
306  * Create a new decoding context, for a new logical slot.
307  *
308  * plugin -- contains the name of the output plugin
309  * output_plugin_options -- contains options passed to the output plugin
310  * need_full_snapshot -- if true, must obtain a snapshot able to read all
311  * tables; if false, one that can read only catalogs is acceptable.
312  * restart_lsn -- if given as invalid, it's this routine's responsibility to
313  * mark WAL as reserved by setting a convenient restart_lsn for the slot.
314  * Otherwise, we set for decoding to start from the given LSN without
315  * marking WAL reserved beforehand. In that scenario, it's up to the
316  * caller to guarantee that WAL remains available.
317  * xl_routine -- XLogReaderRoutine for underlying XLogReader
318  * prepare_write, do_write, update_progress --
319  * callbacks that perform the use-case dependent, actual, work.
320  *
321  * Needs to be called while in a memory context that's at least as long lived
322  * as the decoding context because further memory contexts will be created
323  * inside it.
324  *
325  * Returns an initialized decoding context after calling the output plugin's
326  * startup function.
327  */
330  List *output_plugin_options,
331  bool need_full_snapshot,
332  XLogRecPtr restart_lsn,
333  XLogReaderRoutine *xl_routine,
337 {
338  TransactionId xmin_horizon = InvalidTransactionId;
339  ReplicationSlot *slot;
340  NameData plugin_name;
342  MemoryContext old_context;
343 
344  /*
345  * On a standby, this check is also required while creating the slot.
346  * Check the comments in the function.
347  */
349 
350  /* shorter lines... */
351  slot = MyReplicationSlot;
352 
353  /* first some sanity checks that are unlikely to be violated */
354  if (slot == NULL)
355  elog(ERROR, "cannot perform logical decoding without an acquired slot");
356 
357  if (plugin == NULL)
358  elog(ERROR, "cannot initialize logical decoding without a specified plugin");
359 
360  /* Make sure the passed slot is suitable. These are user facing errors. */
361  if (SlotIsPhysical(slot))
362  ereport(ERROR,
363  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
364  errmsg("cannot use physical replication slot for logical decoding")));
365 
366  if (slot->data.database != MyDatabaseId)
367  ereport(ERROR,
368  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
369  errmsg("replication slot \"%s\" was not created in this database",
370  NameStr(slot->data.name))));
371 
372  if (IsTransactionState() &&
374  ereport(ERROR,
375  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
376  errmsg("cannot create logical replication slot in transaction that has performed writes")));
377 
378  /*
379  * Register output plugin name with slot. We need the mutex to avoid
380  * concurrent reading of a partially copied string. But we don't want any
381  * complicated code while holding a spinlock, so do namestrcpy() outside.
382  */
383  namestrcpy(&plugin_name, plugin);
384  SpinLockAcquire(&slot->mutex);
385  slot->data.plugin = plugin_name;
386  SpinLockRelease(&slot->mutex);
387 
388  if (XLogRecPtrIsInvalid(restart_lsn))
390  else
391  {
392  SpinLockAcquire(&slot->mutex);
393  slot->data.restart_lsn = restart_lsn;
394  SpinLockRelease(&slot->mutex);
395  }
396 
397  /* ----
398  * This is a bit tricky: We need to determine a safe xmin horizon to start
399  * decoding from, to avoid starting from a running xacts record referring
400  * to xids whose rows have been vacuumed or pruned
401  * already. GetOldestSafeDecodingTransactionId() returns such a value, but
402  * without further interlock its return value might immediately be out of
403  * date.
404  *
405  * So we have to acquire the ProcArrayLock to prevent computation of new
406  * xmin horizons by other backends, get the safe decoding xid, and inform
407  * the slot machinery about the new limit. Once that's done the
408  * ProcArrayLock can be released as the slot machinery now is
409  * protecting against vacuum.
410  *
411  * Note that, temporarily, the data, not just the catalog, xmin has to be
412  * reserved if a data snapshot is to be exported. Otherwise the initial
413  * data snapshot created here is not guaranteed to be valid. After that
414  * the data xmin doesn't need to be managed anymore and the global xmin
415  * should be recomputed. As we are fine with losing the pegged data xmin
416  * after crash - no chance a snapshot would get exported anymore - we can
417  * get away with just setting the slot's
418  * effective_xmin. ReplicationSlotRelease will reset it again.
419  *
420  * ----
421  */
422  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
423 
424  xmin_horizon = GetOldestSafeDecodingTransactionId(!need_full_snapshot);
425 
426  SpinLockAcquire(&slot->mutex);
427  slot->effective_catalog_xmin = xmin_horizon;
428  slot->data.catalog_xmin = xmin_horizon;
429  if (need_full_snapshot)
430  slot->effective_xmin = xmin_horizon;
431  SpinLockRelease(&slot->mutex);
432 
434 
435  LWLockRelease(ProcArrayLock);
436 
439 
440  ctx = StartupDecodingContext(NIL, restart_lsn, xmin_horizon,
441  need_full_snapshot, false,
442  xl_routine, prepare_write, do_write,
443  update_progress);
444 
445  /* call output plugin initialization callback */
446  old_context = MemoryContextSwitchTo(ctx->context);
447  if (ctx->callbacks.startup_cb != NULL)
448  startup_cb_wrapper(ctx, &ctx->options, true);
449  MemoryContextSwitchTo(old_context);
450 
451  /*
452  * We allow decoding of prepared transactions when the two_phase is
453  * enabled at the time of slot creation, or when the two_phase option is
454  * given at the streaming start, provided the plugin supports all the
455  * callbacks for two-phase.
456  */
457  ctx->twophase &= slot->data.two_phase;
458 
460 
461  return ctx;
462 }
463 
464 /*
465  * Create a new decoding context, for a logical slot that has previously been
466  * used already.
467  *
468  * start_lsn
469  * The LSN at which to start decoding. If InvalidXLogRecPtr, restart
470  * from the slot's confirmed_flush; otherwise, start from the specified
471  * location (but move it forwards to confirmed_flush if it's older than
472  * that, see below).
473  *
474  * output_plugin_options
475  * options passed to the output plugin.
476  *
477  * fast_forward
478  * bypass the generation of logical changes.
479  *
480  * xl_routine
481  * XLogReaderRoutine used by underlying xlogreader
482  *
483  * prepare_write, do_write, update_progress
484  * callbacks that have to be filled to perform the use-case dependent,
485  * actual work.
486  *
487  * Needs to be called while in a memory context that's at least as long lived
488  * as the decoding context because further memory contexts will be created
489  * inside it.
490  *
491  * Returns an initialized decoding context after calling the output plugin's
492  * startup function.
493  */
496  List *output_plugin_options,
497  bool fast_forward,
498  XLogReaderRoutine *xl_routine,
502 {
504  ReplicationSlot *slot;
505  MemoryContext old_context;
506 
507  /* shorter lines... */
508  slot = MyReplicationSlot;
509 
510  /* first some sanity checks that are unlikely to be violated */
511  if (slot == NULL)
512  elog(ERROR, "cannot perform logical decoding without an acquired slot");
513 
514  /* make sure the passed slot is suitable, these are user facing errors */
515  if (SlotIsPhysical(slot))
516  ereport(ERROR,
517  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
518  errmsg("cannot use physical replication slot for logical decoding")));
519 
520  /*
521  * We need to access the system tables during decoding to build the
522  * logical changes unless we are in fast_forward mode where no changes are
523  * generated.
524  */
525  if (slot->data.database != MyDatabaseId && !fast_forward)
526  ereport(ERROR,
527  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
528  errmsg("replication slot \"%s\" was not created in this database",
529  NameStr(slot->data.name))));
530 
531  /*
532  * The slots being synced from the primary can't be used for decoding as
533  * they are used after failover. However, we do allow advancing the LSNs
534  * during the synchronization of slots. See update_local_synced_slot.
535  */
537  ereport(ERROR,
538  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
539  errmsg("cannot use replication slot \"%s\" for logical decoding",
540  NameStr(slot->data.name)),
541  errdetail("This slot is being synchronized from the primary server."),
542  errhint("Specify another replication slot."));
543 
544  /*
545  * Check if slot has been invalidated due to max_slot_wal_keep_size. Avoid
546  * "cannot get changes" wording in this errmsg because that'd be
547  * confusingly ambiguous about no changes being available when called from
548  * pg_logical_slot_get_changes_guts().
549  */
551  ereport(ERROR,
552  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
553  errmsg("can no longer get changes from replication slot \"%s\"",
555  errdetail("This slot has been invalidated because it exceeded the maximum reserved size.")));
556 
558  ereport(ERROR,
559  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
560  errmsg("can no longer get changes from replication slot \"%s\"",
562  errdetail("This slot has been invalidated because it was conflicting with recovery.")));
563 
566 
567  if (start_lsn == InvalidXLogRecPtr)
568  {
569  /* continue from last position */
570  start_lsn = slot->data.confirmed_flush;
571  }
572  else if (start_lsn < slot->data.confirmed_flush)
573  {
574  /*
575  * It might seem like we should error out in this case, but it's
576  * pretty common for a client to acknowledge a LSN it doesn't have to
577  * do anything for, and thus didn't store persistently, because the
578  * xlog records didn't result in anything relevant for logical
579  * decoding. Clients have to be able to do that to support synchronous
580  * replication.
581  *
582  * Starting at a different LSN than requested might not catch certain
583  * kinds of client errors; so the client may wish to check that
584  * confirmed_flush_lsn matches its expectations.
585  */
586  elog(LOG, "%X/%X has been already streamed, forwarding to %X/%X",
587  LSN_FORMAT_ARGS(start_lsn),
589 
590  start_lsn = slot->data.confirmed_flush;
591  }
592 
593  ctx = StartupDecodingContext(output_plugin_options,
594  start_lsn, InvalidTransactionId, false,
595  fast_forward, xl_routine, prepare_write,
596  do_write, update_progress);
597 
598  /* call output plugin initialization callback */
599  old_context = MemoryContextSwitchTo(ctx->context);
600  if (ctx->callbacks.startup_cb != NULL)
601  startup_cb_wrapper(ctx, &ctx->options, false);
602  MemoryContextSwitchTo(old_context);
603 
604  /*
605  * We allow decoding of prepared transactions when the two_phase is
606  * enabled at the time of slot creation, or when the two_phase option is
607  * given at the streaming start, provided the plugin supports all the
608  * callbacks for two-phase.
609  */
610  ctx->twophase &= (slot->data.two_phase || ctx->twophase_opt_given);
611 
612  /* Mark slot to allow two_phase decoding if not already marked */
613  if (ctx->twophase && !slot->data.two_phase)
614  {
615  SpinLockAcquire(&slot->mutex);
616  slot->data.two_phase = true;
617  slot->data.two_phase_at = start_lsn;
618  SpinLockRelease(&slot->mutex);
621  SnapBuildSetTwoPhaseAt(ctx->snapshot_builder, start_lsn);
622  }
623 
625 
626  ereport(LOG,
627  (errmsg("starting logical decoding for slot \"%s\"",
628  NameStr(slot->data.name)),
629  errdetail("Streaming transactions committing after %X/%X, reading WAL from %X/%X.",
631  LSN_FORMAT_ARGS(slot->data.restart_lsn))));
632 
633  return ctx;
634 }
635 
636 /*
637  * Returns true if a consistent initial decoding snapshot has been built.
638  */
639 bool
641 {
643 }
644 
645 /*
646  * Read from the decoding slot, until it is ready to start extracting changes.
647  */
648 void
650 {
651  ReplicationSlot *slot = ctx->slot;
652 
653  /* Initialize from where to start reading WAL. */
654  XLogBeginRead(ctx->reader, slot->data.restart_lsn);
655 
656  elog(DEBUG1, "searching for logical decoding starting point, starting at %X/%X",
658 
659  /* Wait for a consistent starting point */
660  for (;;)
661  {
662  XLogRecord *record;
663  char *err = NULL;
664 
665  /* the read_page callback waits for new WAL */
666  record = XLogReadRecord(ctx->reader, &err);
667  if (err)
668  elog(ERROR, "could not find logical decoding starting point: %s", err);
669  if (!record)
670  elog(ERROR, "could not find logical decoding starting point");
671 
673 
674  /* only continue till we found a consistent spot */
675  if (DecodingContextReady(ctx))
676  break;
677 
679  }
680 
681  SpinLockAcquire(&slot->mutex);
682  slot->data.confirmed_flush = ctx->reader->EndRecPtr;
683  if (slot->data.two_phase)
684  slot->data.two_phase_at = ctx->reader->EndRecPtr;
685  SpinLockRelease(&slot->mutex);
686 }
687 
688 /*
689  * Free a previously allocated decoding context, invoking the shutdown
690  * callback if necessary.
691  */
692 void
694 {
695  if (ctx->callbacks.shutdown_cb != NULL)
696  shutdown_cb_wrapper(ctx);
697 
700  XLogReaderFree(ctx->reader);
702 }
703 
704 /*
705  * Prepare a write using the context's output routine.
706  */
707 void
709 {
710  if (!ctx->accept_writes)
711  elog(ERROR, "writes are only accepted in commit, begin and change callbacks");
712 
713  ctx->prepare_write(ctx, ctx->write_location, ctx->write_xid, last_write);
714  ctx->prepared_write = true;
715 }
716 
717 /*
718  * Perform a write using the context's output routine.
719  */
720 void
721 OutputPluginWrite(struct LogicalDecodingContext *ctx, bool last_write)
722 {
723  if (!ctx->prepared_write)
724  elog(ERROR, "OutputPluginPrepareWrite needs to be called before OutputPluginWrite");
725 
726  ctx->write(ctx, ctx->write_location, ctx->write_xid, last_write);
727  ctx->prepared_write = false;
728 }
729 
730 /*
731  * Update progress tracking (if supported).
732  */
733 void
735  bool skipped_xact)
736 {
737  if (!ctx->update_progress)
738  return;
739 
740  ctx->update_progress(ctx, ctx->write_location, ctx->write_xid,
741  skipped_xact);
742 }
743 
744 /*
745  * Load the output plugin, lookup its output plugin init function, and check
746  * that it provides the required callbacks.
747  */
748 static void
750 {
751  LogicalOutputPluginInit plugin_init;
752 
753  plugin_init = (LogicalOutputPluginInit)
754  load_external_function(plugin, "_PG_output_plugin_init", false, NULL);
755 
756  if (plugin_init == NULL)
757  elog(ERROR, "output plugins have to declare the _PG_output_plugin_init symbol");
758 
759  /* ask the output plugin to fill the callback struct */
760  plugin_init(callbacks);
761 
762  if (callbacks->begin_cb == NULL)
763  elog(ERROR, "output plugins have to register a begin callback");
764  if (callbacks->change_cb == NULL)
765  elog(ERROR, "output plugins have to register a change callback");
766  if (callbacks->commit_cb == NULL)
767  elog(ERROR, "output plugins have to register a commit callback");
768 }
769 
770 static void
772 {
774 
775  /* not all callbacks have an associated LSN */
776  if (state->report_location != InvalidXLogRecPtr)
777  errcontext("slot \"%s\", output plugin \"%s\", in the %s callback, associated LSN %X/%X",
778  NameStr(state->ctx->slot->data.name),
779  NameStr(state->ctx->slot->data.plugin),
780  state->callback_name,
781  LSN_FORMAT_ARGS(state->report_location));
782  else
783  errcontext("slot \"%s\", output plugin \"%s\", in the %s callback",
784  NameStr(state->ctx->slot->data.name),
785  NameStr(state->ctx->slot->data.plugin),
786  state->callback_name);
787 }
788 
789 static void
791 {
793  ErrorContextCallback errcallback;
794 
795  Assert(!ctx->fast_forward);
796 
797  /* Push callback + info on the error context stack */
798  state.ctx = ctx;
799  state.callback_name = "startup";
800  state.report_location = InvalidXLogRecPtr;
802  errcallback.arg = (void *) &state;
803  errcallback.previous = error_context_stack;
804  error_context_stack = &errcallback;
805 
806  /* set output state */
807  ctx->accept_writes = false;
808  ctx->end_xact = false;
809 
810  /* do the actual work: call callback */
811  ctx->callbacks.startup_cb(ctx, opt, is_init);
812 
813  /* Pop the error context stack */
814  error_context_stack = errcallback.previous;
815 }
816 
817 static void
819 {
821  ErrorContextCallback errcallback;
822 
823  Assert(!ctx->fast_forward);
824 
825  /* Push callback + info on the error context stack */
826  state.ctx = ctx;
827  state.callback_name = "shutdown";
828  state.report_location = InvalidXLogRecPtr;
830  errcallback.arg = (void *) &state;
831  errcallback.previous = error_context_stack;
832  error_context_stack = &errcallback;
833 
834  /* set output state */
835  ctx->accept_writes = false;
836  ctx->end_xact = false;
837 
838  /* do the actual work: call callback */
839  ctx->callbacks.shutdown_cb(ctx);
840 
841  /* Pop the error context stack */
842  error_context_stack = errcallback.previous;
843 }
844 
845 
846 /*
847  * Callbacks for ReorderBuffer which add in some more information and then call
848  * output_plugin.h plugins.
849  */
850 static void
852 {
853  LogicalDecodingContext *ctx = cache->private_data;
855  ErrorContextCallback errcallback;
856 
857  Assert(!ctx->fast_forward);
858 
859  /* Push callback + info on the error context stack */
860  state.ctx = ctx;
861  state.callback_name = "begin";
862  state.report_location = txn->first_lsn;
864  errcallback.arg = (void *) &state;
865  errcallback.previous = error_context_stack;
866  error_context_stack = &errcallback;
867 
868  /* set output state */
869  ctx->accept_writes = true;
870  ctx->write_xid = txn->xid;
871  ctx->write_location = txn->first_lsn;
872  ctx->end_xact = false;
873 
874  /* do the actual work: call callback */
875  ctx->callbacks.begin_cb(ctx, txn);
876 
877  /* Pop the error context stack */
878  error_context_stack = errcallback.previous;
879 }
880 
881 static void
883  XLogRecPtr commit_lsn)
884 {
885  LogicalDecodingContext *ctx = cache->private_data;
887  ErrorContextCallback errcallback;
888 
889  Assert(!ctx->fast_forward);
890 
891  /* Push callback + info on the error context stack */
892  state.ctx = ctx;
893  state.callback_name = "commit";
894  state.report_location = txn->final_lsn; /* beginning of commit record */
896  errcallback.arg = (void *) &state;
897  errcallback.previous = error_context_stack;
898  error_context_stack = &errcallback;
899 
900  /* set output state */
901  ctx->accept_writes = true;
902  ctx->write_xid = txn->xid;
903  ctx->write_location = txn->end_lsn; /* points to the end of the record */
904  ctx->end_xact = true;
905 
906  /* do the actual work: call callback */
907  ctx->callbacks.commit_cb(ctx, txn, commit_lsn);
908 
909  /* Pop the error context stack */
910  error_context_stack = errcallback.previous;
911 }
912 
913 /*
914  * The functionality of begin_prepare is quite similar to begin with the
915  * exception that this will have gid (global transaction id) information which
916  * can be used by plugin. Now, we thought about extending the existing begin
917  * but that would break the replication protocol and additionally this looks
918  * cleaner.
919  */
920 static void
922 {
923  LogicalDecodingContext *ctx = cache->private_data;
925  ErrorContextCallback errcallback;
926 
927  Assert(!ctx->fast_forward);
928 
929  /* We're only supposed to call this when two-phase commits are supported */
930  Assert(ctx->twophase);
931 
932  /* Push callback + info on the error context stack */
933  state.ctx = ctx;
934  state.callback_name = "begin_prepare";
935  state.report_location = txn->first_lsn;
937  errcallback.arg = (void *) &state;
938  errcallback.previous = error_context_stack;
939  error_context_stack = &errcallback;
940 
941  /* set output state */
942  ctx->accept_writes = true;
943  ctx->write_xid = txn->xid;
944  ctx->write_location = txn->first_lsn;
945  ctx->end_xact = false;
946 
947  /*
948  * If the plugin supports two-phase commits then begin prepare callback is
949  * mandatory
950  */
951  if (ctx->callbacks.begin_prepare_cb == NULL)
952  ereport(ERROR,
953  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
954  errmsg("logical replication at prepare time requires a %s callback",
955  "begin_prepare_cb")));
956 
957  /* do the actual work: call callback */
958  ctx->callbacks.begin_prepare_cb(ctx, txn);
959 
960  /* Pop the error context stack */
961  error_context_stack = errcallback.previous;
962 }
963 
964 static void
966  XLogRecPtr prepare_lsn)
967 {
968  LogicalDecodingContext *ctx = cache->private_data;
970  ErrorContextCallback errcallback;
971 
972  Assert(!ctx->fast_forward);
973 
974  /* We're only supposed to call this when two-phase commits are supported */
975  Assert(ctx->twophase);
976 
977  /* Push callback + info on the error context stack */
978  state.ctx = ctx;
979  state.callback_name = "prepare";
980  state.report_location = txn->final_lsn; /* beginning of prepare record */
982  errcallback.arg = (void *) &state;
983  errcallback.previous = error_context_stack;
984  error_context_stack = &errcallback;
985 
986  /* set output state */
987  ctx->accept_writes = true;
988  ctx->write_xid = txn->xid;
989  ctx->write_location = txn->end_lsn; /* points to the end of the record */
990  ctx->end_xact = true;
991 
992  /*
993  * If the plugin supports two-phase commits then prepare callback is
994  * mandatory
995  */
996  if (ctx->callbacks.prepare_cb == NULL)
997  ereport(ERROR,
998  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
999  errmsg("logical replication at prepare time requires a %s callback",
1000  "prepare_cb")));
1001 
1002  /* do the actual work: call callback */
1003  ctx->callbacks.prepare_cb(ctx, txn, prepare_lsn);
1004 
1005  /* Pop the error context stack */
1006  error_context_stack = errcallback.previous;
1007 }
1008 
1009 static void
1011  XLogRecPtr commit_lsn)
1012 {
1013  LogicalDecodingContext *ctx = cache->private_data;
1015  ErrorContextCallback errcallback;
1016 
1017  Assert(!ctx->fast_forward);
1018 
1019  /* We're only supposed to call this when two-phase commits are supported */
1020  Assert(ctx->twophase);
1021 
1022  /* Push callback + info on the error context stack */
1023  state.ctx = ctx;
1024  state.callback_name = "commit_prepared";
1025  state.report_location = txn->final_lsn; /* beginning of commit record */
1026  errcallback.callback = output_plugin_error_callback;
1027  errcallback.arg = (void *) &state;
1028  errcallback.previous = error_context_stack;
1029  error_context_stack = &errcallback;
1030 
1031  /* set output state */
1032  ctx->accept_writes = true;
1033  ctx->write_xid = txn->xid;
1034  ctx->write_location = txn->end_lsn; /* points to the end of the record */
1035  ctx->end_xact = true;
1036 
1037  /*
1038  * If the plugin support two-phase commits then commit prepared callback
1039  * is mandatory
1040  */
1041  if (ctx->callbacks.commit_prepared_cb == NULL)
1042  ereport(ERROR,
1043  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1044  errmsg("logical replication at prepare time requires a %s callback",
1045  "commit_prepared_cb")));
1046 
1047  /* do the actual work: call callback */
1048  ctx->callbacks.commit_prepared_cb(ctx, txn, commit_lsn);
1049 
1050  /* Pop the error context stack */
1051  error_context_stack = errcallback.previous;
1052 }
1053 
1054 static void
1056  XLogRecPtr prepare_end_lsn,
1057  TimestampTz prepare_time)
1058 {
1059  LogicalDecodingContext *ctx = cache->private_data;
1061  ErrorContextCallback errcallback;
1062 
1063  Assert(!ctx->fast_forward);
1064 
1065  /* We're only supposed to call this when two-phase commits are supported */
1066  Assert(ctx->twophase);
1067 
1068  /* Push callback + info on the error context stack */
1069  state.ctx = ctx;
1070  state.callback_name = "rollback_prepared";
1071  state.report_location = txn->final_lsn; /* beginning of commit record */
1072  errcallback.callback = output_plugin_error_callback;
1073  errcallback.arg = (void *) &state;
1074  errcallback.previous = error_context_stack;
1075  error_context_stack = &errcallback;
1076 
1077  /* set output state */
1078  ctx->accept_writes = true;
1079  ctx->write_xid = txn->xid;
1080  ctx->write_location = txn->end_lsn; /* points to the end of the record */
1081  ctx->end_xact = true;
1082 
1083  /*
1084  * If the plugin support two-phase commits then rollback prepared callback
1085  * is mandatory
1086  */
1087  if (ctx->callbacks.rollback_prepared_cb == NULL)
1088  ereport(ERROR,
1089  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1090  errmsg("logical replication at prepare time requires a %s callback",
1091  "rollback_prepared_cb")));
1092 
1093  /* do the actual work: call callback */
1094  ctx->callbacks.rollback_prepared_cb(ctx, txn, prepare_end_lsn,
1095  prepare_time);
1096 
1097  /* Pop the error context stack */
1098  error_context_stack = errcallback.previous;
1099 }
1100 
1101 static void
1103  Relation relation, ReorderBufferChange *change)
1104 {
1105  LogicalDecodingContext *ctx = cache->private_data;
1107  ErrorContextCallback errcallback;
1108 
1109  Assert(!ctx->fast_forward);
1110 
1111  /* Push callback + info on the error context stack */
1112  state.ctx = ctx;
1113  state.callback_name = "change";
1114  state.report_location = change->lsn;
1115  errcallback.callback = output_plugin_error_callback;
1116  errcallback.arg = (void *) &state;
1117  errcallback.previous = error_context_stack;
1118  error_context_stack = &errcallback;
1119 
1120  /* set output state */
1121  ctx->accept_writes = true;
1122  ctx->write_xid = txn->xid;
1123 
1124  /*
1125  * Report this change's lsn so replies from clients can give an up-to-date
1126  * answer. This won't ever be enough (and shouldn't be!) to confirm
1127  * receipt of this transaction, but it might allow another transaction's
1128  * commit to be confirmed with one message.
1129  */
1130  ctx->write_location = change->lsn;
1131 
1132  ctx->end_xact = false;
1133 
1134  ctx->callbacks.change_cb(ctx, txn, relation, change);
1135 
1136  /* Pop the error context stack */
1137  error_context_stack = errcallback.previous;
1138 }
1139 
1140 static void
1142  int nrelations, Relation relations[], ReorderBufferChange *change)
1143 {
1144  LogicalDecodingContext *ctx = cache->private_data;
1146  ErrorContextCallback errcallback;
1147 
1148  Assert(!ctx->fast_forward);
1149 
1150  if (!ctx->callbacks.truncate_cb)
1151  return;
1152 
1153  /* Push callback + info on the error context stack */
1154  state.ctx = ctx;
1155  state.callback_name = "truncate";
1156  state.report_location = change->lsn;
1157  errcallback.callback = output_plugin_error_callback;
1158  errcallback.arg = (void *) &state;
1159  errcallback.previous = error_context_stack;
1160  error_context_stack = &errcallback;
1161 
1162  /* set output state */
1163  ctx->accept_writes = true;
1164  ctx->write_xid = txn->xid;
1165 
1166  /*
1167  * Report this change's lsn so replies from clients can give an up-to-date
1168  * answer. This won't ever be enough (and shouldn't be!) to confirm
1169  * receipt of this transaction, but it might allow another transaction's
1170  * commit to be confirmed with one message.
1171  */
1172  ctx->write_location = change->lsn;
1173 
1174  ctx->end_xact = false;
1175 
1176  ctx->callbacks.truncate_cb(ctx, txn, nrelations, relations, change);
1177 
1178  /* Pop the error context stack */
1179  error_context_stack = errcallback.previous;
1180 }
1181 
1182 bool
1184  const char *gid)
1185 {
1187  ErrorContextCallback errcallback;
1188  bool ret;
1189 
1190  Assert(!ctx->fast_forward);
1191 
1192  /* Push callback + info on the error context stack */
1193  state.ctx = ctx;
1194  state.callback_name = "filter_prepare";
1195  state.report_location = InvalidXLogRecPtr;
1196  errcallback.callback = output_plugin_error_callback;
1197  errcallback.arg = (void *) &state;
1198  errcallback.previous = error_context_stack;
1199  error_context_stack = &errcallback;
1200 
1201  /* set output state */
1202  ctx->accept_writes = false;
1203  ctx->end_xact = false;
1204 
1205  /* do the actual work: call callback */
1206  ret = ctx->callbacks.filter_prepare_cb(ctx, xid, gid);
1207 
1208  /* Pop the error context stack */
1209  error_context_stack = errcallback.previous;
1210 
1211  return ret;
1212 }
1213 
1214 bool
1216 {
1218  ErrorContextCallback errcallback;
1219  bool ret;
1220 
1221  Assert(!ctx->fast_forward);
1222 
1223  /* Push callback + info on the error context stack */
1224  state.ctx = ctx;
1225  state.callback_name = "filter_by_origin";
1226  state.report_location = InvalidXLogRecPtr;
1227  errcallback.callback = output_plugin_error_callback;
1228  errcallback.arg = (void *) &state;
1229  errcallback.previous = error_context_stack;
1230  error_context_stack = &errcallback;
1231 
1232  /* set output state */
1233  ctx->accept_writes = false;
1234  ctx->end_xact = false;
1235 
1236  /* do the actual work: call callback */
1237  ret = ctx->callbacks.filter_by_origin_cb(ctx, origin_id);
1238 
1239  /* Pop the error context stack */
1240  error_context_stack = errcallback.previous;
1241 
1242  return ret;
1243 }
1244 
1245 static void
1247  XLogRecPtr message_lsn, bool transactional,
1248  const char *prefix, Size message_size, const char *message)
1249 {
1250  LogicalDecodingContext *ctx = cache->private_data;
1252  ErrorContextCallback errcallback;
1253 
1254  Assert(!ctx->fast_forward);
1255 
1256  if (ctx->callbacks.message_cb == NULL)
1257  return;
1258 
1259  /* Push callback + info on the error context stack */
1260  state.ctx = ctx;
1261  state.callback_name = "message";
1262  state.report_location = message_lsn;
1263  errcallback.callback = output_plugin_error_callback;
1264  errcallback.arg = (void *) &state;
1265  errcallback.previous = error_context_stack;
1266  error_context_stack = &errcallback;
1267 
1268  /* set output state */
1269  ctx->accept_writes = true;
1270  ctx->write_xid = txn != NULL ? txn->xid : InvalidTransactionId;
1271  ctx->write_location = message_lsn;
1272  ctx->end_xact = false;
1273 
1274  /* do the actual work: call callback */
1275  ctx->callbacks.message_cb(ctx, txn, message_lsn, transactional, prefix,
1276  message_size, message);
1277 
1278  /* Pop the error context stack */
1279  error_context_stack = errcallback.previous;
1280 }
1281 
1282 static void
1284  XLogRecPtr first_lsn)
1285 {
1286  LogicalDecodingContext *ctx = cache->private_data;
1288  ErrorContextCallback errcallback;
1289 
1290  Assert(!ctx->fast_forward);
1291 
1292  /* We're only supposed to call this when streaming is supported. */
1293  Assert(ctx->streaming);
1294 
1295  /* Push callback + info on the error context stack */
1296  state.ctx = ctx;
1297  state.callback_name = "stream_start";
1298  state.report_location = first_lsn;
1299  errcallback.callback = output_plugin_error_callback;
1300  errcallback.arg = (void *) &state;
1301  errcallback.previous = error_context_stack;
1302  error_context_stack = &errcallback;
1303 
1304  /* set output state */
1305  ctx->accept_writes = true;
1306  ctx->write_xid = txn->xid;
1307 
1308  /*
1309  * Report this message's lsn so replies from clients can give an
1310  * up-to-date answer. This won't ever be enough (and shouldn't be!) to
1311  * confirm receipt of this transaction, but it might allow another
1312  * transaction's commit to be confirmed with one message.
1313  */
1314  ctx->write_location = first_lsn;
1315 
1316  ctx->end_xact = false;
1317 
1318  /* in streaming mode, stream_start_cb is required */
1319  if (ctx->callbacks.stream_start_cb == NULL)
1320  ereport(ERROR,
1321  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1322  errmsg("logical streaming requires a %s callback",
1323  "stream_start_cb")));
1324 
1325  ctx->callbacks.stream_start_cb(ctx, txn);
1326 
1327  /* Pop the error context stack */
1328  error_context_stack = errcallback.previous;
1329 }
1330 
1331 static void
1333  XLogRecPtr last_lsn)
1334 {
1335  LogicalDecodingContext *ctx = cache->private_data;
1337  ErrorContextCallback errcallback;
1338 
1339  Assert(!ctx->fast_forward);
1340 
1341  /* We're only supposed to call this when streaming is supported. */
1342  Assert(ctx->streaming);
1343 
1344  /* Push callback + info on the error context stack */
1345  state.ctx = ctx;
1346  state.callback_name = "stream_stop";
1347  state.report_location = last_lsn;
1348  errcallback.callback = output_plugin_error_callback;
1349  errcallback.arg = (void *) &state;
1350  errcallback.previous = error_context_stack;
1351  error_context_stack = &errcallback;
1352 
1353  /* set output state */
1354  ctx->accept_writes = true;
1355  ctx->write_xid = txn->xid;
1356 
1357  /*
1358  * Report this message's lsn so replies from clients can give an
1359  * up-to-date answer. This won't ever be enough (and shouldn't be!) to
1360  * confirm receipt of this transaction, but it might allow another
1361  * transaction's commit to be confirmed with one message.
1362  */
1363  ctx->write_location = last_lsn;
1364 
1365  ctx->end_xact = false;
1366 
1367  /* in streaming mode, stream_stop_cb is required */
1368  if (ctx->callbacks.stream_stop_cb == NULL)
1369  ereport(ERROR,
1370  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1371  errmsg("logical streaming requires a %s callback",
1372  "stream_stop_cb")));
1373 
1374  ctx->callbacks.stream_stop_cb(ctx, txn);
1375 
1376  /* Pop the error context stack */
1377  error_context_stack = errcallback.previous;
1378 }
1379 
1380 static void
1382  XLogRecPtr abort_lsn)
1383 {
1384  LogicalDecodingContext *ctx = cache->private_data;
1386  ErrorContextCallback errcallback;
1387 
1388  Assert(!ctx->fast_forward);
1389 
1390  /* We're only supposed to call this when streaming is supported. */
1391  Assert(ctx->streaming);
1392 
1393  /* Push callback + info on the error context stack */
1394  state.ctx = ctx;
1395  state.callback_name = "stream_abort";
1396  state.report_location = abort_lsn;
1397  errcallback.callback = output_plugin_error_callback;
1398  errcallback.arg = (void *) &state;
1399  errcallback.previous = error_context_stack;
1400  error_context_stack = &errcallback;
1401 
1402  /* set output state */
1403  ctx->accept_writes = true;
1404  ctx->write_xid = txn->xid;
1405  ctx->write_location = abort_lsn;
1406  ctx->end_xact = true;
1407 
1408  /* in streaming mode, stream_abort_cb is required */
1409  if (ctx->callbacks.stream_abort_cb == NULL)
1410  ereport(ERROR,
1411  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1412  errmsg("logical streaming requires a %s callback",
1413  "stream_abort_cb")));
1414 
1415  ctx->callbacks.stream_abort_cb(ctx, txn, abort_lsn);
1416 
1417  /* Pop the error context stack */
1418  error_context_stack = errcallback.previous;
1419 }
1420 
1421 static void
1423  XLogRecPtr prepare_lsn)
1424 {
1425  LogicalDecodingContext *ctx = cache->private_data;
1427  ErrorContextCallback errcallback;
1428 
1429  Assert(!ctx->fast_forward);
1430 
1431  /*
1432  * We're only supposed to call this when streaming and two-phase commits
1433  * are supported.
1434  */
1435  Assert(ctx->streaming);
1436  Assert(ctx->twophase);
1437 
1438  /* Push callback + info on the error context stack */
1439  state.ctx = ctx;
1440  state.callback_name = "stream_prepare";
1441  state.report_location = txn->final_lsn;
1442  errcallback.callback = output_plugin_error_callback;
1443  errcallback.arg = (void *) &state;
1444  errcallback.previous = error_context_stack;
1445  error_context_stack = &errcallback;
1446 
1447  /* set output state */
1448  ctx->accept_writes = true;
1449  ctx->write_xid = txn->xid;
1450  ctx->write_location = txn->end_lsn;
1451  ctx->end_xact = true;
1452 
1453  /* in streaming mode with two-phase commits, stream_prepare_cb is required */
1454  if (ctx->callbacks.stream_prepare_cb == NULL)
1455  ereport(ERROR,
1456  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1457  errmsg("logical streaming at prepare time requires a %s callback",
1458  "stream_prepare_cb")));
1459 
1460  ctx->callbacks.stream_prepare_cb(ctx, txn, prepare_lsn);
1461 
1462  /* Pop the error context stack */
1463  error_context_stack = errcallback.previous;
1464 }
1465 
1466 static void
1468  XLogRecPtr commit_lsn)
1469 {
1470  LogicalDecodingContext *ctx = cache->private_data;
1472  ErrorContextCallback errcallback;
1473 
1474  Assert(!ctx->fast_forward);
1475 
1476  /* We're only supposed to call this when streaming is supported. */
1477  Assert(ctx->streaming);
1478 
1479  /* Push callback + info on the error context stack */
1480  state.ctx = ctx;
1481  state.callback_name = "stream_commit";
1482  state.report_location = txn->final_lsn;
1483  errcallback.callback = output_plugin_error_callback;
1484  errcallback.arg = (void *) &state;
1485  errcallback.previous = error_context_stack;
1486  error_context_stack = &errcallback;
1487 
1488  /* set output state */
1489  ctx->accept_writes = true;
1490  ctx->write_xid = txn->xid;
1491  ctx->write_location = txn->end_lsn;
1492  ctx->end_xact = true;
1493 
1494  /* in streaming mode, stream_commit_cb is required */
1495  if (ctx->callbacks.stream_commit_cb == NULL)
1496  ereport(ERROR,
1497  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1498  errmsg("logical streaming requires a %s callback",
1499  "stream_commit_cb")));
1500 
1501  ctx->callbacks.stream_commit_cb(ctx, txn, commit_lsn);
1502 
1503  /* Pop the error context stack */
1504  error_context_stack = errcallback.previous;
1505 }
1506 
1507 static void
1509  Relation relation, ReorderBufferChange *change)
1510 {
1511  LogicalDecodingContext *ctx = cache->private_data;
1513  ErrorContextCallback errcallback;
1514 
1515  Assert(!ctx->fast_forward);
1516 
1517  /* We're only supposed to call this when streaming is supported. */
1518  Assert(ctx->streaming);
1519 
1520  /* Push callback + info on the error context stack */
1521  state.ctx = ctx;
1522  state.callback_name = "stream_change";
1523  state.report_location = change->lsn;
1524  errcallback.callback = output_plugin_error_callback;
1525  errcallback.arg = (void *) &state;
1526  errcallback.previous = error_context_stack;
1527  error_context_stack = &errcallback;
1528 
1529  /* set output state */
1530  ctx->accept_writes = true;
1531  ctx->write_xid = txn->xid;
1532 
1533  /*
1534  * Report this change's lsn so replies from clients can give an up-to-date
1535  * answer. This won't ever be enough (and shouldn't be!) to confirm
1536  * receipt of this transaction, but it might allow another transaction's
1537  * commit to be confirmed with one message.
1538  */
1539  ctx->write_location = change->lsn;
1540 
1541  ctx->end_xact = false;
1542 
1543  /* in streaming mode, stream_change_cb is required */
1544  if (ctx->callbacks.stream_change_cb == NULL)
1545  ereport(ERROR,
1546  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1547  errmsg("logical streaming requires a %s callback",
1548  "stream_change_cb")));
1549 
1550  ctx->callbacks.stream_change_cb(ctx, txn, relation, change);
1551 
1552  /* Pop the error context stack */
1553  error_context_stack = errcallback.previous;
1554 }
1555 
1556 static void
1558  XLogRecPtr message_lsn, bool transactional,
1559  const char *prefix, Size message_size, const char *message)
1560 {
1561  LogicalDecodingContext *ctx = cache->private_data;
1563  ErrorContextCallback errcallback;
1564 
1565  Assert(!ctx->fast_forward);
1566 
1567  /* We're only supposed to call this when streaming is supported. */
1568  Assert(ctx->streaming);
1569 
1570  /* this callback is optional */
1571  if (ctx->callbacks.stream_message_cb == NULL)
1572  return;
1573 
1574  /* Push callback + info on the error context stack */
1575  state.ctx = ctx;
1576  state.callback_name = "stream_message";
1577  state.report_location = message_lsn;
1578  errcallback.callback = output_plugin_error_callback;
1579  errcallback.arg = (void *) &state;
1580  errcallback.previous = error_context_stack;
1581  error_context_stack = &errcallback;
1582 
1583  /* set output state */
1584  ctx->accept_writes = true;
1585  ctx->write_xid = txn != NULL ? txn->xid : InvalidTransactionId;
1586  ctx->write_location = message_lsn;
1587  ctx->end_xact = false;
1588 
1589  /* do the actual work: call callback */
1590  ctx->callbacks.stream_message_cb(ctx, txn, message_lsn, transactional, prefix,
1591  message_size, message);
1592 
1593  /* Pop the error context stack */
1594  error_context_stack = errcallback.previous;
1595 }
1596 
1597 static void
1599  int nrelations, Relation relations[],
1600  ReorderBufferChange *change)
1601 {
1602  LogicalDecodingContext *ctx = cache->private_data;
1604  ErrorContextCallback errcallback;
1605 
1606  Assert(!ctx->fast_forward);
1607 
1608  /* We're only supposed to call this when streaming is supported. */
1609  Assert(ctx->streaming);
1610 
1611  /* this callback is optional */
1612  if (!ctx->callbacks.stream_truncate_cb)
1613  return;
1614 
1615  /* Push callback + info on the error context stack */
1616  state.ctx = ctx;
1617  state.callback_name = "stream_truncate";
1618  state.report_location = change->lsn;
1619  errcallback.callback = output_plugin_error_callback;
1620  errcallback.arg = (void *) &state;
1621  errcallback.previous = error_context_stack;
1622  error_context_stack = &errcallback;
1623 
1624  /* set output state */
1625  ctx->accept_writes = true;
1626  ctx->write_xid = txn->xid;
1627 
1628  /*
1629  * Report this change's lsn so replies from clients can give an up-to-date
1630  * answer. This won't ever be enough (and shouldn't be!) to confirm
1631  * receipt of this transaction, but it might allow another transaction's
1632  * commit to be confirmed with one message.
1633  */
1634  ctx->write_location = change->lsn;
1635 
1636  ctx->end_xact = false;
1637 
1638  ctx->callbacks.stream_truncate_cb(ctx, txn, nrelations, relations, change);
1639 
1640  /* Pop the error context stack */
1641  error_context_stack = errcallback.previous;
1642 }
1643 
1644 static void
1646  XLogRecPtr lsn)
1647 {
1648  LogicalDecodingContext *ctx = cache->private_data;
1650  ErrorContextCallback errcallback;
1651 
1652  Assert(!ctx->fast_forward);
1653 
1654  /* Push callback + info on the error context stack */
1655  state.ctx = ctx;
1656  state.callback_name = "update_progress_txn";
1657  state.report_location = lsn;
1658  errcallback.callback = output_plugin_error_callback;
1659  errcallback.arg = (void *) &state;
1660  errcallback.previous = error_context_stack;
1661  error_context_stack = &errcallback;
1662 
1663  /* set output state */
1664  ctx->accept_writes = false;
1665  ctx->write_xid = txn->xid;
1666 
1667  /*
1668  * Report this change's lsn so replies from clients can give an up-to-date
1669  * answer. This won't ever be enough (and shouldn't be!) to confirm
1670  * receipt of this transaction, but it might allow another transaction's
1671  * commit to be confirmed with one message.
1672  */
1673  ctx->write_location = lsn;
1674 
1675  ctx->end_xact = false;
1676 
1677  OutputPluginUpdateProgress(ctx, false);
1678 
1679  /* Pop the error context stack */
1680  error_context_stack = errcallback.previous;
1681 }
1682 
1683 /*
1684  * Set the required catalog xmin horizon for historic snapshots in the current
1685  * replication slot.
1686  *
1687  * Note that in the most cases, we won't be able to immediately use the xmin
1688  * to increase the xmin horizon: we need to wait till the client has confirmed
1689  * receiving current_lsn with LogicalConfirmReceivedLocation().
1690  */
1691 void
1693 {
1694  bool updated_xmin = false;
1695  ReplicationSlot *slot;
1696  bool got_new_xmin = false;
1697 
1698  slot = MyReplicationSlot;
1699 
1700  Assert(slot != NULL);
1701 
1702  SpinLockAcquire(&slot->mutex);
1703 
1704  /*
1705  * don't overwrite if we already have a newer xmin. This can happen if we
1706  * restart decoding in a slot.
1707  */
1709  {
1710  }
1711 
1712  /*
1713  * If the client has already confirmed up to this lsn, we directly can
1714  * mark this as accepted. This can happen if we restart decoding in a
1715  * slot.
1716  */
1717  else if (current_lsn <= slot->data.confirmed_flush)
1718  {
1719  slot->candidate_catalog_xmin = xmin;
1720  slot->candidate_xmin_lsn = current_lsn;
1721 
1722  /* our candidate can directly be used */
1723  updated_xmin = true;
1724  }
1725 
1726  /*
1727  * Only increase if the previous values have been applied, otherwise we
1728  * might never end up updating if the receiver acks too slowly.
1729  */
1730  else if (slot->candidate_xmin_lsn == InvalidXLogRecPtr)
1731  {
1732  slot->candidate_catalog_xmin = xmin;
1733  slot->candidate_xmin_lsn = current_lsn;
1734 
1735  /*
1736  * Log new xmin at an appropriate log level after releasing the
1737  * spinlock.
1738  */
1739  got_new_xmin = true;
1740  }
1741  SpinLockRelease(&slot->mutex);
1742 
1743  if (got_new_xmin)
1744  elog(DEBUG1, "got new catalog xmin %u at %X/%X", xmin,
1745  LSN_FORMAT_ARGS(current_lsn));
1746 
1747  /* candidate already valid with the current flush position, apply */
1748  if (updated_xmin)
1750 }
1751 
1752 /*
1753  * Mark the minimal LSN (restart_lsn) we need to read to replay all
1754  * transactions that have not yet committed at current_lsn.
1755  *
1756  * Just like LogicalIncreaseXminForSlot this only takes effect when the
1757  * client has confirmed to have received current_lsn.
1758  */
1759 void
1761 {
1762  bool updated_lsn = false;
1763  ReplicationSlot *slot;
1764 
1765  slot = MyReplicationSlot;
1766 
1767  Assert(slot != NULL);
1768  Assert(restart_lsn != InvalidXLogRecPtr);
1769  Assert(current_lsn != InvalidXLogRecPtr);
1770 
1771  SpinLockAcquire(&slot->mutex);
1772 
1773  /* don't overwrite if have a newer restart lsn */
1774  if (restart_lsn <= slot->data.restart_lsn)
1775  {
1776  }
1777 
1778  /*
1779  * We might have already flushed far enough to directly accept this lsn,
1780  * in this case there is no need to check for existing candidate LSNs
1781  */
1782  else if (current_lsn <= slot->data.confirmed_flush)
1783  {
1784  slot->candidate_restart_valid = current_lsn;
1785  slot->candidate_restart_lsn = restart_lsn;
1786 
1787  /* our candidate can directly be used */
1788  updated_lsn = true;
1789  }
1790 
1791  /*
1792  * Only increase if the previous values have been applied, otherwise we
1793  * might never end up updating if the receiver acks too slowly. A missed
1794  * value here will just cause some extra effort after reconnecting.
1795  */
1797  {
1798  slot->candidate_restart_valid = current_lsn;
1799  slot->candidate_restart_lsn = restart_lsn;
1800  SpinLockRelease(&slot->mutex);
1801 
1802  elog(DEBUG1, "got new restart lsn %X/%X at %X/%X",
1803  LSN_FORMAT_ARGS(restart_lsn),
1804  LSN_FORMAT_ARGS(current_lsn));
1805  }
1806  else
1807  {
1808  XLogRecPtr candidate_restart_lsn;
1809  XLogRecPtr candidate_restart_valid;
1810  XLogRecPtr confirmed_flush;
1811 
1812  candidate_restart_lsn = slot->candidate_restart_lsn;
1813  candidate_restart_valid = slot->candidate_restart_valid;
1814  confirmed_flush = slot->data.confirmed_flush;
1815  SpinLockRelease(&slot->mutex);
1816 
1817  elog(DEBUG1, "failed to increase restart lsn: proposed %X/%X, after %X/%X, current candidate %X/%X, current after %X/%X, flushed up to %X/%X",
1818  LSN_FORMAT_ARGS(restart_lsn),
1819  LSN_FORMAT_ARGS(current_lsn),
1820  LSN_FORMAT_ARGS(candidate_restart_lsn),
1821  LSN_FORMAT_ARGS(candidate_restart_valid),
1822  LSN_FORMAT_ARGS(confirmed_flush));
1823  }
1824 
1825  /* candidates are already valid with the current flush position, apply */
1826  if (updated_lsn)
1828 }
1829 
1830 /*
1831  * Handle a consumer's confirmation having received all changes up to lsn.
1832  */
1833 void
1835 {
1836  Assert(lsn != InvalidXLogRecPtr);
1837 
1838  /* Do an unlocked check for candidate_lsn first. */
1841  {
1842  bool updated_xmin = false;
1843  bool updated_restart = false;
1844 
1846 
1848 
1849  /* if we're past the location required for bumping xmin, do so */
1852  {
1853  /*
1854  * We have to write the changed xmin to disk *before* we change
1855  * the in-memory value, otherwise after a crash we wouldn't know
1856  * that some catalog tuples might have been removed already.
1857  *
1858  * Ensure that by first writing to ->xmin and only update
1859  * ->effective_xmin once the new state is synced to disk. After a
1860  * crash ->effective_xmin is set to ->xmin.
1861  */
1864  {
1868  updated_xmin = true;
1869  }
1870  }
1871 
1874  {
1876 
1880  updated_restart = true;
1881  }
1882 
1884 
1885  /* first write new xmin to disk, so we know what's up after a crash */
1886  if (updated_xmin || updated_restart)
1887  {
1890  elog(DEBUG1, "updated xmin: %u restart: %u", updated_xmin, updated_restart);
1891  }
1892 
1893  /*
1894  * Now the new xmin is safely on disk, we can let the global value
1895  * advance. We do not take ProcArrayLock or similar since we only
1896  * advance xmin here and there's not much harm done by a concurrent
1897  * computation missing that.
1898  */
1899  if (updated_xmin)
1900  {
1904 
1907  }
1908  }
1909  else
1910  {
1914  }
1915 }
1916 
1917 /*
1918  * Clear logical streaming state during (sub)transaction abort.
1919  */
1920 void
1922 {
1924  bsysscan = false;
1925 }
1926 
1927 /*
1928  * Report stats for a slot.
1929  */
1930 void
1932 {
1933  ReorderBuffer *rb = ctx->reorder;
1934  PgStat_StatReplSlotEntry repSlotStat;
1935 
1936  /* Nothing to do if we don't have any replication stats to be sent. */
1937  if (rb->spillBytes <= 0 && rb->streamBytes <= 0 && rb->totalBytes <= 0)
1938  return;
1939 
1940  elog(DEBUG2, "UpdateDecodingStats: updating stats %p %lld %lld %lld %lld %lld %lld %lld %lld",
1941  rb,
1942  (long long) rb->spillTxns,
1943  (long long) rb->spillCount,
1944  (long long) rb->spillBytes,
1945  (long long) rb->streamTxns,
1946  (long long) rb->streamCount,
1947  (long long) rb->streamBytes,
1948  (long long) rb->totalTxns,
1949  (long long) rb->totalBytes);
1950 
1951  repSlotStat.spill_txns = rb->spillTxns;
1952  repSlotStat.spill_count = rb->spillCount;
1953  repSlotStat.spill_bytes = rb->spillBytes;
1954  repSlotStat.stream_txns = rb->streamTxns;
1955  repSlotStat.stream_count = rb->streamCount;
1956  repSlotStat.stream_bytes = rb->streamBytes;
1957  repSlotStat.total_txns = rb->totalTxns;
1958  repSlotStat.total_bytes = rb->totalBytes;
1959 
1960  pgstat_report_replslot(ctx->slot, &repSlotStat);
1961 
1962  rb->spillTxns = 0;
1963  rb->spillCount = 0;
1964  rb->spillBytes = 0;
1965  rb->streamTxns = 0;
1966  rb->streamCount = 0;
1967  rb->streamBytes = 0;
1968  rb->totalTxns = 0;
1969  rb->totalBytes = 0;
1970 }
1971 
1972 /*
1973  * Read up to the end of WAL starting from the decoding slot's restart_lsn.
1974  * Return true if any meaningful/decodable WAL records are encountered,
1975  * otherwise false.
1976  */
1977 bool
1979 {
1980  bool has_pending_wal = false;
1981 
1983 
1984  PG_TRY();
1985  {
1987 
1988  /*
1989  * Create our decoding context in fast_forward mode, passing start_lsn
1990  * as InvalidXLogRecPtr, so that we start processing from the slot's
1991  * confirmed_flush.
1992  */
1994  NIL,
1995  true, /* fast_forward */
1996  XL_ROUTINE(.page_read = read_local_xlog_page,
1997  .segment_open = wal_segment_open,
1998  .segment_close = wal_segment_close),
1999  NULL, NULL, NULL);
2000 
2001  /*
2002  * Start reading at the slot's restart_lsn, which we know points to a
2003  * valid record.
2004  */
2006 
2007  /* Invalidate non-timetravel entries */
2009 
2010  /* Loop until the end of WAL or some changes are processed */
2011  while (!has_pending_wal && ctx->reader->EndRecPtr < end_of_wal)
2012  {
2013  XLogRecord *record;
2014  char *errm = NULL;
2015 
2016  record = XLogReadRecord(ctx->reader, &errm);
2017 
2018  if (errm)
2019  elog(ERROR, "could not find record for logical decoding: %s", errm);
2020 
2021  if (record != NULL)
2023 
2024  has_pending_wal = ctx->processing_required;
2025 
2027  }
2028 
2029  /* Clean up */
2030  FreeDecodingContext(ctx);
2032  }
2033  PG_CATCH();
2034  {
2035  /* clear all timetravel entries */
2037 
2038  PG_RE_THROW();
2039  }
2040  PG_END_TRY();
2041 
2042  return has_pending_wal;
2043 }
2044 
2045 /*
2046  * Helper function for advancing our logical replication slot forward.
2047  *
2048  * The slot's restart_lsn is used as start point for reading records, while
2049  * confirmed_flush is used as base point for the decoding context.
2050  *
2051  * We cannot just do LogicalConfirmReceivedLocation to update confirmed_flush,
2052  * because we need to digest WAL to advance restart_lsn allowing to recycle
2053  * WAL and removal of old catalog tuples. As decoding is done in fast_forward
2054  * mode, no changes are generated anyway.
2055  *
2056  * *found_consistent_snapshot will be true if the initial decoding snapshot has
2057  * been built; Otherwise, it will be false.
2058  */
2059 XLogRecPtr
2061  bool *found_consistent_snapshot)
2062 {
2064  ResourceOwner old_resowner = CurrentResourceOwner;
2065  XLogRecPtr retlsn;
2066 
2067  Assert(moveto != InvalidXLogRecPtr);
2068 
2069  if (found_consistent_snapshot)
2070  *found_consistent_snapshot = false;
2071 
2072  PG_TRY();
2073  {
2074  /*
2075  * Create our decoding context in fast_forward mode, passing start_lsn
2076  * as InvalidXLogRecPtr, so that we start processing from my slot's
2077  * confirmed_flush.
2078  */
2080  NIL,
2081  true, /* fast_forward */
2082  XL_ROUTINE(.page_read = read_local_xlog_page,
2083  .segment_open = wal_segment_open,
2084  .segment_close = wal_segment_close),
2085  NULL, NULL, NULL);
2086 
2087  /*
2088  * Wait for specified streaming replication standby servers (if any)
2089  * to confirm receipt of WAL up to moveto lsn.
2090  */
2092 
2093  /*
2094  * Start reading at the slot's restart_lsn, which we know to point to
2095  * a valid record.
2096  */
2098 
2099  /* invalidate non-timetravel entries */
2101 
2102  /* Decode records until we reach the requested target */
2103  while (ctx->reader->EndRecPtr < moveto)
2104  {
2105  char *errm = NULL;
2106  XLogRecord *record;
2107 
2108  /*
2109  * Read records. No changes are generated in fast_forward mode,
2110  * but snapbuilder/slot statuses are updated properly.
2111  */
2112  record = XLogReadRecord(ctx->reader, &errm);
2113  if (errm)
2114  elog(ERROR, "could not find record while advancing replication slot: %s",
2115  errm);
2116 
2117  /*
2118  * Process the record. Storage-level changes are ignored in
2119  * fast_forward mode, but other modules (such as snapbuilder)
2120  * might still have critical updates to do.
2121  */
2122  if (record)
2124 
2126  }
2127 
2128  if (found_consistent_snapshot && DecodingContextReady(ctx))
2129  *found_consistent_snapshot = true;
2130 
2131  /*
2132  * Logical decoding could have clobbered CurrentResourceOwner during
2133  * transaction management, so restore the executor's value. (This is
2134  * a kluge, but it's not worth cleaning up right now.)
2135  */
2136  CurrentResourceOwner = old_resowner;
2137 
2138  if (ctx->reader->EndRecPtr != InvalidXLogRecPtr)
2139  {
2141 
2142  /*
2143  * If only the confirmed_flush LSN has changed the slot won't get
2144  * marked as dirty by the above. Callers on the walsender
2145  * interface are expected to keep track of their own progress and
2146  * don't need it written out. But SQL-interface users cannot
2147  * specify their own start positions and it's harder for them to
2148  * keep track of their progress, so we should make more of an
2149  * effort to save it for them.
2150  *
2151  * Dirty the slot so it is written out at the next checkpoint. The
2152  * LSN position advanced to may still be lost on a crash but this
2153  * makes the data consistent after a clean shutdown.
2154  */
2156  }
2157 
2159 
2160  /* free context, call shutdown callback */
2161  FreeDecodingContext(ctx);
2162 
2164  }
2165  PG_CATCH();
2166  {
2167  /* clear all timetravel entries */
2169 
2170  PG_RE_THROW();
2171  }
2172  PG_END_TRY();
2173 
2174  return retlsn;
2175 }
#define NameStr(name)
Definition: c.h:746
#define Assert(condition)
Definition: c.h:858
uint32 TransactionId
Definition: c.h:652
size_t Size
Definition: c.h:605
int64 TimestampTz
Definition: timestamp.h:39
void LogicalDecodingProcessRecord(LogicalDecodingContext *ctx, XLogReaderState *record)
Definition: decode.c:88
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:105
int errdetail(const char *fmt,...)
Definition: elog.c:1205
ErrorContextCallback * error_context_stack
Definition: elog.c:94
int errhint(const char *fmt,...)
Definition: elog.c:1319
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define LOG
Definition: elog.h:31
#define PG_RE_THROW()
Definition: elog.h:411
#define errcontext
Definition: elog.h:196
#define PG_TRY(...)
Definition: elog.h:370
#define DEBUG2
Definition: elog.h:29
#define PG_END_TRY(...)
Definition: elog.h:395
#define DEBUG1
Definition: elog.h:30
#define ERROR
Definition: elog.h:39
#define PG_CATCH(...)
Definition: elog.h:380
#define elog(elevel,...)
Definition: elog.h:224
#define ereport(elevel,...)
Definition: elog.h:149
void err(int eval, const char *fmt,...)
Definition: err.c:43
Oid MyDatabaseId
Definition: globals.c:91
void InvalidateSystemCaches(void)
Definition: inval.c:792
static void change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change)
Definition: logical.c:1102
static void commit_prepared_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
Definition: logical.c:1010
static void update_progress_txn_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr lsn)
Definition: logical.c:1645
XLogRecPtr LogicalSlotAdvanceAndCheckSnapState(XLogRecPtr moveto, bool *found_consistent_snapshot)
Definition: logical.c:2060
void LogicalConfirmReceivedLocation(XLogRecPtr lsn)
Definition: logical.c:1834
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:693
bool LogicalReplicationSlotHasPendingWal(XLogRecPtr end_of_wal)
Definition: logical.c:1978
static void stream_start_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr first_lsn)
Definition: logical.c:1283
static void commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
Definition: logical.c:882
static void output_plugin_error_callback(void *arg)
Definition: logical.c:771
static void begin_prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn)
Definition: logical.c:921
static void stream_prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr prepare_lsn)
Definition: logical.c:1422
static void prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr prepare_lsn)
Definition: logical.c:965
static LogicalDecodingContext * StartupDecodingContext(List *output_plugin_options, XLogRecPtr start_lsn, TransactionId xmin_horizon, bool need_full_snapshot, bool fast_forward, XLogReaderRoutine *xl_routine, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:150
void OutputPluginWrite(struct LogicalDecodingContext *ctx, bool last_write)
Definition: logical.c:721
static void stream_truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, int nrelations, Relation relations[], ReorderBufferChange *change)
Definition: logical.c:1598
static void truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, int nrelations, Relation relations[], ReorderBufferChange *change)
Definition: logical.c:1141
void DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
Definition: logical.c:649
static void begin_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn)
Definition: logical.c:851
static void rollback_prepared_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr prepare_end_lsn, TimestampTz prepare_time)
Definition: logical.c:1055
bool DecodingContextReady(LogicalDecodingContext *ctx)
Definition: logical.c:640
void OutputPluginUpdateProgress(struct LogicalDecodingContext *ctx, bool skipped_xact)
Definition: logical.c:734
static void startup_cb_wrapper(LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init)
Definition: logical.c:790
void UpdateDecodingStats(LogicalDecodingContext *ctx)
Definition: logical.c:1931
void LogicalIncreaseRestartDecodingForSlot(XLogRecPtr current_lsn, XLogRecPtr restart_lsn)
Definition: logical.c:1760
static void stream_change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change)
Definition: logical.c:1508
static void stream_abort_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr abort_lsn)
Definition: logical.c:1381
void ResetLogicalStreamingState(void)
Definition: logical.c:1921
void LogicalIncreaseXminForSlot(XLogRecPtr current_lsn, TransactionId xmin)
Definition: logical.c:1692
struct LogicalErrorCallbackState LogicalErrorCallbackState
static void stream_message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr message_lsn, bool transactional, const char *prefix, Size message_size, const char *message)
Definition: logical.c:1557
static void stream_commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
Definition: logical.c:1467
bool filter_prepare_cb_wrapper(LogicalDecodingContext *ctx, TransactionId xid, const char *gid)
Definition: logical.c:1183
static void shutdown_cb_wrapper(LogicalDecodingContext *ctx)
Definition: logical.c:818
void OutputPluginPrepareWrite(struct LogicalDecodingContext *ctx, bool last_write)
Definition: logical.c:708
void CheckLogicalDecodingRequirements(void)
Definition: logical.c:109
LogicalDecodingContext * CreateInitDecodingContext(const char *plugin, List *output_plugin_options, bool need_full_snapshot, XLogRecPtr restart_lsn, XLogReaderRoutine *xl_routine, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:329
bool filter_by_origin_cb_wrapper(LogicalDecodingContext *ctx, RepOriginId origin_id)
Definition: logical.c:1215
static void LoadOutputPlugin(OutputPluginCallbacks *callbacks, const char *plugin)
Definition: logical.c:749
static void stream_stop_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr last_lsn)
Definition: logical.c:1332
static void message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr message_lsn, bool transactional, const char *prefix, Size message_size, const char *message)
Definition: logical.c:1246
LogicalDecodingContext * CreateDecodingContext(XLogRecPtr start_lsn, List *output_plugin_options, bool fast_forward, XLogReaderRoutine *xl_routine, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:495
void(* LogicalOutputPluginWriterUpdateProgress)(struct LogicalDecodingContext *lr, XLogRecPtr Ptr, TransactionId xid, bool skipped_xact)
Definition: logical.h:27
void(* LogicalOutputPluginWriterWrite)(struct LogicalDecodingContext *lr, XLogRecPtr Ptr, TransactionId xid, bool last_write)
Definition: logical.h:19
LogicalOutputPluginWriterWrite LogicalOutputPluginWriterPrepareWrite
Definition: logical.h:25
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1170
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1783
@ LW_EXCLUSIVE
Definition: lwlock.h:114
void * palloc0(Size size)
Definition: mcxt.c:1346
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
void namestrcpy(Name name, const char *str)
Definition: name.c:233
void(* LogicalOutputPluginInit)(struct OutputPluginCallbacks *cb)
Definition: output_plugin.h:36
void * arg
const void * data
#define NIL
Definition: pg_list.h:68
static const char * plugin
void pgstat_report_replslot(ReplicationSlot *slot, const PgStat_StatReplSlotEntry *repSlotStat)
#define InvalidOid
Definition: postgres_ext.h:36
#define PROC_IN_LOGICAL_DECODING
Definition: proc.h:61
TransactionId GetOldestSafeDecodingTransactionId(bool catalogOnly)
Definition: procarray.c:2932
tree context
Definition: radixtree.h:1829
MemoryContextSwitchTo(old_ctx)
ReorderBuffer * ReorderBufferAllocate(void)
void ReorderBufferFree(ReorderBuffer *rb)
ResourceOwner CurrentResourceOwner
Definition: resowner.c:165
void ReplicationSlotMarkDirty(void)
Definition: slot.c:1006
void ReplicationSlotReserveWal(void)
Definition: slot.c:1397
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:1045
ReplicationSlot * MyReplicationSlot
Definition: slot.c:138
void ReplicationSlotSave(void)
Definition: slot.c:988
void WaitForStandbyConfirmation(XLogRecPtr wait_for_lsn)
Definition: slot.c:2738
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:1101
void CheckSlotRequirements(void)
Definition: slot.c:1358
#define SlotIsPhysical(slot)
Definition: slot.h:209
@ RS_INVAL_WAL_REMOVED
Definition: slot.h:51
@ RS_INVAL_NONE
Definition: slot.h:49
bool IsSyncingReplicationSlots(void)
Definition: slotsync.c:1569
void SnapBuildSetTwoPhaseAt(SnapBuild *builder, XLogRecPtr ptr)
Definition: snapbuild.c:424
SnapBuildState SnapBuildCurrentState(SnapBuild *builder)
Definition: snapbuild.c:406
void FreeSnapshotBuilder(SnapBuild *builder)
Definition: snapbuild.c:362
SnapBuild * AllocateSnapshotBuilder(ReorderBuffer *reorder, TransactionId xmin_horizon, XLogRecPtr start_lsn, bool need_full_snapshot, XLogRecPtr two_phase_at)
Definition: snapbuild.c:316
@ SNAPBUILD_CONSISTENT
Definition: snapbuild.h:46
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
PGPROC * MyProc
Definition: proc.c:66
PROC_HDR * ProcGlobal
Definition: proc.c:78
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
struct ErrorContextCallback * previous
Definition: elog.h:295
void(* callback)(void *arg)
Definition: elog.h:296
Definition: pg_list.h:54
OutputPluginOptions options
Definition: logical.h:54
XLogReaderState * reader
Definition: logical.h:42
MemoryContext context
Definition: logical.h:36
struct SnapBuild * snapshot_builder
Definition: logical.h:44
StringInfo out
Definition: logical.h:71
XLogRecPtr write_location
Definition: logical.h:108
LogicalOutputPluginWriterPrepareWrite prepare_write
Definition: logical.h:64
OutputPluginCallbacks callbacks
Definition: logical.h:53
TransactionId write_xid
Definition: logical.h:109
List * output_plugin_options
Definition: logical.h:59
ReplicationSlot * slot
Definition: logical.h:39
LogicalOutputPluginWriterWrite write
Definition: logical.h:65
struct ReorderBuffer * reorder
Definition: logical.h:43
LogicalOutputPluginWriterUpdateProgress update_progress
Definition: logical.h:66
XLogRecPtr report_location
Definition: logical.c:52
LogicalDecodingContext * ctx
Definition: logical.c:50
const char * callback_name
Definition: logical.c:51
LogicalDecodeStreamChangeCB stream_change_cb
LogicalDecodeMessageCB message_cb
LogicalDecodeStreamTruncateCB stream_truncate_cb
LogicalDecodeStreamMessageCB stream_message_cb
LogicalDecodeFilterPrepareCB filter_prepare_cb
LogicalDecodeFilterByOriginCB filter_by_origin_cb
LogicalDecodeTruncateCB truncate_cb
LogicalDecodeStreamStopCB stream_stop_cb
LogicalDecodeStreamCommitCB stream_commit_cb
LogicalDecodeRollbackPreparedCB rollback_prepared_cb
LogicalDecodeStreamPrepareCB stream_prepare_cb
LogicalDecodeCommitPreparedCB commit_prepared_cb
LogicalDecodeStreamStartCB stream_start_cb
LogicalDecodePrepareCB prepare_cb
LogicalDecodeStartupCB startup_cb
LogicalDecodeCommitCB commit_cb
LogicalDecodeBeginCB begin_cb
LogicalDecodeStreamAbortCB stream_abort_cb
LogicalDecodeBeginPrepareCB begin_prepare_cb
LogicalDecodeChangeCB change_cb
LogicalDecodeShutdownCB shutdown_cb
uint8 statusFlags
Definition: proc.h:238
int pgxactoff
Definition: proc.h:180
uint8 * statusFlags
Definition: proc.h:395
PgStat_Counter stream_count
Definition: pgstat.h:373
PgStat_Counter total_txns
Definition: pgstat.h:375
PgStat_Counter total_bytes
Definition: pgstat.h:376
PgStat_Counter spill_txns
Definition: pgstat.h:369
PgStat_Counter stream_txns
Definition: pgstat.h:372
PgStat_Counter spill_count
Definition: pgstat.h:370
PgStat_Counter stream_bytes
Definition: pgstat.h:374
PgStat_Counter spill_bytes
Definition: pgstat.h:371
XLogRecPtr first_lsn
XLogRecPtr final_lsn
XLogRecPtr end_lsn
TransactionId xid
ReorderBufferStreamMessageCB stream_message
ReorderBufferStreamChangeCB stream_change
ReorderBufferBeginCB begin_prepare
ReorderBufferStreamTruncateCB stream_truncate
ReorderBufferCommitPreparedCB commit_prepared
ReorderBufferUpdateProgressTxnCB update_progress_txn
ReorderBufferMessageCB message
ReorderBufferRollbackPreparedCB rollback_prepared
ReorderBufferPrepareCB prepare
ReorderBufferStreamStopCB stream_stop
ReorderBufferApplyChangeCB apply_change
ReorderBufferStreamPrepareCB stream_prepare
ReorderBufferStreamAbortCB stream_abort
ReorderBufferCommitCB commit
ReorderBufferStreamStartCB stream_start
ReorderBufferStreamCommitCB stream_commit
ReorderBufferApplyTruncateCB apply_truncate
ReorderBufferBeginCB begin
void * private_data
TransactionId catalog_xmin
Definition: slot.h:90
XLogRecPtr restart_lsn
Definition: slot.h:93
XLogRecPtr confirmed_flush
Definition: slot.h:104
ReplicationSlotInvalidationCause invalidated
Definition: slot.h:96
XLogRecPtr candidate_xmin_lsn
Definition: slot.h:194
TransactionId effective_catalog_xmin
Definition: slot.h:175
slock_t mutex
Definition: slot.h:151
XLogRecPtr candidate_restart_valid
Definition: slot.h:195
TransactionId effective_xmin
Definition: slot.h:174
XLogRecPtr candidate_restart_lsn
Definition: slot.h:196
TransactionId candidate_catalog_xmin
Definition: slot.h:193
ReplicationSlotPersistentData data
Definition: slot.h:178
XLogRecPtr EndRecPtr
Definition: xlogreader.h:207
Definition: c.h:741
Definition: regguts.h:323
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:299
#define InvalidTransactionId
Definition: transam.h:31
#define TransactionIdIsValid(xid)
Definition: transam.h:41
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4933
bool bsysscan
Definition: xact.c:98
TransactionId CheckXidAlive
Definition: xact.c:97
bool IsTransactionState(void)
Definition: xact.c:384
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:438
bool RecoveryInProgress(void)
Definition: xlog.c:6290
int wal_level
Definition: xlog.c:131
int wal_segment_size
Definition: xlog.c:143
WalLevel GetActiveWalLevelOnStandby(void)
Definition: xlog.c:4826
@ WAL_LEVEL_LOGICAL
Definition: xlog.h:74
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
uint16 RepOriginId
Definition: xlogdefs.h:65
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:389
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:161
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition: xlogreader.c:106
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:231
#define XL_ROUTINE(...)
Definition: xlogreader.h:117
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:842
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:817
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:861