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 DCB
Current: c70b6db34ffeab48beef1fb4ce61bcad3772b8dd vs 06473f5a344df8c9594ead90a609b86f6724cff8 Lines: 92.9 % 791 735 56 6 729 6
Current Date: 2025-09-06 07:49:51 +0900 Functions: 97.6 % 41 40 1 5 35
Baseline: lcov-20250906-005545-baseline Branches: 57.3 % 422 242 1 179 1 9 232
Baseline Date: 2025-09-05 08:21:35 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 97.4 % 39 38 1 6 32
(360..) days: 92.7 % 752 697 55 697
Function coverage date bins:
(360..) days: 97.6 % 41 40 1 5 35
Branch coverage date bins:
(30,360] days: 86.4 % 22 19 1 2 9 10
(360..) days: 55.8 % 400 223 177 1 222

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

Generated by: LCOV version 2.4-beta