1 /*-------------------------------------------------------------------------
3 * PostgreSQL logical decoding coordination
5 * Copyright (c) 2012-2024, PostgreSQL Global Development Group
8 * src/backend/replication/logical/logical.c
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
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
26 *-------------------------------------------------------------------------
31 #include "access/xact.h"
32 #include "access/xlogutils.h"
34 #include "miscadmin.h"
36 #include "replication/decode.h"
37 #include "replication/logical.h"
38 #include "replication/reorderbuffer.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"
47 /* data for errcontext callback */
48 typedef struct LogicalErrorCallbackState
50 LogicalDecodingContext
*ctx
;
51 const char *callback_name
;
52 XLogRecPtr report_location
;
53 } LogicalErrorCallbackState
;
55 /* wrappers around output plugin callbacks */
56 static void output_plugin_error_callback(void *arg
);
57 static void startup_cb_wrapper(LogicalDecodingContext
*ctx
, OutputPluginOptions
*opt
,
59 static void shutdown_cb_wrapper(LogicalDecodingContext
*ctx
);
60 static void begin_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
);
61 static void commit_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
62 XLogRecPtr commit_lsn
);
63 static void begin_prepare_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
);
64 static void prepare_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
65 XLogRecPtr prepare_lsn
);
66 static void commit_prepared_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
67 XLogRecPtr commit_lsn
);
68 static void rollback_prepared_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
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
);
78 /* streaming callbacks */
79 static void stream_start_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
80 XLogRecPtr first_lsn
);
81 static void stream_stop_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
83 static void stream_abort_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
84 XLogRecPtr abort_lsn
);
85 static void stream_prepare_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
86 XLogRecPtr prepare_lsn
);
87 static void stream_commit_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
88 XLogRecPtr commit_lsn
);
89 static void stream_change_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
90 Relation relation
, ReorderBufferChange
*change
);
91 static void stream_message_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
92 XLogRecPtr message_lsn
, bool transactional
,
93 const char *prefix
, Size message_size
, const char *message
);
94 static void stream_truncate_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
95 int nrelations
, Relation relations
[], ReorderBufferChange
*change
);
97 /* callback to update txn's progress */
98 static void update_progress_txn_cb_wrapper(ReorderBuffer
*cache
,
99 ReorderBufferTXN
*txn
,
102 static void LoadOutputPlugin(OutputPluginCallbacks
*callbacks
, const char *plugin
);
105 * Make sure the current settings & environment are capable of doing logical
109 CheckLogicalDecodingRequirements(void)
111 CheckSlotRequirements();
114 * NB: Adding a new requirement likely means that RestoreSlotFromDisk()
115 * needs the same check.
118 if (wal_level
< WAL_LEVEL_LOGICAL
)
120 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
121 errmsg("logical decoding requires \"wal_level\" >= \"logical\"")));
123 if (MyDatabaseId
== InvalidOid
)
125 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
126 errmsg("logical decoding requires a database connection")));
128 if (RecoveryInProgress())
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.
138 if (GetActiveWalLevelOnStandby() < WAL_LEVEL_LOGICAL
)
140 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
141 errmsg("logical decoding on standby requires \"wal_level\" >= \"logical\" on the primary")));
146 * Helper function for CreateInitDecodingContext() and
147 * CreateDecodingContext() performing common tasks.
149 static LogicalDecodingContext
*
150 StartupDecodingContext(List
*output_plugin_options
,
151 XLogRecPtr start_lsn
,
152 TransactionId xmin_horizon
,
153 bool need_full_snapshot
,
156 XLogReaderRoutine
*xl_routine
,
157 LogicalOutputPluginWriterPrepareWrite prepare_write
,
158 LogicalOutputPluginWriterWrite do_write
,
159 LogicalOutputPluginWriterUpdateProgress update_progress
)
161 ReplicationSlot
*slot
;
162 MemoryContext context
,
164 LogicalDecodingContext
*ctx
;
166 /* shorter lines... */
167 slot
= MyReplicationSlot
;
169 context
= AllocSetContextCreate(CurrentMemoryContext
,
170 "Logical decoding context",
171 ALLOCSET_DEFAULT_SIZES
);
172 old_context
= MemoryContextSwitchTo(context
);
173 ctx
= palloc0(sizeof(LogicalDecodingContext
));
175 ctx
->context
= context
;
178 * (re-)load output plugins, so we detect a bad (removed) output plugin
182 LoadOutputPlugin(&ctx
->callbacks
, NameStr(slot
->data
.plugin
));
185 * Now that the slot's xmin has been set, we can announce ourselves as a
186 * logical decoding backend which doesn't need to be checked individually
187 * when computing the xmin horizon because the xmin is enforced via
190 * We can only do so if we're outside of a transaction (i.e. the case when
191 * streaming changes via walsender), otherwise an already setup
192 * snapshot/xid would end up being ignored. That's not a particularly
193 * bothersome restriction since the SQL interface can't be used for
196 if (!IsTransactionOrTransactionBlock())
198 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
199 MyProc
->statusFlags
|= PROC_IN_LOGICAL_DECODING
;
200 ProcGlobal
->statusFlags
[MyProc
->pgxactoff
] = MyProc
->statusFlags
;
201 LWLockRelease(ProcArrayLock
);
206 ctx
->reader
= XLogReaderAllocate(wal_segment_size
, NULL
, xl_routine
, ctx
);
209 (errcode(ERRCODE_OUT_OF_MEMORY
),
210 errmsg("out of memory"),
211 errdetail("Failed while allocating a WAL reading processor.")));
213 ctx
->reorder
= ReorderBufferAllocate();
214 ctx
->snapshot_builder
=
215 AllocateSnapshotBuilder(ctx
->reorder
, xmin_horizon
, start_lsn
,
216 need_full_snapshot
, in_create
, slot
->data
.two_phase_at
);
218 ctx
->reorder
->private_data
= ctx
;
220 /* wrap output plugin callbacks, so we can add error context information */
221 ctx
->reorder
->begin
= begin_cb_wrapper
;
222 ctx
->reorder
->apply_change
= change_cb_wrapper
;
223 ctx
->reorder
->apply_truncate
= truncate_cb_wrapper
;
224 ctx
->reorder
->commit
= commit_cb_wrapper
;
225 ctx
->reorder
->message
= message_cb_wrapper
;
228 * To support streaming, we require start/stop/abort/commit/change
229 * callbacks. The message and truncate callbacks are optional, similar to
230 * regular output plugins. We however enable streaming when at least one
231 * of the methods is enabled so that we can easily identify missing
234 * We decide it here, but only check it later in the wrappers.
236 ctx
->streaming
= (ctx
->callbacks
.stream_start_cb
!= NULL
) ||
237 (ctx
->callbacks
.stream_stop_cb
!= NULL
) ||
238 (ctx
->callbacks
.stream_abort_cb
!= NULL
) ||
239 (ctx
->callbacks
.stream_commit_cb
!= NULL
) ||
240 (ctx
->callbacks
.stream_change_cb
!= NULL
) ||
241 (ctx
->callbacks
.stream_message_cb
!= NULL
) ||
242 (ctx
->callbacks
.stream_truncate_cb
!= NULL
);
245 * streaming callbacks
247 * stream_message and stream_truncate callbacks are optional, so we do not
248 * fail with ERROR when missing, but the wrappers simply do nothing. We
249 * must set the ReorderBuffer callbacks to something, otherwise the calls
250 * from there will crash (we don't want to move the checks there).
252 ctx
->reorder
->stream_start
= stream_start_cb_wrapper
;
253 ctx
->reorder
->stream_stop
= stream_stop_cb_wrapper
;
254 ctx
->reorder
->stream_abort
= stream_abort_cb_wrapper
;
255 ctx
->reorder
->stream_prepare
= stream_prepare_cb_wrapper
;
256 ctx
->reorder
->stream_commit
= stream_commit_cb_wrapper
;
257 ctx
->reorder
->stream_change
= stream_change_cb_wrapper
;
258 ctx
->reorder
->stream_message
= stream_message_cb_wrapper
;
259 ctx
->reorder
->stream_truncate
= stream_truncate_cb_wrapper
;
263 * To support two-phase logical decoding, we require
264 * begin_prepare/prepare/commit-prepare/abort-prepare callbacks. The
265 * filter_prepare callback is optional. We however enable two-phase
266 * logical decoding when at least one of the methods is enabled so that we
267 * can easily identify missing methods.
269 * We decide it here, but only check it later in the wrappers.
271 ctx
->twophase
= (ctx
->callbacks
.begin_prepare_cb
!= NULL
) ||
272 (ctx
->callbacks
.prepare_cb
!= NULL
) ||
273 (ctx
->callbacks
.commit_prepared_cb
!= NULL
) ||
274 (ctx
->callbacks
.rollback_prepared_cb
!= NULL
) ||
275 (ctx
->callbacks
.stream_prepare_cb
!= NULL
) ||
276 (ctx
->callbacks
.filter_prepare_cb
!= NULL
);
279 * Callback to support decoding at prepare time.
281 ctx
->reorder
->begin_prepare
= begin_prepare_cb_wrapper
;
282 ctx
->reorder
->prepare
= prepare_cb_wrapper
;
283 ctx
->reorder
->commit_prepared
= commit_prepared_cb_wrapper
;
284 ctx
->reorder
->rollback_prepared
= rollback_prepared_cb_wrapper
;
287 * Callback to support updating progress during sending data of a
288 * transaction (and its subtransactions) to the output plugin.
290 ctx
->reorder
->update_progress_txn
= update_progress_txn_cb_wrapper
;
292 ctx
->out
= makeStringInfo();
293 ctx
->prepare_write
= prepare_write
;
294 ctx
->write
= do_write
;
295 ctx
->update_progress
= update_progress
;
297 ctx
->output_plugin_options
= output_plugin_options
;
299 ctx
->fast_forward
= fast_forward
;
301 MemoryContextSwitchTo(old_context
);
307 * Create a new decoding context, for a new logical slot.
309 * plugin -- contains the name of the output plugin
310 * output_plugin_options -- contains options passed to the output plugin
311 * need_full_snapshot -- if true, must obtain a snapshot able to read all
312 * tables; if false, one that can read only catalogs is acceptable.
313 * restart_lsn -- if given as invalid, it's this routine's responsibility to
314 * mark WAL as reserved by setting a convenient restart_lsn for the slot.
315 * Otherwise, we set for decoding to start from the given LSN without
316 * marking WAL reserved beforehand. In that scenario, it's up to the
317 * caller to guarantee that WAL remains available.
318 * xl_routine -- XLogReaderRoutine for underlying XLogReader
319 * prepare_write, do_write, update_progress --
320 * callbacks that perform the use-case dependent, actual, work.
322 * Needs to be called while in a memory context that's at least as long lived
323 * as the decoding context because further memory contexts will be created
326 * Returns an initialized decoding context after calling the output plugin's
329 LogicalDecodingContext
*
330 CreateInitDecodingContext(const char *plugin
,
331 List
*output_plugin_options
,
332 bool need_full_snapshot
,
333 XLogRecPtr restart_lsn
,
334 XLogReaderRoutine
*xl_routine
,
335 LogicalOutputPluginWriterPrepareWrite prepare_write
,
336 LogicalOutputPluginWriterWrite do_write
,
337 LogicalOutputPluginWriterUpdateProgress update_progress
)
339 TransactionId xmin_horizon
= InvalidTransactionId
;
340 ReplicationSlot
*slot
;
341 NameData plugin_name
;
342 LogicalDecodingContext
*ctx
;
343 MemoryContext old_context
;
346 * On a standby, this check is also required while creating the slot.
347 * Check the comments in the function.
349 CheckLogicalDecodingRequirements();
351 /* shorter lines... */
352 slot
= MyReplicationSlot
;
354 /* first some sanity checks that are unlikely to be violated */
356 elog(ERROR
, "cannot perform logical decoding without an acquired slot");
359 elog(ERROR
, "cannot initialize logical decoding without a specified plugin");
361 /* Make sure the passed slot is suitable. These are user facing errors. */
362 if (SlotIsPhysical(slot
))
364 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
365 errmsg("cannot use physical replication slot for logical decoding")));
367 if (slot
->data
.database
!= MyDatabaseId
)
369 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
370 errmsg("replication slot \"%s\" was not created in this database",
371 NameStr(slot
->data
.name
))));
373 if (IsTransactionState() &&
374 GetTopTransactionIdIfAny() != InvalidTransactionId
)
376 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION
),
377 errmsg("cannot create logical replication slot in transaction that has performed writes")));
380 * Register output plugin name with slot. We need the mutex to avoid
381 * concurrent reading of a partially copied string. But we don't want any
382 * complicated code while holding a spinlock, so do namestrcpy() outside.
384 namestrcpy(&plugin_name
, plugin
);
385 SpinLockAcquire(&slot
->mutex
);
386 slot
->data
.plugin
= plugin_name
;
387 SpinLockRelease(&slot
->mutex
);
389 if (XLogRecPtrIsInvalid(restart_lsn
))
390 ReplicationSlotReserveWal();
393 SpinLockAcquire(&slot
->mutex
);
394 slot
->data
.restart_lsn
= restart_lsn
;
395 SpinLockRelease(&slot
->mutex
);
399 * This is a bit tricky: We need to determine a safe xmin horizon to start
400 * decoding from, to avoid starting from a running xacts record referring
401 * to xids whose rows have been vacuumed or pruned
402 * already. GetOldestSafeDecodingTransactionId() returns such a value, but
403 * without further interlock its return value might immediately be out of
406 * So we have to acquire the ProcArrayLock to prevent computation of new
407 * xmin horizons by other backends, get the safe decoding xid, and inform
408 * the slot machinery about the new limit. Once that's done the
409 * ProcArrayLock can be released as the slot machinery now is
410 * protecting against vacuum.
412 * Note that, temporarily, the data, not just the catalog, xmin has to be
413 * reserved if a data snapshot is to be exported. Otherwise the initial
414 * data snapshot created here is not guaranteed to be valid. After that
415 * the data xmin doesn't need to be managed anymore and the global xmin
416 * should be recomputed. As we are fine with losing the pegged data xmin
417 * after crash - no chance a snapshot would get exported anymore - we can
418 * get away with just setting the slot's
419 * effective_xmin. ReplicationSlotRelease will reset it again.
423 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
425 xmin_horizon
= GetOldestSafeDecodingTransactionId(!need_full_snapshot
);
427 SpinLockAcquire(&slot
->mutex
);
428 slot
->effective_catalog_xmin
= xmin_horizon
;
429 slot
->data
.catalog_xmin
= xmin_horizon
;
430 if (need_full_snapshot
)
431 slot
->effective_xmin
= xmin_horizon
;
432 SpinLockRelease(&slot
->mutex
);
434 ReplicationSlotsComputeRequiredXmin(true);
436 LWLockRelease(ProcArrayLock
);
438 ReplicationSlotMarkDirty();
439 ReplicationSlotSave();
441 ctx
= StartupDecodingContext(NIL
, restart_lsn
, xmin_horizon
,
442 need_full_snapshot
, false, true,
443 xl_routine
, prepare_write
, do_write
,
446 /* call output plugin initialization callback */
447 old_context
= MemoryContextSwitchTo(ctx
->context
);
448 if (ctx
->callbacks
.startup_cb
!= NULL
)
449 startup_cb_wrapper(ctx
, &ctx
->options
, true);
450 MemoryContextSwitchTo(old_context
);
453 * We allow decoding of prepared transactions when the two_phase is
454 * enabled at the time of slot creation, or when the two_phase option is
455 * given at the streaming start, provided the plugin supports all the
456 * callbacks for two-phase.
458 ctx
->twophase
&= slot
->data
.two_phase
;
460 ctx
->reorder
->output_rewrites
= ctx
->options
.receive_rewrites
;
466 * Create a new decoding context, for a logical slot that has previously been
470 * The LSN at which to start decoding. If InvalidXLogRecPtr, restart
471 * from the slot's confirmed_flush; otherwise, start from the specified
472 * location (but move it forwards to confirmed_flush if it's older than
475 * output_plugin_options
476 * options passed to the output plugin.
479 * bypass the generation of logical changes.
482 * XLogReaderRoutine used by underlying xlogreader
484 * prepare_write, do_write, update_progress
485 * callbacks that have to be filled to perform the use-case dependent,
488 * Needs to be called while in a memory context that's at least as long lived
489 * as the decoding context because further memory contexts will be created
492 * Returns an initialized decoding context after calling the output plugin's
495 LogicalDecodingContext
*
496 CreateDecodingContext(XLogRecPtr start_lsn
,
497 List
*output_plugin_options
,
499 XLogReaderRoutine
*xl_routine
,
500 LogicalOutputPluginWriterPrepareWrite prepare_write
,
501 LogicalOutputPluginWriterWrite do_write
,
502 LogicalOutputPluginWriterUpdateProgress update_progress
)
504 LogicalDecodingContext
*ctx
;
505 ReplicationSlot
*slot
;
506 MemoryContext old_context
;
508 /* shorter lines... */
509 slot
= MyReplicationSlot
;
511 /* first some sanity checks that are unlikely to be violated */
513 elog(ERROR
, "cannot perform logical decoding without an acquired slot");
515 /* make sure the passed slot is suitable, these are user facing errors */
516 if (SlotIsPhysical(slot
))
518 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
519 errmsg("cannot use physical replication slot for logical decoding")));
522 * We need to access the system tables during decoding to build the
523 * logical changes unless we are in fast_forward mode where no changes are
526 if (slot
->data
.database
!= MyDatabaseId
&& !fast_forward
)
528 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
529 errmsg("replication slot \"%s\" was not created in this database",
530 NameStr(slot
->data
.name
))));
533 * The slots being synced from the primary can't be used for decoding as
534 * they are used after failover. However, we do allow advancing the LSNs
535 * during the synchronization of slots. See update_local_synced_slot.
537 if (RecoveryInProgress() && slot
->data
.synced
&& !IsSyncingReplicationSlots())
539 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
540 errmsg("cannot use replication slot \"%s\" for logical decoding",
541 NameStr(slot
->data
.name
)),
542 errdetail("This replication slot is being synchronized from the primary server."),
543 errhint("Specify another replication slot."));
546 * Check if slot has been invalidated due to max_slot_wal_keep_size. Avoid
547 * "cannot get changes" wording in this errmsg because that'd be
548 * confusingly ambiguous about no changes being available when called from
549 * pg_logical_slot_get_changes_guts().
551 if (MyReplicationSlot
->data
.invalidated
== RS_INVAL_WAL_REMOVED
)
553 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
554 errmsg("can no longer get changes from replication slot \"%s\"",
555 NameStr(MyReplicationSlot
->data
.name
)),
556 errdetail("This slot has been invalidated because it exceeded the maximum reserved size.")));
558 if (MyReplicationSlot
->data
.invalidated
!= RS_INVAL_NONE
)
560 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
561 errmsg("can no longer get changes from replication slot \"%s\"",
562 NameStr(MyReplicationSlot
->data
.name
)),
563 errdetail("This slot has been invalidated because it was conflicting with recovery.")));
565 Assert(MyReplicationSlot
->data
.invalidated
== RS_INVAL_NONE
);
566 Assert(MyReplicationSlot
->data
.restart_lsn
!= InvalidXLogRecPtr
);
568 if (start_lsn
== InvalidXLogRecPtr
)
570 /* continue from last position */
571 start_lsn
= slot
->data
.confirmed_flush
;
573 else if (start_lsn
< slot
->data
.confirmed_flush
)
576 * It might seem like we should error out in this case, but it's
577 * pretty common for a client to acknowledge a LSN it doesn't have to
578 * do anything for, and thus didn't store persistently, because the
579 * xlog records didn't result in anything relevant for logical
580 * decoding. Clients have to be able to do that to support synchronous
583 * Starting at a different LSN than requested might not catch certain
584 * kinds of client errors; so the client may wish to check that
585 * confirmed_flush_lsn matches its expectations.
587 elog(LOG
, "%X/%X has been already streamed, forwarding to %X/%X",
588 LSN_FORMAT_ARGS(start_lsn
),
589 LSN_FORMAT_ARGS(slot
->data
.confirmed_flush
));
591 start_lsn
= slot
->data
.confirmed_flush
;
594 ctx
= StartupDecodingContext(output_plugin_options
,
595 start_lsn
, InvalidTransactionId
, false,
596 fast_forward
, false, xl_routine
, prepare_write
,
597 do_write
, update_progress
);
599 /* call output plugin initialization callback */
600 old_context
= MemoryContextSwitchTo(ctx
->context
);
601 if (ctx
->callbacks
.startup_cb
!= NULL
)
602 startup_cb_wrapper(ctx
, &ctx
->options
, false);
603 MemoryContextSwitchTo(old_context
);
606 * We allow decoding of prepared transactions when the two_phase is
607 * enabled at the time of slot creation, or when the two_phase option is
608 * given at the streaming start, provided the plugin supports all the
609 * callbacks for two-phase.
611 ctx
->twophase
&= (slot
->data
.two_phase
|| ctx
->twophase_opt_given
);
613 /* Mark slot to allow two_phase decoding if not already marked */
614 if (ctx
->twophase
&& !slot
->data
.two_phase
)
616 SpinLockAcquire(&slot
->mutex
);
617 slot
->data
.two_phase
= true;
618 slot
->data
.two_phase_at
= start_lsn
;
619 SpinLockRelease(&slot
->mutex
);
620 ReplicationSlotMarkDirty();
621 ReplicationSlotSave();
622 SnapBuildSetTwoPhaseAt(ctx
->snapshot_builder
, start_lsn
);
625 ctx
->reorder
->output_rewrites
= ctx
->options
.receive_rewrites
;
628 (errmsg("starting logical decoding for slot \"%s\"",
629 NameStr(slot
->data
.name
)),
630 errdetail("Streaming transactions committing after %X/%X, reading WAL from %X/%X.",
631 LSN_FORMAT_ARGS(slot
->data
.confirmed_flush
),
632 LSN_FORMAT_ARGS(slot
->data
.restart_lsn
))));
638 * Returns true if a consistent initial decoding snapshot has been built.
641 DecodingContextReady(LogicalDecodingContext
*ctx
)
643 return SnapBuildCurrentState(ctx
->snapshot_builder
) == SNAPBUILD_CONSISTENT
;
647 * Read from the decoding slot, until it is ready to start extracting changes.
650 DecodingContextFindStartpoint(LogicalDecodingContext
*ctx
)
652 ReplicationSlot
*slot
= ctx
->slot
;
654 /* Initialize from where to start reading WAL. */
655 XLogBeginRead(ctx
->reader
, slot
->data
.restart_lsn
);
657 elog(DEBUG1
, "searching for logical decoding starting point, starting at %X/%X",
658 LSN_FORMAT_ARGS(slot
->data
.restart_lsn
));
660 /* Wait for a consistent starting point */
666 /* the read_page callback waits for new WAL */
667 record
= XLogReadRecord(ctx
->reader
, &err
);
669 elog(ERROR
, "could not find logical decoding starting point: %s", err
);
671 elog(ERROR
, "could not find logical decoding starting point");
673 LogicalDecodingProcessRecord(ctx
, ctx
->reader
);
675 /* only continue till we found a consistent spot */
676 if (DecodingContextReady(ctx
))
679 CHECK_FOR_INTERRUPTS();
682 SpinLockAcquire(&slot
->mutex
);
683 slot
->data
.confirmed_flush
= ctx
->reader
->EndRecPtr
;
684 if (slot
->data
.two_phase
)
685 slot
->data
.two_phase_at
= ctx
->reader
->EndRecPtr
;
686 SpinLockRelease(&slot
->mutex
);
690 * Free a previously allocated decoding context, invoking the shutdown
691 * callback if necessary.
694 FreeDecodingContext(LogicalDecodingContext
*ctx
)
696 if (ctx
->callbacks
.shutdown_cb
!= NULL
)
697 shutdown_cb_wrapper(ctx
);
699 ReorderBufferFree(ctx
->reorder
);
700 FreeSnapshotBuilder(ctx
->snapshot_builder
);
701 XLogReaderFree(ctx
->reader
);
702 MemoryContextDelete(ctx
->context
);
706 * Prepare a write using the context's output routine.
709 OutputPluginPrepareWrite(struct LogicalDecodingContext
*ctx
, bool last_write
)
711 if (!ctx
->accept_writes
)
712 elog(ERROR
, "writes are only accepted in commit, begin and change callbacks");
714 ctx
->prepare_write(ctx
, ctx
->write_location
, ctx
->write_xid
, last_write
);
715 ctx
->prepared_write
= true;
719 * Perform a write using the context's output routine.
722 OutputPluginWrite(struct LogicalDecodingContext
*ctx
, bool last_write
)
724 if (!ctx
->prepared_write
)
725 elog(ERROR
, "OutputPluginPrepareWrite needs to be called before OutputPluginWrite");
727 ctx
->write(ctx
, ctx
->write_location
, ctx
->write_xid
, last_write
);
728 ctx
->prepared_write
= false;
732 * Update progress tracking (if supported).
735 OutputPluginUpdateProgress(struct LogicalDecodingContext
*ctx
,
738 if (!ctx
->update_progress
)
741 ctx
->update_progress(ctx
, ctx
->write_location
, ctx
->write_xid
,
746 * Load the output plugin, lookup its output plugin init function, and check
747 * that it provides the required callbacks.
750 LoadOutputPlugin(OutputPluginCallbacks
*callbacks
, const char *plugin
)
752 LogicalOutputPluginInit plugin_init
;
754 plugin_init
= (LogicalOutputPluginInit
)
755 load_external_function(plugin
, "_PG_output_plugin_init", false, NULL
);
757 if (plugin_init
== NULL
)
758 elog(ERROR
, "output plugins have to declare the _PG_output_plugin_init symbol");
760 /* ask the output plugin to fill the callback struct */
761 plugin_init(callbacks
);
763 if (callbacks
->begin_cb
== NULL
)
764 elog(ERROR
, "output plugins have to register a begin callback");
765 if (callbacks
->change_cb
== NULL
)
766 elog(ERROR
, "output plugins have to register a change callback");
767 if (callbacks
->commit_cb
== NULL
)
768 elog(ERROR
, "output plugins have to register a commit callback");
772 output_plugin_error_callback(void *arg
)
774 LogicalErrorCallbackState
*state
= (LogicalErrorCallbackState
*) arg
;
776 /* not all callbacks have an associated LSN */
777 if (state
->report_location
!= InvalidXLogRecPtr
)
778 errcontext("slot \"%s\", output plugin \"%s\", in the %s callback, associated LSN %X/%X",
779 NameStr(state
->ctx
->slot
->data
.name
),
780 NameStr(state
->ctx
->slot
->data
.plugin
),
781 state
->callback_name
,
782 LSN_FORMAT_ARGS(state
->report_location
));
784 errcontext("slot \"%s\", output plugin \"%s\", in the %s callback",
785 NameStr(state
->ctx
->slot
->data
.name
),
786 NameStr(state
->ctx
->slot
->data
.plugin
),
787 state
->callback_name
);
791 startup_cb_wrapper(LogicalDecodingContext
*ctx
, OutputPluginOptions
*opt
, bool is_init
)
793 LogicalErrorCallbackState state
;
794 ErrorContextCallback errcallback
;
796 Assert(!ctx
->fast_forward
);
798 /* Push callback + info on the error context stack */
800 state
.callback_name
= "startup";
801 state
.report_location
= InvalidXLogRecPtr
;
802 errcallback
.callback
= output_plugin_error_callback
;
803 errcallback
.arg
= &state
;
804 errcallback
.previous
= error_context_stack
;
805 error_context_stack
= &errcallback
;
807 /* set output state */
808 ctx
->accept_writes
= false;
809 ctx
->end_xact
= false;
811 /* do the actual work: call callback */
812 ctx
->callbacks
.startup_cb(ctx
, opt
, is_init
);
814 /* Pop the error context stack */
815 error_context_stack
= errcallback
.previous
;
819 shutdown_cb_wrapper(LogicalDecodingContext
*ctx
)
821 LogicalErrorCallbackState state
;
822 ErrorContextCallback errcallback
;
824 Assert(!ctx
->fast_forward
);
826 /* Push callback + info on the error context stack */
828 state
.callback_name
= "shutdown";
829 state
.report_location
= InvalidXLogRecPtr
;
830 errcallback
.callback
= output_plugin_error_callback
;
831 errcallback
.arg
= &state
;
832 errcallback
.previous
= error_context_stack
;
833 error_context_stack
= &errcallback
;
835 /* set output state */
836 ctx
->accept_writes
= false;
837 ctx
->end_xact
= false;
839 /* do the actual work: call callback */
840 ctx
->callbacks
.shutdown_cb(ctx
);
842 /* Pop the error context stack */
843 error_context_stack
= errcallback
.previous
;
848 * Callbacks for ReorderBuffer which add in some more information and then call
849 * output_plugin.h plugins.
852 begin_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
)
854 LogicalDecodingContext
*ctx
= cache
->private_data
;
855 LogicalErrorCallbackState state
;
856 ErrorContextCallback errcallback
;
858 Assert(!ctx
->fast_forward
);
860 /* Push callback + info on the error context stack */
862 state
.callback_name
= "begin";
863 state
.report_location
= txn
->first_lsn
;
864 errcallback
.callback
= output_plugin_error_callback
;
865 errcallback
.arg
= &state
;
866 errcallback
.previous
= error_context_stack
;
867 error_context_stack
= &errcallback
;
869 /* set output state */
870 ctx
->accept_writes
= true;
871 ctx
->write_xid
= txn
->xid
;
872 ctx
->write_location
= txn
->first_lsn
;
873 ctx
->end_xact
= false;
875 /* do the actual work: call callback */
876 ctx
->callbacks
.begin_cb(ctx
, txn
);
878 /* Pop the error context stack */
879 error_context_stack
= errcallback
.previous
;
883 commit_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
884 XLogRecPtr commit_lsn
)
886 LogicalDecodingContext
*ctx
= cache
->private_data
;
887 LogicalErrorCallbackState state
;
888 ErrorContextCallback errcallback
;
890 Assert(!ctx
->fast_forward
);
892 /* Push callback + info on the error context stack */
894 state
.callback_name
= "commit";
895 state
.report_location
= txn
->final_lsn
; /* beginning of commit record */
896 errcallback
.callback
= output_plugin_error_callback
;
897 errcallback
.arg
= &state
;
898 errcallback
.previous
= error_context_stack
;
899 error_context_stack
= &errcallback
;
901 /* set output state */
902 ctx
->accept_writes
= true;
903 ctx
->write_xid
= txn
->xid
;
904 ctx
->write_location
= txn
->end_lsn
; /* points to the end of the record */
905 ctx
->end_xact
= true;
907 /* do the actual work: call callback */
908 ctx
->callbacks
.commit_cb(ctx
, txn
, commit_lsn
);
910 /* Pop the error context stack */
911 error_context_stack
= errcallback
.previous
;
915 * The functionality of begin_prepare is quite similar to begin with the
916 * exception that this will have gid (global transaction id) information which
917 * can be used by plugin. Now, we thought about extending the existing begin
918 * but that would break the replication protocol and additionally this looks
922 begin_prepare_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
)
924 LogicalDecodingContext
*ctx
= cache
->private_data
;
925 LogicalErrorCallbackState state
;
926 ErrorContextCallback errcallback
;
928 Assert(!ctx
->fast_forward
);
930 /* We're only supposed to call this when two-phase commits are supported */
931 Assert(ctx
->twophase
);
933 /* Push callback + info on the error context stack */
935 state
.callback_name
= "begin_prepare";
936 state
.report_location
= txn
->first_lsn
;
937 errcallback
.callback
= output_plugin_error_callback
;
938 errcallback
.arg
= &state
;
939 errcallback
.previous
= error_context_stack
;
940 error_context_stack
= &errcallback
;
942 /* set output state */
943 ctx
->accept_writes
= true;
944 ctx
->write_xid
= txn
->xid
;
945 ctx
->write_location
= txn
->first_lsn
;
946 ctx
->end_xact
= false;
949 * If the plugin supports two-phase commits then begin prepare callback is
952 if (ctx
->callbacks
.begin_prepare_cb
== NULL
)
954 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
955 errmsg("logical replication at prepare time requires a %s callback",
956 "begin_prepare_cb")));
958 /* do the actual work: call callback */
959 ctx
->callbacks
.begin_prepare_cb(ctx
, txn
);
961 /* Pop the error context stack */
962 error_context_stack
= errcallback
.previous
;
966 prepare_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
967 XLogRecPtr prepare_lsn
)
969 LogicalDecodingContext
*ctx
= cache
->private_data
;
970 LogicalErrorCallbackState state
;
971 ErrorContextCallback errcallback
;
973 Assert(!ctx
->fast_forward
);
975 /* We're only supposed to call this when two-phase commits are supported */
976 Assert(ctx
->twophase
);
978 /* Push callback + info on the error context stack */
980 state
.callback_name
= "prepare";
981 state
.report_location
= txn
->final_lsn
; /* beginning of prepare record */
982 errcallback
.callback
= output_plugin_error_callback
;
983 errcallback
.arg
= &state
;
984 errcallback
.previous
= error_context_stack
;
985 error_context_stack
= &errcallback
;
987 /* set output state */
988 ctx
->accept_writes
= true;
989 ctx
->write_xid
= txn
->xid
;
990 ctx
->write_location
= txn
->end_lsn
; /* points to the end of the record */
991 ctx
->end_xact
= true;
994 * If the plugin supports two-phase commits then prepare callback is
997 if (ctx
->callbacks
.prepare_cb
== NULL
)
999 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
1000 errmsg("logical replication at prepare time requires a %s callback",
1003 /* do the actual work: call callback */
1004 ctx
->callbacks
.prepare_cb(ctx
, txn
, prepare_lsn
);
1006 /* Pop the error context stack */
1007 error_context_stack
= errcallback
.previous
;
1011 commit_prepared_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1012 XLogRecPtr commit_lsn
)
1014 LogicalDecodingContext
*ctx
= cache
->private_data
;
1015 LogicalErrorCallbackState state
;
1016 ErrorContextCallback errcallback
;
1018 Assert(!ctx
->fast_forward
);
1020 /* We're only supposed to call this when two-phase commits are supported */
1021 Assert(ctx
->twophase
);
1023 /* Push callback + info on the error context stack */
1025 state
.callback_name
= "commit_prepared";
1026 state
.report_location
= txn
->final_lsn
; /* beginning of commit record */
1027 errcallback
.callback
= output_plugin_error_callback
;
1028 errcallback
.arg
= &state
;
1029 errcallback
.previous
= error_context_stack
;
1030 error_context_stack
= &errcallback
;
1032 /* set output state */
1033 ctx
->accept_writes
= true;
1034 ctx
->write_xid
= txn
->xid
;
1035 ctx
->write_location
= txn
->end_lsn
; /* points to the end of the record */
1036 ctx
->end_xact
= true;
1039 * If the plugin support two-phase commits then commit prepared callback
1042 if (ctx
->callbacks
.commit_prepared_cb
== NULL
)
1044 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
1045 errmsg("logical replication at prepare time requires a %s callback",
1046 "commit_prepared_cb")));
1048 /* do the actual work: call callback */
1049 ctx
->callbacks
.commit_prepared_cb(ctx
, txn
, commit_lsn
);
1051 /* Pop the error context stack */
1052 error_context_stack
= errcallback
.previous
;
1056 rollback_prepared_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1057 XLogRecPtr prepare_end_lsn
,
1058 TimestampTz prepare_time
)
1060 LogicalDecodingContext
*ctx
= cache
->private_data
;
1061 LogicalErrorCallbackState state
;
1062 ErrorContextCallback errcallback
;
1064 Assert(!ctx
->fast_forward
);
1066 /* We're only supposed to call this when two-phase commits are supported */
1067 Assert(ctx
->twophase
);
1069 /* Push callback + info on the error context stack */
1071 state
.callback_name
= "rollback_prepared";
1072 state
.report_location
= txn
->final_lsn
; /* beginning of commit record */
1073 errcallback
.callback
= output_plugin_error_callback
;
1074 errcallback
.arg
= &state
;
1075 errcallback
.previous
= error_context_stack
;
1076 error_context_stack
= &errcallback
;
1078 /* set output state */
1079 ctx
->accept_writes
= true;
1080 ctx
->write_xid
= txn
->xid
;
1081 ctx
->write_location
= txn
->end_lsn
; /* points to the end of the record */
1082 ctx
->end_xact
= true;
1085 * If the plugin support two-phase commits then rollback prepared callback
1088 if (ctx
->callbacks
.rollback_prepared_cb
== NULL
)
1090 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
1091 errmsg("logical replication at prepare time requires a %s callback",
1092 "rollback_prepared_cb")));
1094 /* do the actual work: call callback */
1095 ctx
->callbacks
.rollback_prepared_cb(ctx
, txn
, prepare_end_lsn
,
1098 /* Pop the error context stack */
1099 error_context_stack
= errcallback
.previous
;
1103 change_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1104 Relation relation
, ReorderBufferChange
*change
)
1106 LogicalDecodingContext
*ctx
= cache
->private_data
;
1107 LogicalErrorCallbackState state
;
1108 ErrorContextCallback errcallback
;
1110 Assert(!ctx
->fast_forward
);
1112 /* Push callback + info on the error context stack */
1114 state
.callback_name
= "change";
1115 state
.report_location
= change
->lsn
;
1116 errcallback
.callback
= output_plugin_error_callback
;
1117 errcallback
.arg
= &state
;
1118 errcallback
.previous
= error_context_stack
;
1119 error_context_stack
= &errcallback
;
1121 /* set output state */
1122 ctx
->accept_writes
= true;
1123 ctx
->write_xid
= txn
->xid
;
1126 * Report this change's lsn so replies from clients can give an up-to-date
1127 * answer. This won't ever be enough (and shouldn't be!) to confirm
1128 * receipt of this transaction, but it might allow another transaction's
1129 * commit to be confirmed with one message.
1131 ctx
->write_location
= change
->lsn
;
1133 ctx
->end_xact
= false;
1135 ctx
->callbacks
.change_cb(ctx
, txn
, relation
, change
);
1137 /* Pop the error context stack */
1138 error_context_stack
= errcallback
.previous
;
1142 truncate_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1143 int nrelations
, Relation relations
[], ReorderBufferChange
*change
)
1145 LogicalDecodingContext
*ctx
= cache
->private_data
;
1146 LogicalErrorCallbackState state
;
1147 ErrorContextCallback errcallback
;
1149 Assert(!ctx
->fast_forward
);
1151 if (!ctx
->callbacks
.truncate_cb
)
1154 /* Push callback + info on the error context stack */
1156 state
.callback_name
= "truncate";
1157 state
.report_location
= change
->lsn
;
1158 errcallback
.callback
= output_plugin_error_callback
;
1159 errcallback
.arg
= &state
;
1160 errcallback
.previous
= error_context_stack
;
1161 error_context_stack
= &errcallback
;
1163 /* set output state */
1164 ctx
->accept_writes
= true;
1165 ctx
->write_xid
= txn
->xid
;
1168 * Report this change's lsn so replies from clients can give an up-to-date
1169 * answer. This won't ever be enough (and shouldn't be!) to confirm
1170 * receipt of this transaction, but it might allow another transaction's
1171 * commit to be confirmed with one message.
1173 ctx
->write_location
= change
->lsn
;
1175 ctx
->end_xact
= false;
1177 ctx
->callbacks
.truncate_cb(ctx
, txn
, nrelations
, relations
, change
);
1179 /* Pop the error context stack */
1180 error_context_stack
= errcallback
.previous
;
1184 filter_prepare_cb_wrapper(LogicalDecodingContext
*ctx
, TransactionId xid
,
1187 LogicalErrorCallbackState state
;
1188 ErrorContextCallback errcallback
;
1191 Assert(!ctx
->fast_forward
);
1193 /* Push callback + info on the error context stack */
1195 state
.callback_name
= "filter_prepare";
1196 state
.report_location
= InvalidXLogRecPtr
;
1197 errcallback
.callback
= output_plugin_error_callback
;
1198 errcallback
.arg
= &state
;
1199 errcallback
.previous
= error_context_stack
;
1200 error_context_stack
= &errcallback
;
1202 /* set output state */
1203 ctx
->accept_writes
= false;
1204 ctx
->end_xact
= false;
1206 /* do the actual work: call callback */
1207 ret
= ctx
->callbacks
.filter_prepare_cb(ctx
, xid
, gid
);
1209 /* Pop the error context stack */
1210 error_context_stack
= errcallback
.previous
;
1216 filter_by_origin_cb_wrapper(LogicalDecodingContext
*ctx
, RepOriginId origin_id
)
1218 LogicalErrorCallbackState state
;
1219 ErrorContextCallback errcallback
;
1222 Assert(!ctx
->fast_forward
);
1224 /* Push callback + info on the error context stack */
1226 state
.callback_name
= "filter_by_origin";
1227 state
.report_location
= InvalidXLogRecPtr
;
1228 errcallback
.callback
= output_plugin_error_callback
;
1229 errcallback
.arg
= &state
;
1230 errcallback
.previous
= error_context_stack
;
1231 error_context_stack
= &errcallback
;
1233 /* set output state */
1234 ctx
->accept_writes
= false;
1235 ctx
->end_xact
= false;
1237 /* do the actual work: call callback */
1238 ret
= ctx
->callbacks
.filter_by_origin_cb(ctx
, origin_id
);
1240 /* Pop the error context stack */
1241 error_context_stack
= errcallback
.previous
;
1247 message_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1248 XLogRecPtr message_lsn
, bool transactional
,
1249 const char *prefix
, Size message_size
, const char *message
)
1251 LogicalDecodingContext
*ctx
= cache
->private_data
;
1252 LogicalErrorCallbackState state
;
1253 ErrorContextCallback errcallback
;
1255 Assert(!ctx
->fast_forward
);
1257 if (ctx
->callbacks
.message_cb
== NULL
)
1260 /* Push callback + info on the error context stack */
1262 state
.callback_name
= "message";
1263 state
.report_location
= message_lsn
;
1264 errcallback
.callback
= output_plugin_error_callback
;
1265 errcallback
.arg
= &state
;
1266 errcallback
.previous
= error_context_stack
;
1267 error_context_stack
= &errcallback
;
1269 /* set output state */
1270 ctx
->accept_writes
= true;
1271 ctx
->write_xid
= txn
!= NULL
? txn
->xid
: InvalidTransactionId
;
1272 ctx
->write_location
= message_lsn
;
1273 ctx
->end_xact
= false;
1275 /* do the actual work: call callback */
1276 ctx
->callbacks
.message_cb(ctx
, txn
, message_lsn
, transactional
, prefix
,
1277 message_size
, message
);
1279 /* Pop the error context stack */
1280 error_context_stack
= errcallback
.previous
;
1284 stream_start_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1285 XLogRecPtr first_lsn
)
1287 LogicalDecodingContext
*ctx
= cache
->private_data
;
1288 LogicalErrorCallbackState state
;
1289 ErrorContextCallback errcallback
;
1291 Assert(!ctx
->fast_forward
);
1293 /* We're only supposed to call this when streaming is supported. */
1294 Assert(ctx
->streaming
);
1296 /* Push callback + info on the error context stack */
1298 state
.callback_name
= "stream_start";
1299 state
.report_location
= first_lsn
;
1300 errcallback
.callback
= output_plugin_error_callback
;
1301 errcallback
.arg
= &state
;
1302 errcallback
.previous
= error_context_stack
;
1303 error_context_stack
= &errcallback
;
1305 /* set output state */
1306 ctx
->accept_writes
= true;
1307 ctx
->write_xid
= txn
->xid
;
1310 * Report this message's lsn so replies from clients can give an
1311 * up-to-date answer. This won't ever be enough (and shouldn't be!) to
1312 * confirm receipt of this transaction, but it might allow another
1313 * transaction's commit to be confirmed with one message.
1315 ctx
->write_location
= first_lsn
;
1317 ctx
->end_xact
= false;
1319 /* in streaming mode, stream_start_cb is required */
1320 if (ctx
->callbacks
.stream_start_cb
== NULL
)
1322 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
1323 errmsg("logical streaming requires a %s callback",
1324 "stream_start_cb")));
1326 ctx
->callbacks
.stream_start_cb(ctx
, txn
);
1328 /* Pop the error context stack */
1329 error_context_stack
= errcallback
.previous
;
1333 stream_stop_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1334 XLogRecPtr last_lsn
)
1336 LogicalDecodingContext
*ctx
= cache
->private_data
;
1337 LogicalErrorCallbackState state
;
1338 ErrorContextCallback errcallback
;
1340 Assert(!ctx
->fast_forward
);
1342 /* We're only supposed to call this when streaming is supported. */
1343 Assert(ctx
->streaming
);
1345 /* Push callback + info on the error context stack */
1347 state
.callback_name
= "stream_stop";
1348 state
.report_location
= last_lsn
;
1349 errcallback
.callback
= output_plugin_error_callback
;
1350 errcallback
.arg
= &state
;
1351 errcallback
.previous
= error_context_stack
;
1352 error_context_stack
= &errcallback
;
1354 /* set output state */
1355 ctx
->accept_writes
= true;
1356 ctx
->write_xid
= txn
->xid
;
1359 * Report this message's lsn so replies from clients can give an
1360 * up-to-date answer. This won't ever be enough (and shouldn't be!) to
1361 * confirm receipt of this transaction, but it might allow another
1362 * transaction's commit to be confirmed with one message.
1364 ctx
->write_location
= last_lsn
;
1366 ctx
->end_xact
= false;
1368 /* in streaming mode, stream_stop_cb is required */
1369 if (ctx
->callbacks
.stream_stop_cb
== NULL
)
1371 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
1372 errmsg("logical streaming requires a %s callback",
1373 "stream_stop_cb")));
1375 ctx
->callbacks
.stream_stop_cb(ctx
, txn
);
1377 /* Pop the error context stack */
1378 error_context_stack
= errcallback
.previous
;
1382 stream_abort_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1383 XLogRecPtr abort_lsn
)
1385 LogicalDecodingContext
*ctx
= cache
->private_data
;
1386 LogicalErrorCallbackState state
;
1387 ErrorContextCallback errcallback
;
1389 Assert(!ctx
->fast_forward
);
1391 /* We're only supposed to call this when streaming is supported. */
1392 Assert(ctx
->streaming
);
1394 /* Push callback + info on the error context stack */
1396 state
.callback_name
= "stream_abort";
1397 state
.report_location
= abort_lsn
;
1398 errcallback
.callback
= output_plugin_error_callback
;
1399 errcallback
.arg
= &state
;
1400 errcallback
.previous
= error_context_stack
;
1401 error_context_stack
= &errcallback
;
1403 /* set output state */
1404 ctx
->accept_writes
= true;
1405 ctx
->write_xid
= txn
->xid
;
1406 ctx
->write_location
= abort_lsn
;
1407 ctx
->end_xact
= true;
1409 /* in streaming mode, stream_abort_cb is required */
1410 if (ctx
->callbacks
.stream_abort_cb
== NULL
)
1412 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
1413 errmsg("logical streaming requires a %s callback",
1414 "stream_abort_cb")));
1416 ctx
->callbacks
.stream_abort_cb(ctx
, txn
, abort_lsn
);
1418 /* Pop the error context stack */
1419 error_context_stack
= errcallback
.previous
;
1423 stream_prepare_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1424 XLogRecPtr prepare_lsn
)
1426 LogicalDecodingContext
*ctx
= cache
->private_data
;
1427 LogicalErrorCallbackState state
;
1428 ErrorContextCallback errcallback
;
1430 Assert(!ctx
->fast_forward
);
1433 * We're only supposed to call this when streaming and two-phase commits
1436 Assert(ctx
->streaming
);
1437 Assert(ctx
->twophase
);
1439 /* Push callback + info on the error context stack */
1441 state
.callback_name
= "stream_prepare";
1442 state
.report_location
= txn
->final_lsn
;
1443 errcallback
.callback
= output_plugin_error_callback
;
1444 errcallback
.arg
= &state
;
1445 errcallback
.previous
= error_context_stack
;
1446 error_context_stack
= &errcallback
;
1448 /* set output state */
1449 ctx
->accept_writes
= true;
1450 ctx
->write_xid
= txn
->xid
;
1451 ctx
->write_location
= txn
->end_lsn
;
1452 ctx
->end_xact
= true;
1454 /* in streaming mode with two-phase commits, stream_prepare_cb is required */
1455 if (ctx
->callbacks
.stream_prepare_cb
== NULL
)
1457 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
1458 errmsg("logical streaming at prepare time requires a %s callback",
1459 "stream_prepare_cb")));
1461 ctx
->callbacks
.stream_prepare_cb(ctx
, txn
, prepare_lsn
);
1463 /* Pop the error context stack */
1464 error_context_stack
= errcallback
.previous
;
1468 stream_commit_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1469 XLogRecPtr commit_lsn
)
1471 LogicalDecodingContext
*ctx
= cache
->private_data
;
1472 LogicalErrorCallbackState state
;
1473 ErrorContextCallback errcallback
;
1475 Assert(!ctx
->fast_forward
);
1477 /* We're only supposed to call this when streaming is supported. */
1478 Assert(ctx
->streaming
);
1480 /* Push callback + info on the error context stack */
1482 state
.callback_name
= "stream_commit";
1483 state
.report_location
= txn
->final_lsn
;
1484 errcallback
.callback
= output_plugin_error_callback
;
1485 errcallback
.arg
= &state
;
1486 errcallback
.previous
= error_context_stack
;
1487 error_context_stack
= &errcallback
;
1489 /* set output state */
1490 ctx
->accept_writes
= true;
1491 ctx
->write_xid
= txn
->xid
;
1492 ctx
->write_location
= txn
->end_lsn
;
1493 ctx
->end_xact
= true;
1495 /* in streaming mode, stream_commit_cb is required */
1496 if (ctx
->callbacks
.stream_commit_cb
== NULL
)
1498 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
1499 errmsg("logical streaming requires a %s callback",
1500 "stream_commit_cb")));
1502 ctx
->callbacks
.stream_commit_cb(ctx
, txn
, commit_lsn
);
1504 /* Pop the error context stack */
1505 error_context_stack
= errcallback
.previous
;
1509 stream_change_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1510 Relation relation
, ReorderBufferChange
*change
)
1512 LogicalDecodingContext
*ctx
= cache
->private_data
;
1513 LogicalErrorCallbackState state
;
1514 ErrorContextCallback errcallback
;
1516 Assert(!ctx
->fast_forward
);
1518 /* We're only supposed to call this when streaming is supported. */
1519 Assert(ctx
->streaming
);
1521 /* Push callback + info on the error context stack */
1523 state
.callback_name
= "stream_change";
1524 state
.report_location
= change
->lsn
;
1525 errcallback
.callback
= output_plugin_error_callback
;
1526 errcallback
.arg
= &state
;
1527 errcallback
.previous
= error_context_stack
;
1528 error_context_stack
= &errcallback
;
1530 /* set output state */
1531 ctx
->accept_writes
= true;
1532 ctx
->write_xid
= txn
->xid
;
1535 * Report this change's lsn so replies from clients can give an up-to-date
1536 * answer. This won't ever be enough (and shouldn't be!) to confirm
1537 * receipt of this transaction, but it might allow another transaction's
1538 * commit to be confirmed with one message.
1540 ctx
->write_location
= change
->lsn
;
1542 ctx
->end_xact
= false;
1544 /* in streaming mode, stream_change_cb is required */
1545 if (ctx
->callbacks
.stream_change_cb
== NULL
)
1547 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
1548 errmsg("logical streaming requires a %s callback",
1549 "stream_change_cb")));
1551 ctx
->callbacks
.stream_change_cb(ctx
, txn
, relation
, change
);
1553 /* Pop the error context stack */
1554 error_context_stack
= errcallback
.previous
;
1558 stream_message_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1559 XLogRecPtr message_lsn
, bool transactional
,
1560 const char *prefix
, Size message_size
, const char *message
)
1562 LogicalDecodingContext
*ctx
= cache
->private_data
;
1563 LogicalErrorCallbackState state
;
1564 ErrorContextCallback errcallback
;
1566 Assert(!ctx
->fast_forward
);
1568 /* We're only supposed to call this when streaming is supported. */
1569 Assert(ctx
->streaming
);
1571 /* this callback is optional */
1572 if (ctx
->callbacks
.stream_message_cb
== NULL
)
1575 /* Push callback + info on the error context stack */
1577 state
.callback_name
= "stream_message";
1578 state
.report_location
= message_lsn
;
1579 errcallback
.callback
= output_plugin_error_callback
;
1580 errcallback
.arg
= &state
;
1581 errcallback
.previous
= error_context_stack
;
1582 error_context_stack
= &errcallback
;
1584 /* set output state */
1585 ctx
->accept_writes
= true;
1586 ctx
->write_xid
= txn
!= NULL
? txn
->xid
: InvalidTransactionId
;
1587 ctx
->write_location
= message_lsn
;
1588 ctx
->end_xact
= false;
1590 /* do the actual work: call callback */
1591 ctx
->callbacks
.stream_message_cb(ctx
, txn
, message_lsn
, transactional
, prefix
,
1592 message_size
, message
);
1594 /* Pop the error context stack */
1595 error_context_stack
= errcallback
.previous
;
1599 stream_truncate_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1600 int nrelations
, Relation relations
[],
1601 ReorderBufferChange
*change
)
1603 LogicalDecodingContext
*ctx
= cache
->private_data
;
1604 LogicalErrorCallbackState state
;
1605 ErrorContextCallback errcallback
;
1607 Assert(!ctx
->fast_forward
);
1609 /* We're only supposed to call this when streaming is supported. */
1610 Assert(ctx
->streaming
);
1612 /* this callback is optional */
1613 if (!ctx
->callbacks
.stream_truncate_cb
)
1616 /* Push callback + info on the error context stack */
1618 state
.callback_name
= "stream_truncate";
1619 state
.report_location
= change
->lsn
;
1620 errcallback
.callback
= output_plugin_error_callback
;
1621 errcallback
.arg
= &state
;
1622 errcallback
.previous
= error_context_stack
;
1623 error_context_stack
= &errcallback
;
1625 /* set output state */
1626 ctx
->accept_writes
= true;
1627 ctx
->write_xid
= txn
->xid
;
1630 * Report this change's lsn so replies from clients can give an up-to-date
1631 * answer. This won't ever be enough (and shouldn't be!) to confirm
1632 * receipt of this transaction, but it might allow another transaction's
1633 * commit to be confirmed with one message.
1635 ctx
->write_location
= change
->lsn
;
1637 ctx
->end_xact
= false;
1639 ctx
->callbacks
.stream_truncate_cb(ctx
, txn
, nrelations
, relations
, change
);
1641 /* Pop the error context stack */
1642 error_context_stack
= errcallback
.previous
;
1646 update_progress_txn_cb_wrapper(ReorderBuffer
*cache
, ReorderBufferTXN
*txn
,
1649 LogicalDecodingContext
*ctx
= cache
->private_data
;
1650 LogicalErrorCallbackState state
;
1651 ErrorContextCallback errcallback
;
1653 Assert(!ctx
->fast_forward
);
1655 /* Push callback + info on the error context stack */
1657 state
.callback_name
= "update_progress_txn";
1658 state
.report_location
= lsn
;
1659 errcallback
.callback
= output_plugin_error_callback
;
1660 errcallback
.arg
= &state
;
1661 errcallback
.previous
= error_context_stack
;
1662 error_context_stack
= &errcallback
;
1664 /* set output state */
1665 ctx
->accept_writes
= false;
1666 ctx
->write_xid
= txn
->xid
;
1669 * Report this change's lsn so replies from clients can give an up-to-date
1670 * answer. This won't ever be enough (and shouldn't be!) to confirm
1671 * receipt of this transaction, but it might allow another transaction's
1672 * commit to be confirmed with one message.
1674 ctx
->write_location
= lsn
;
1676 ctx
->end_xact
= false;
1678 OutputPluginUpdateProgress(ctx
, false);
1680 /* Pop the error context stack */
1681 error_context_stack
= errcallback
.previous
;
1685 * Set the required catalog xmin horizon for historic snapshots in the current
1688 * Note that in the most cases, we won't be able to immediately use the xmin
1689 * to increase the xmin horizon: we need to wait till the client has confirmed
1690 * receiving current_lsn with LogicalConfirmReceivedLocation().
1693 LogicalIncreaseXminForSlot(XLogRecPtr current_lsn
, TransactionId xmin
)
1695 bool updated_xmin
= false;
1696 ReplicationSlot
*slot
;
1697 bool got_new_xmin
= false;
1699 slot
= MyReplicationSlot
;
1701 Assert(slot
!= NULL
);
1703 SpinLockAcquire(&slot
->mutex
);
1706 * don't overwrite if we already have a newer xmin. This can happen if we
1707 * restart decoding in a slot.
1709 if (TransactionIdPrecedesOrEquals(xmin
, slot
->data
.catalog_xmin
))
1714 * If the client has already confirmed up to this lsn, we directly can
1715 * mark this as accepted. This can happen if we restart decoding in a
1718 else if (current_lsn
<= slot
->data
.confirmed_flush
)
1720 slot
->candidate_catalog_xmin
= xmin
;
1721 slot
->candidate_xmin_lsn
= current_lsn
;
1723 /* our candidate can directly be used */
1724 updated_xmin
= true;
1728 * Only increase if the previous values have been applied, otherwise we
1729 * might never end up updating if the receiver acks too slowly.
1731 else if (slot
->candidate_xmin_lsn
== InvalidXLogRecPtr
)
1733 slot
->candidate_catalog_xmin
= xmin
;
1734 slot
->candidate_xmin_lsn
= current_lsn
;
1737 * Log new xmin at an appropriate log level after releasing the
1740 got_new_xmin
= true;
1742 SpinLockRelease(&slot
->mutex
);
1745 elog(DEBUG1
, "got new catalog xmin %u at %X/%X", xmin
,
1746 LSN_FORMAT_ARGS(current_lsn
));
1748 /* candidate already valid with the current flush position, apply */
1750 LogicalConfirmReceivedLocation(slot
->data
.confirmed_flush
);
1754 * Mark the minimal LSN (restart_lsn) we need to read to replay all
1755 * transactions that have not yet committed at current_lsn.
1757 * Just like LogicalIncreaseXminForSlot this only takes effect when the
1758 * client has confirmed to have received current_lsn.
1761 LogicalIncreaseRestartDecodingForSlot(XLogRecPtr current_lsn
, XLogRecPtr restart_lsn
)
1763 bool updated_lsn
= false;
1764 ReplicationSlot
*slot
;
1766 slot
= MyReplicationSlot
;
1768 Assert(slot
!= NULL
);
1769 Assert(restart_lsn
!= InvalidXLogRecPtr
);
1770 Assert(current_lsn
!= InvalidXLogRecPtr
);
1772 SpinLockAcquire(&slot
->mutex
);
1774 /* don't overwrite if have a newer restart lsn */
1775 if (restart_lsn
<= slot
->data
.restart_lsn
)
1777 SpinLockRelease(&slot
->mutex
);
1781 * We might have already flushed far enough to directly accept this lsn,
1782 * in this case there is no need to check for existing candidate LSNs
1784 else if (current_lsn
<= slot
->data
.confirmed_flush
)
1786 slot
->candidate_restart_valid
= current_lsn
;
1787 slot
->candidate_restart_lsn
= restart_lsn
;
1788 SpinLockRelease(&slot
->mutex
);
1790 /* our candidate can directly be used */
1795 * Only increase if the previous values have been applied, otherwise we
1796 * might never end up updating if the receiver acks too slowly. A missed
1797 * value here will just cause some extra effort after reconnecting.
1799 else if (slot
->candidate_restart_valid
== InvalidXLogRecPtr
)
1801 slot
->candidate_restart_valid
= current_lsn
;
1802 slot
->candidate_restart_lsn
= restart_lsn
;
1803 SpinLockRelease(&slot
->mutex
);
1805 elog(DEBUG1
, "got new restart lsn %X/%X at %X/%X",
1806 LSN_FORMAT_ARGS(restart_lsn
),
1807 LSN_FORMAT_ARGS(current_lsn
));
1811 XLogRecPtr candidate_restart_lsn
;
1812 XLogRecPtr candidate_restart_valid
;
1813 XLogRecPtr confirmed_flush
;
1815 candidate_restart_lsn
= slot
->candidate_restart_lsn
;
1816 candidate_restart_valid
= slot
->candidate_restart_valid
;
1817 confirmed_flush
= slot
->data
.confirmed_flush
;
1818 SpinLockRelease(&slot
->mutex
);
1820 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",
1821 LSN_FORMAT_ARGS(restart_lsn
),
1822 LSN_FORMAT_ARGS(current_lsn
),
1823 LSN_FORMAT_ARGS(candidate_restart_lsn
),
1824 LSN_FORMAT_ARGS(candidate_restart_valid
),
1825 LSN_FORMAT_ARGS(confirmed_flush
));
1828 /* candidates are already valid with the current flush position, apply */
1830 LogicalConfirmReceivedLocation(slot
->data
.confirmed_flush
);
1834 * Handle a consumer's confirmation having received all changes up to lsn.
1837 LogicalConfirmReceivedLocation(XLogRecPtr lsn
)
1839 Assert(lsn
!= InvalidXLogRecPtr
);
1841 /* Do an unlocked check for candidate_lsn first. */
1842 if (MyReplicationSlot
->candidate_xmin_lsn
!= InvalidXLogRecPtr
||
1843 MyReplicationSlot
->candidate_restart_valid
!= InvalidXLogRecPtr
)
1845 bool updated_xmin
= false;
1846 bool updated_restart
= false;
1848 SpinLockAcquire(&MyReplicationSlot
->mutex
);
1850 MyReplicationSlot
->data
.confirmed_flush
= lsn
;
1852 /* if we're past the location required for bumping xmin, do so */
1853 if (MyReplicationSlot
->candidate_xmin_lsn
!= InvalidXLogRecPtr
&&
1854 MyReplicationSlot
->candidate_xmin_lsn
<= lsn
)
1857 * We have to write the changed xmin to disk *before* we change
1858 * the in-memory value, otherwise after a crash we wouldn't know
1859 * that some catalog tuples might have been removed already.
1861 * Ensure that by first writing to ->xmin and only update
1862 * ->effective_xmin once the new state is synced to disk. After a
1863 * crash ->effective_xmin is set to ->xmin.
1865 if (TransactionIdIsValid(MyReplicationSlot
->candidate_catalog_xmin
) &&
1866 MyReplicationSlot
->data
.catalog_xmin
!= MyReplicationSlot
->candidate_catalog_xmin
)
1868 MyReplicationSlot
->data
.catalog_xmin
= MyReplicationSlot
->candidate_catalog_xmin
;
1869 MyReplicationSlot
->candidate_catalog_xmin
= InvalidTransactionId
;
1870 MyReplicationSlot
->candidate_xmin_lsn
= InvalidXLogRecPtr
;
1871 updated_xmin
= true;
1875 if (MyReplicationSlot
->candidate_restart_valid
!= InvalidXLogRecPtr
&&
1876 MyReplicationSlot
->candidate_restart_valid
<= lsn
)
1878 Assert(MyReplicationSlot
->candidate_restart_lsn
!= InvalidXLogRecPtr
);
1880 MyReplicationSlot
->data
.restart_lsn
= MyReplicationSlot
->candidate_restart_lsn
;
1881 MyReplicationSlot
->candidate_restart_lsn
= InvalidXLogRecPtr
;
1882 MyReplicationSlot
->candidate_restart_valid
= InvalidXLogRecPtr
;
1883 updated_restart
= true;
1886 SpinLockRelease(&MyReplicationSlot
->mutex
);
1888 /* first write new xmin to disk, so we know what's up after a crash */
1889 if (updated_xmin
|| updated_restart
)
1891 ReplicationSlotMarkDirty();
1892 ReplicationSlotSave();
1893 elog(DEBUG1
, "updated xmin: %u restart: %u", updated_xmin
, updated_restart
);
1897 * Now the new xmin is safely on disk, we can let the global value
1898 * advance. We do not take ProcArrayLock or similar since we only
1899 * advance xmin here and there's not much harm done by a concurrent
1900 * computation missing that.
1904 SpinLockAcquire(&MyReplicationSlot
->mutex
);
1905 MyReplicationSlot
->effective_catalog_xmin
= MyReplicationSlot
->data
.catalog_xmin
;
1906 SpinLockRelease(&MyReplicationSlot
->mutex
);
1908 ReplicationSlotsComputeRequiredXmin(false);
1909 ReplicationSlotsComputeRequiredLSN();
1914 SpinLockAcquire(&MyReplicationSlot
->mutex
);
1915 MyReplicationSlot
->data
.confirmed_flush
= lsn
;
1916 SpinLockRelease(&MyReplicationSlot
->mutex
);
1921 * Clear logical streaming state during (sub)transaction abort.
1924 ResetLogicalStreamingState(void)
1926 CheckXidAlive
= InvalidTransactionId
;
1931 * Report stats for a slot.
1934 UpdateDecodingStats(LogicalDecodingContext
*ctx
)
1936 ReorderBuffer
*rb
= ctx
->reorder
;
1937 PgStat_StatReplSlotEntry repSlotStat
;
1939 /* Nothing to do if we don't have any replication stats to be sent. */
1940 if (rb
->spillBytes
<= 0 && rb
->streamBytes
<= 0 && rb
->totalBytes
<= 0)
1943 elog(DEBUG2
, "UpdateDecodingStats: updating stats %p %lld %lld %lld %lld %lld %lld %lld %lld",
1945 (long long) rb
->spillTxns
,
1946 (long long) rb
->spillCount
,
1947 (long long) rb
->spillBytes
,
1948 (long long) rb
->streamTxns
,
1949 (long long) rb
->streamCount
,
1950 (long long) rb
->streamBytes
,
1951 (long long) rb
->totalTxns
,
1952 (long long) rb
->totalBytes
);
1954 repSlotStat
.spill_txns
= rb
->spillTxns
;
1955 repSlotStat
.spill_count
= rb
->spillCount
;
1956 repSlotStat
.spill_bytes
= rb
->spillBytes
;
1957 repSlotStat
.stream_txns
= rb
->streamTxns
;
1958 repSlotStat
.stream_count
= rb
->streamCount
;
1959 repSlotStat
.stream_bytes
= rb
->streamBytes
;
1960 repSlotStat
.total_txns
= rb
->totalTxns
;
1961 repSlotStat
.total_bytes
= rb
->totalBytes
;
1963 pgstat_report_replslot(ctx
->slot
, &repSlotStat
);
1969 rb
->streamCount
= 0;
1970 rb
->streamBytes
= 0;
1976 * Read up to the end of WAL starting from the decoding slot's restart_lsn.
1977 * Return true if any meaningful/decodable WAL records are encountered,
1981 LogicalReplicationSlotHasPendingWal(XLogRecPtr end_of_wal
)
1983 bool has_pending_wal
= false;
1985 Assert(MyReplicationSlot
);
1989 LogicalDecodingContext
*ctx
;
1992 * Create our decoding context in fast_forward mode, passing start_lsn
1993 * as InvalidXLogRecPtr, so that we start processing from the slot's
1996 ctx
= CreateDecodingContext(InvalidXLogRecPtr
,
1998 true, /* fast_forward */
1999 XL_ROUTINE(.page_read
= read_local_xlog_page
,
2000 .segment_open
= wal_segment_open
,
2001 .segment_close
= wal_segment_close
),
2005 * Start reading at the slot's restart_lsn, which we know points to a
2008 XLogBeginRead(ctx
->reader
, MyReplicationSlot
->data
.restart_lsn
);
2010 /* Invalidate non-timetravel entries */
2011 InvalidateSystemCaches();
2013 /* Loop until the end of WAL or some changes are processed */
2014 while (!has_pending_wal
&& ctx
->reader
->EndRecPtr
< end_of_wal
)
2019 record
= XLogReadRecord(ctx
->reader
, &errm
);
2022 elog(ERROR
, "could not find record for logical decoding: %s", errm
);
2025 LogicalDecodingProcessRecord(ctx
, ctx
->reader
);
2027 has_pending_wal
= ctx
->processing_required
;
2029 CHECK_FOR_INTERRUPTS();
2033 FreeDecodingContext(ctx
);
2034 InvalidateSystemCaches();
2038 /* clear all timetravel entries */
2039 InvalidateSystemCaches();
2045 return has_pending_wal
;
2049 * Helper function for advancing our logical replication slot forward.
2051 * The slot's restart_lsn is used as start point for reading records, while
2052 * confirmed_flush is used as base point for the decoding context.
2054 * We cannot just do LogicalConfirmReceivedLocation to update confirmed_flush,
2055 * because we need to digest WAL to advance restart_lsn allowing to recycle
2056 * WAL and removal of old catalog tuples. As decoding is done in fast_forward
2057 * mode, no changes are generated anyway.
2059 * *found_consistent_snapshot will be true if the initial decoding snapshot has
2060 * been built; Otherwise, it will be false.
2063 LogicalSlotAdvanceAndCheckSnapState(XLogRecPtr moveto
,
2064 bool *found_consistent_snapshot
)
2066 LogicalDecodingContext
*ctx
;
2067 ResourceOwner old_resowner
= CurrentResourceOwner
;
2070 Assert(moveto
!= InvalidXLogRecPtr
);
2072 if (found_consistent_snapshot
)
2073 *found_consistent_snapshot
= false;
2078 * Create our decoding context in fast_forward mode, passing start_lsn
2079 * as InvalidXLogRecPtr, so that we start processing from my slot's
2082 ctx
= CreateDecodingContext(InvalidXLogRecPtr
,
2084 true, /* fast_forward */
2085 XL_ROUTINE(.page_read
= read_local_xlog_page
,
2086 .segment_open
= wal_segment_open
,
2087 .segment_close
= wal_segment_close
),
2091 * Wait for specified streaming replication standby servers (if any)
2092 * to confirm receipt of WAL up to moveto lsn.
2094 WaitForStandbyConfirmation(moveto
);
2097 * Start reading at the slot's restart_lsn, which we know to point to
2100 XLogBeginRead(ctx
->reader
, MyReplicationSlot
->data
.restart_lsn
);
2102 /* invalidate non-timetravel entries */
2103 InvalidateSystemCaches();
2105 /* Decode records until we reach the requested target */
2106 while (ctx
->reader
->EndRecPtr
< moveto
)
2112 * Read records. No changes are generated in fast_forward mode,
2113 * but snapbuilder/slot statuses are updated properly.
2115 record
= XLogReadRecord(ctx
->reader
, &errm
);
2117 elog(ERROR
, "could not find record while advancing replication slot: %s",
2121 * Process the record. Storage-level changes are ignored in
2122 * fast_forward mode, but other modules (such as snapbuilder)
2123 * might still have critical updates to do.
2126 LogicalDecodingProcessRecord(ctx
, ctx
->reader
);
2128 CHECK_FOR_INTERRUPTS();
2131 if (found_consistent_snapshot
&& DecodingContextReady(ctx
))
2132 *found_consistent_snapshot
= true;
2135 * Logical decoding could have clobbered CurrentResourceOwner during
2136 * transaction management, so restore the executor's value. (This is
2137 * a kluge, but it's not worth cleaning up right now.)
2139 CurrentResourceOwner
= old_resowner
;
2141 if (ctx
->reader
->EndRecPtr
!= InvalidXLogRecPtr
)
2143 LogicalConfirmReceivedLocation(moveto
);
2146 * If only the confirmed_flush LSN has changed the slot won't get
2147 * marked as dirty by the above. Callers on the walsender
2148 * interface are expected to keep track of their own progress and
2149 * don't need it written out. But SQL-interface users cannot
2150 * specify their own start positions and it's harder for them to
2151 * keep track of their progress, so we should make more of an
2152 * effort to save it for them.
2154 * Dirty the slot so it is written out at the next checkpoint. The
2155 * LSN position advanced to may still be lost on a crash but this
2156 * makes the data consistent after a clean shutdown.
2158 ReplicationSlotMarkDirty();
2161 retlsn
= MyReplicationSlot
->data
.confirmed_flush
;
2163 /* free context, call shutdown callback */
2164 FreeDecodingContext(ctx
);
2166 InvalidateSystemCaches();
2170 /* clear all timetravel entries */
2171 InvalidateSystemCaches();