LCOV - differential code coverage report
Current view: top level - src/backend/replication/logical - logical.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC EUB ECB DUB DCB
Current: 0e5ff9b9b45a657aea12440478dc002e9b01f138 vs 0123ce131fca454009439dfa3b2266d1d40737d7 Lines: 93.2 % 803 748 1 54 43 705 1 37
Current Date: 2026-03-14 14:10:32 -0400 Functions: 97.6 % 41 40 1 13 27 2
Baseline: lcov-20260315-024220-baseline Branches: 59.0 % 410 242 13 155 1 57 184 10 10 12 52
Baseline Date: 2026-03-14 15:27:56 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 98.2 % 55 54 1 43 11
(360..) days: 92.8 % 748 694 54 694
Function coverage date bins:
(30,360] days: 100.0 % 2 2 2
(360..) days: 97.4 % 39 38 1 11 27
Branch coverage date bins:
(30,360] days: 82.9 % 76 63 13 57 6
(360..) days: 50.6 % 354 179 155 1 178 10 10

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

Generated by: LCOV version 2.4-beta