LCOV - differential code coverage report
Current view: top level - src/backend/replication/libpqwalreceiver - libpqwalreceiver.c (source / functions) Coverage Total Hit UBC CBC
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 84.3 % 440 371 69 371
Current Date: 2026-08-27 14:31:44 +0300 Functions: 95.7 % 23 22 1 22
Baseline: lcov-20260827-baseline Branches: 61.9 % 323 200 123 200
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 80.0 % 5 4 1 4
(30,360] days: 94.0 % 50 47 3 47
(360..) days: 83.1 % 385 320 65 320
Function coverage date bins:
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 3 3 3
(360..) days: 94.7 % 19 18 1 18
Branch coverage date bins:
(7,30] days: 50.0 % 6 3 3 3
(30,360] days: 72.7 % 22 16 6 16
(360..) days: 61.4 % 295 181 114 181

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * libpqwalreceiver.c
                                  4                 :                :  *
                                  5                 :                :  * This file contains the libpq-specific parts of walreceiver. It's
                                  6                 :                :  * loaded as a dynamic module to avoid linking the main server binary with
                                  7                 :                :  * libpq.
                                  8                 :                :  *
                                  9                 :                :  * Apart from walreceiver, the libpq-specific routines are now being used by
                                 10                 :                :  * logical replication workers and slot synchronization.
                                 11                 :                :  *
                                 12                 :                :  * Portions Copyright (c) 2010-2026, PostgreSQL Global Development Group
                                 13                 :                :  *
                                 14                 :                :  *
                                 15                 :                :  * IDENTIFICATION
                                 16                 :                :  *    src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
                                 17                 :                :  *
                                 18                 :                :  *-------------------------------------------------------------------------
                                 19                 :                :  */
                                 20                 :                : #include "postgres.h"
                                 21                 :                : 
                                 22                 :                : #include <unistd.h>
                                 23                 :                : #include <sys/time.h>
                                 24                 :                : 
                                 25                 :                : #include "common/connect.h"
                                 26                 :                : #include "funcapi.h"
                                 27                 :                : #include "libpq-fe.h"
                                 28                 :                : #include "libpq/libpq-be-fe-helpers.h"
                                 29                 :                : #include "mb/pg_wchar.h"
                                 30                 :                : #include "miscadmin.h"
                                 31                 :                : #include "pgstat.h"
                                 32                 :                : #include "pqexpbuffer.h"
                                 33                 :                : #include "replication/walreceiver.h"
                                 34                 :                : #include "storage/latch.h"
                                 35                 :                : #include "utils/builtins.h"
                                 36                 :                : #include "utils/memutils.h"
                                 37                 :                : #include "utils/pg_lsn.h"
                                 38                 :                : #include "utils/tuplestore.h"
                                 39                 :                : 
  519 tgl@sss.pgh.pa.us          40                 :CBC        1152 : PG_MODULE_MAGIC_EXT(
                                 41                 :                :                     .name = "libpqwalreceiver",
                                 42                 :                :                     .version = PG_VERSION
                                 43                 :                : );
                                 44                 :                : 
                                 45                 :                : struct WalReceiverConn
                                 46                 :                : {
                                 47                 :                :     /* Current connection to the primary, if any */
                                 48                 :                :     PGconn     *streamConn;
                                 49                 :                :     /* Used to remember if the connection is logical or physical */
                                 50                 :                :     bool        logical;
                                 51                 :                :     /* Buffer for currently read records */
                                 52                 :                :     char       *recvBuf;
                                 53                 :                : };
                                 54                 :                : 
                                 55                 :                : /* Prototypes for interface functions */
                                 56                 :                : static WalReceiverConn *libpqrcv_connect(const char *conninfo,
                                 57                 :                :                                          bool replication, bool logical,
                                 58                 :                :                                          bool must_use_password,
                                 59                 :                :                                          const char *appname, char **err);
                                 60                 :                : static void libpqrcv_check_conninfo(const char *conninfo,
                                 61                 :                :                                     bool must_use_password);
                                 62                 :                : static char *libpqrcv_get_conninfo(WalReceiverConn *conn);
                                 63                 :                : static void libpqrcv_get_senderinfo(WalReceiverConn *conn,
                                 64                 :                :                                     char **sender_host, int *sender_port);
                                 65                 :                : static char *libpqrcv_identify_system(WalReceiverConn *conn,
                                 66                 :                :                                       TimeLineID *primary_tli,
                                 67                 :                :                                       XLogRecPtr *server_lsn);
                                 68                 :                : static char *libpqrcv_get_dbname_from_conninfo(const char *connInfo);
                                 69                 :                : static char *libpqrcv_get_option_from_conninfo(const char *connInfo,
                                 70                 :                :                                                const char *keyword);
                                 71                 :                : static int  libpqrcv_server_version(WalReceiverConn *conn);
                                 72                 :                : static void libpqrcv_readtimelinehistoryfile(WalReceiverConn *conn,
                                 73                 :                :                                              TimeLineID tli, char **filename,
                                 74                 :                :                                              char **content, size_t *len);
                                 75                 :                : static bool libpqrcv_startstreaming(WalReceiverConn *conn,
                                 76                 :                :                                     const WalRcvStreamOptions *options);
                                 77                 :                : static void libpqrcv_endstreaming(WalReceiverConn *conn,
                                 78                 :                :                                   TimeLineID *next_tli);
                                 79                 :                : static int  libpqrcv_receive(WalReceiverConn *conn, char **buffer,
                                 80                 :                :                              pgsocket *wait_fd);
                                 81                 :                : static void libpqrcv_send(WalReceiverConn *conn, const char *buffer,
                                 82                 :                :                           int nbytes);
                                 83                 :                : static char *libpqrcv_create_slot(WalReceiverConn *conn,
                                 84                 :                :                                   const char *slotname,
                                 85                 :                :                                   bool temporary,
                                 86                 :                :                                   bool two_phase,
                                 87                 :                :                                   bool failover,
                                 88                 :                :                                   CRSSnapshotAction snapshot_action,
                                 89                 :                :                                   XLogRecPtr *lsn);
                                 90                 :                : static void libpqrcv_alter_slot(WalReceiverConn *conn, const char *slotname,
                                 91                 :                :                                 const bool *failover, const bool *two_phase);
                                 92                 :                : static pid_t libpqrcv_get_backend_pid(WalReceiverConn *conn);
                                 93                 :                : static WalRcvExecResult *libpqrcv_exec(WalReceiverConn *conn,
                                 94                 :                :                                        const char *query,
                                 95                 :                :                                        const int nRetTypes,
                                 96                 :                :                                        const Oid *retTypes);
                                 97                 :                : static void libpqrcv_disconnect(WalReceiverConn *conn);
                                 98                 :                : 
                                 99                 :                : static WalReceiverFunctionsType PQWalReceiverFunctions = {
                                100                 :                :     .walrcv_connect = libpqrcv_connect,
                                101                 :                :     .walrcv_check_conninfo = libpqrcv_check_conninfo,
                                102                 :                :     .walrcv_get_conninfo = libpqrcv_get_conninfo,
                                103                 :                :     .walrcv_get_senderinfo = libpqrcv_get_senderinfo,
                                104                 :                :     .walrcv_identify_system = libpqrcv_identify_system,
                                105                 :                :     .walrcv_server_version = libpqrcv_server_version,
                                106                 :                :     .walrcv_readtimelinehistoryfile = libpqrcv_readtimelinehistoryfile,
                                107                 :                :     .walrcv_startstreaming = libpqrcv_startstreaming,
                                108                 :                :     .walrcv_endstreaming = libpqrcv_endstreaming,
                                109                 :                :     .walrcv_receive = libpqrcv_receive,
                                110                 :                :     .walrcv_send = libpqrcv_send,
                                111                 :                :     .walrcv_create_slot = libpqrcv_create_slot,
                                112                 :                :     .walrcv_alter_slot = libpqrcv_alter_slot,
                                113                 :                :     .walrcv_get_dbname_from_conninfo = libpqrcv_get_dbname_from_conninfo,
                                114                 :                :     .walrcv_get_backend_pid = libpqrcv_get_backend_pid,
                                115                 :                :     .walrcv_exec = libpqrcv_exec,
                                116                 :                :     .walrcv_disconnect = libpqrcv_disconnect
                                117                 :                : };
                                118                 :                : 
                                119                 :                : /* Prototypes for private functions */
                                120                 :                : static char *stringlist_to_identifierstr(List *strings);
                                121                 :                : 
                                122                 :                : /*
                                123                 :                :  * Module initialization function
                                124                 :                :  */
                                125                 :                : void
 6063 heikki.linnakangas@i      126                 :           1152 : _PG_init(void)
                                127                 :                : {
 3557 peter_e@gmx.net           128         [ -  + ]:           1152 :     if (WalReceiverFunctions != NULL)
 6063 heikki.linnakangas@i      129         [ #  # ]:UBC           0 :         elog(ERROR, "libpqwalreceiver already loaded");
 3557 peter_e@gmx.net           130                 :CBC        1152 :     WalReceiverFunctions = &PQWalReceiverFunctions;
 6063 heikki.linnakangas@i      131                 :           1152 : }
                                132                 :                : 
                                133                 :                : /*
                                134                 :                :  * Establish the connection to the primary server.
                                135                 :                :  *
                                136                 :                :  * This function can be used for both replication and regular connections.
                                137                 :                :  * If it is a replication connection, it could be either logical or physical
                                138                 :                :  * based on input argument 'logical'.
                                139                 :                :  *
                                140                 :                :  * If an error occurs, this function will normally return NULL and set *err
                                141                 :                :  * to a palloc'ed error message. However, if must_use_password is true and
                                142                 :                :  * the connection fails to use the password, this function will ereport(ERROR).
                                143                 :                :  * We do this because in that case the error includes a detail and a hint for
                                144                 :                :  * consistency with other parts of the system, and it's not worth adding the
                                145                 :                :  * machinery to pass all of those back to the caller just to cover this one
                                146                 :                :  * case.
                                147                 :                :  */
                                148                 :                : static WalReceiverConn *
  934 akapila@postgresql.o      149                 :           1067 : libpqrcv_connect(const char *conninfo, bool replication, bool logical,
                                150                 :                :                  bool must_use_password, const char *appname, char **err)
                                151                 :                : {
                                152                 :                :     WalReceiverConn *conn;
                                153                 :                :     const char *keys[6];
                                154                 :                :     const char *vals[6];
 3557 peter_e@gmx.net           155                 :           1067 :     int         i = 0;
  233 fujii@postgresql.org      156                 :           1067 :     char       *options_val = NULL;
                                157                 :                : 
                                158                 :                :     /*
                                159                 :                :      * Re-validate connection string. The validation already happened at DDL
                                160                 :                :      * time, but the subscription owner may have changed. If we don't recheck
                                161                 :                :      * with the correct must_use_password, it's possible that the connection
                                162                 :                :      * will obtain the password from a different source, such as PGPASSFILE or
                                163                 :                :      * PGPASSWORD.
                                164                 :                :      */
  958 jdavis@postgresql.or      165                 :           1067 :     libpqrcv_check_conninfo(conninfo, must_use_password);
                                166                 :                : 
                                167                 :                :     /*
                                168                 :                :      * We use the expand_dbname parameter to process the connection string (or
                                169                 :                :      * URI), and pass some extra options.
                                170                 :                :      */
 3557 peter_e@gmx.net           171                 :           1058 :     keys[i] = "dbname";
                                172                 :           1058 :     vals[i] = conninfo;
                                173                 :                : 
                                174                 :                :     /* We can not have logical without replication */
  934 akapila@postgresql.o      175   [ +  +  -  + ]:           1058 :     Assert(replication || !logical);
                                176                 :                : 
                                177         [ +  + ]:           1058 :     if (replication)
                                178                 :                :     {
                                179                 :           1042 :         keys[++i] = "replication";
                                180         [ +  + ]:           1042 :         vals[i] = logical ? "database" : "true";
                                181                 :                : 
                                182         [ +  + ]:           1042 :         if (logical)
                                183                 :                :         {
  233 fujii@postgresql.org      184                 :            777 :             char       *opt = NULL;
                                185                 :                : 
                                186                 :                :             /* Tell the publisher to translate to our encoding */
  934 akapila@postgresql.o      187                 :            777 :             keys[++i] = "client_encoding";
                                188                 :            777 :             vals[i] = GetDatabaseEncodingName();
                                189                 :                : 
                                190                 :                :             /*
                                191                 :                :              * Force assorted GUC parameters to settings that ensure that the
                                192                 :                :              * publisher will output data values in a form that is unambiguous
                                193                 :                :              * to the subscriber.  (We don't want to modify the subscriber's
                                194                 :                :              * GUC settings, since that might surprise user-defined code
                                195                 :                :              * running in the subscriber, such as triggers.)  This should
                                196                 :                :              * match what pg_dump does.
                                197                 :                :              */
  233 fujii@postgresql.org      198                 :            777 :             opt = libpqrcv_get_option_from_conninfo(conninfo, "options");
                                199         [ +  + ]:            777 :             options_val = psprintf("%s -c datestyle=ISO -c intervalstyle=postgres -c extra_float_digits=3",
                                200                 :                :                                    (opt == NULL) ? "" : opt);
  934 akapila@postgresql.o      201                 :            777 :             keys[++i] = "options";
  233 fujii@postgresql.org      202                 :            777 :             vals[i] = options_val;
                                203         [ +  + ]:            777 :             if (opt != NULL)
                                204                 :              9 :                 pfree(opt);
                                205                 :                :         }
                                206                 :                :         else
                                207                 :                :         {
                                208                 :                :             /*
                                209                 :                :              * The database name is ignored by the server in replication mode,
                                210                 :                :              * but specify "replication" for .pgpass lookup.
                                211                 :                :              */
  934 akapila@postgresql.o      212                 :            265 :             keys[++i] = "dbname";
                                213                 :            265 :             vals[i] = "replication";
                                214                 :                :         }
                                215                 :                :     }
                                216                 :                : 
 3557 peter_e@gmx.net           217                 :           1058 :     keys[++i] = "fallback_application_name";
                                218                 :           1058 :     vals[i] = appname;
                                219                 :                : 
                                220                 :           1058 :     keys[++i] = NULL;
                                221                 :           1058 :     vals[i] = NULL;
                                222                 :                : 
  536 heikki.linnakangas@i      223         [ -  + ]:           1058 :     Assert(i < lengthof(keys));
                                224                 :                : 
  260 michael@paquier.xyz       225                 :           1058 :     conn = palloc0_object(WalReceiverConn);
  510 heikki.linnakangas@i      226                 :           1058 :     conn->streamConn =
   96 fujii@postgresql.org      227                 :           1058 :         libpqsrv_connect_params_start(keys, vals,
                                228                 :                :                                        /* expand_dbname = */ true);
                                229                 :           1058 :     PQsetNoticeReceiver(conn->streamConn, libpqsrv_notice_receiver,
                                230                 :                :                         "received message via replication");
                                231                 :           1058 :     libpqsrv_connect_complete(conn->streamConn,
                                232                 :                :                               WAIT_EVENT_LIBPQWALRECEIVER_CONNECT);
                                233                 :                : 
  233                           234         [ +  + ]:           1058 :     if (options_val != NULL)
                                235                 :            777 :         pfree(options_val);
                                236                 :                : 
 3557 peter_e@gmx.net           237         [ +  + ]:           1058 :     if (PQstatus(conn->streamConn) != CONNECTION_OK)
 1312 andres@anarazel.de        238                 :            139 :         goto bad_connection_errmsg;
                                239                 :                : 
 1246 rhaas@postgresql.org      240   [ +  +  -  + ]:            919 :     if (must_use_password && !PQconnectionUsedPassword(conn->streamConn))
                                241                 :                :     {
  510 heikki.linnakangas@i      242                 :UBC           0 :         libpqsrv_disconnect(conn->streamConn);
 1246 rhaas@postgresql.org      243                 :              0 :         pfree(conn);
                                244                 :                : 
                                245         [ #  # ]:              0 :         ereport(ERROR,
                                246                 :                :                 (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
                                247                 :                :                  errmsg("password is required"),
                                248                 :                :                  errdetail("Non-superuser cannot connect if the server does not request a password."),
                                249                 :                :                  errhint("Target server's authentication method must be changed, or set password_required=false in the subscription parameters.")));
                                250                 :                :     }
                                251                 :                : 
                                252                 :                :     /*
                                253                 :                :      * Set always-secure search path for the cases where the connection is
                                254                 :                :      * used to run SQL queries, so malicious users can't get control.
                                255                 :                :      */
  910 akapila@postgresql.o      256   [ +  +  +  + ]:CBC         919 :     if (!replication || logical)
                                257                 :                :     {
                                258                 :                :         PGresult   *res;
                                259                 :                : 
  510 heikki.linnakangas@i      260                 :            756 :         res = libpqsrv_exec(conn->streamConn,
                                261                 :                :                             ALWAYS_SECURE_SEARCH_PATH_SQL,
                                262                 :                :                             WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 2208 noah@leadboat.com         263         [ -  + ]:            756 :         if (PQresultStatus(res) != PGRES_TUPLES_OK)
                                264                 :                :         {
 2208 noah@leadboat.com         265                 :UBC           0 :             PQclear(res);
 1312 andres@anarazel.de        266                 :              0 :             *err = psprintf(_("could not clear search path: %s"),
                                267                 :              0 :                             pchomp(PQerrorMessage(conn->streamConn)));
                                268                 :              0 :             goto bad_connection;
                                269                 :                :         }
 2208 noah@leadboat.com         270                 :CBC         756 :         PQclear(res);
                                271                 :                :     }
                                272                 :                : 
 3557 peter_e@gmx.net           273                 :            919 :     conn->logical = logical;
                                274                 :                : 
                                275                 :            919 :     return conn;
                                276                 :                : 
                                277                 :                :     /* error path, using libpq's error message */
 1312 andres@anarazel.de        278                 :            139 : bad_connection_errmsg:
                                279                 :            139 :     *err = pchomp(PQerrorMessage(conn->streamConn));
                                280                 :                : 
                                281                 :                :     /* error path, error already set */
                                282                 :            139 : bad_connection:
  510 heikki.linnakangas@i      283                 :            139 :     libpqsrv_disconnect(conn->streamConn);
 1312 andres@anarazel.de        284                 :            139 :     pfree(conn);
                                285                 :            139 :     return NULL;
                                286                 :                : }
                                287                 :                : 
                                288                 :                : /*
                                289                 :                :  * Validate connection info string.
                                290                 :                :  *
                                291                 :                :  * If the connection string can't be parsed, this function will raise
                                292                 :                :  * an error. If must_use_password is true, the function raises an error
                                293                 :                :  * if no password is provided in the connection string. In any other case
                                294                 :                :  * it successfully completes.
                                295                 :                :  */
                                296                 :                : static void
 1246 rhaas@postgresql.org      297                 :           1315 : libpqrcv_check_conninfo(const char *conninfo, bool must_use_password)
                                298                 :                : {
 3389 bruce@momjian.us          299                 :           1315 :     PQconninfoOption *opts = NULL;
                                300                 :                :     PQconninfoOption *opt;
                                301                 :           1315 :     char       *err = NULL;
                                302                 :                : 
 3507 peter_e@gmx.net           303                 :           1315 :     opts = PQconninfoParse(conninfo, &err);
                                304         [ +  + ]:           1315 :     if (opts == NULL)
                                305                 :                :     {
                                306                 :                :         /* The error string is malloc'd, so we must free it explicitly */
 1988 tgl@sss.pgh.pa.us         307         [ +  - ]:             12 :         char       *errcopy = err ? pstrdup(err) : "out of memory";
                                308                 :                : 
                                309                 :             12 :         PQfreemem(err);
 3507 peter_e@gmx.net           310         [ +  - ]:             12 :         ereport(ERROR,
                                311                 :                :                 (errcode(ERRCODE_SYNTAX_ERROR),
                                312                 :                :                  errmsg("invalid connection string syntax: %s", errcopy)));
                                313                 :                :     }
                                314                 :                : 
 1246 rhaas@postgresql.org      315         [ +  + ]:           1303 :     if (must_use_password)
                                316                 :                :     {
 1196 tgl@sss.pgh.pa.us         317                 :             28 :         bool        uses_password = false;
                                318                 :                : 
 1246 rhaas@postgresql.org      319         [ +  + ]:            749 :         for (opt = opts; opt->keyword != NULL; ++opt)
                                320                 :                :         {
                                321                 :                :             /* Ignore connection options that are not present. */
                                322         [ +  + ]:            736 :             if (opt->val == NULL)
                                323                 :            685 :                 continue;
                                324                 :                : 
                                325   [ +  +  +  - ]:             51 :             if (strcmp(opt->keyword, "password") == 0 && opt->val[0] != '\0')
                                326                 :                :             {
                                327                 :             15 :                 uses_password = true;
                                328                 :             15 :                 break;
                                329                 :                :             }
                                330                 :                :         }
                                331                 :                : 
                                332         [ +  + ]:             28 :         if (!uses_password)
                                333                 :                :         {
                                334                 :                :             /* malloc'd, so we must free it explicitly */
  958 jdavis@postgresql.or      335                 :             13 :             PQconninfoFree(opts);
                                336                 :                : 
 1246 rhaas@postgresql.org      337         [ +  - ]:             13 :             ereport(ERROR,
                                338                 :                :                     (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
                                339                 :                :                      errmsg("password is required"),
                                340                 :                :                      errdetail("Non-superusers must provide a password in the connection string.")));
                                341                 :                :         }
                                342                 :                :     }
                                343                 :                : 
 3507 peter_e@gmx.net           344                 :           1290 :     PQconninfoFree(opts);
                                345                 :           1290 : }
                                346                 :                : 
                                347                 :                : /*
                                348                 :                :  * Return a user-displayable conninfo string.  Any security-sensitive fields
                                349                 :                :  * are obfuscated.
                                350                 :                :  */
                                351                 :                : static char *
 3557                           352                 :            163 : libpqrcv_get_conninfo(WalReceiverConn *conn)
                                353                 :                : {
                                354                 :                :     PQconninfoOption *conn_opts;
                                355                 :                :     PQconninfoOption *conn_opt;
                                356                 :                :     PQExpBufferData buf;
                                357                 :                :     char       *retval;
                                358                 :                : 
                                359         [ -  + ]:            163 :     Assert(conn->streamConn != NULL);
                                360                 :                : 
 3711 alvherre@alvh.no-ip.      361                 :            163 :     initPQExpBuffer(&buf);
 3557 peter_e@gmx.net           362                 :            163 :     conn_opts = PQconninfo(conn->streamConn);
                                363                 :                : 
 3711 alvherre@alvh.no-ip.      364         [ -  + ]:            163 :     if (conn_opts == NULL)
 3711 alvherre@alvh.no-ip.      365         [ #  # ]:UBC           0 :         ereport(ERROR,
                                366                 :                :                 (errcode(ERRCODE_OUT_OF_MEMORY),
                                367                 :                :                  errmsg("could not parse connection string: %s",
                                368                 :                :                         _("out of memory"))));
                                369                 :                : 
                                370                 :                :     /* build a clean connection string from pieces */
 3711 alvherre@alvh.no-ip.      371         [ +  + ]:CBC        8639 :     for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
                                372                 :                :     {
                                373                 :                :         bool        obfuscate;
                                374                 :                : 
                                375                 :                :         /* Skip debug and empty options */
                                376         [ +  + ]:           8476 :         if (strchr(conn_opt->dispchar, 'D') ||
                                377         [ +  + ]:           7824 :             conn_opt->val == NULL ||
                                378         [ +  + ]:           3110 :             conn_opt->val[0] == '\0')
                                379                 :           5529 :             continue;
                                380                 :                : 
                                381                 :                :         /* Obfuscate security-sensitive options */
                                382                 :           2947 :         obfuscate = strchr(conn_opt->dispchar, '*') != NULL;
                                383                 :                : 
                                384         [ +  + ]:           5894 :         appendPQExpBuffer(&buf, "%s%s=%s",
                                385         [ +  + ]:           2947 :                           buf.len == 0 ? "" : " ",
                                386                 :                :                           conn_opt->keyword,
                                387                 :                :                           obfuscate ? "********" : conn_opt->val);
                                388                 :                :     }
                                389                 :                : 
                                390                 :            163 :     PQconninfoFree(conn_opts);
                                391                 :                : 
                                392         [ +  - ]:            163 :     retval = PQExpBufferDataBroken(buf) ? NULL : pstrdup(buf.data);
                                393                 :            163 :     termPQExpBuffer(&buf);
                                394                 :            163 :     return retval;
                                395                 :                : }
                                396                 :                : 
                                397                 :                : /*
                                398                 :                :  * Provides information of sender this WAL receiver is connected to.
                                399                 :                :  */
                                400                 :                : static void
 3071 fujii@postgresql.org      401                 :            163 : libpqrcv_get_senderinfo(WalReceiverConn *conn, char **sender_host,
                                402                 :                :                         int *sender_port)
                                403                 :                : {
 3045 tgl@sss.pgh.pa.us         404                 :            163 :     char       *ret = NULL;
                                405                 :                : 
 3071 fujii@postgresql.org      406                 :            163 :     *sender_host = NULL;
                                407                 :            163 :     *sender_port = 0;
                                408                 :                : 
                                409         [ -  + ]:            163 :     Assert(conn->streamConn != NULL);
                                410                 :                : 
                                411                 :            163 :     ret = PQhost(conn->streamConn);
                                412   [ +  -  +  - ]:            163 :     if (ret && strlen(ret) != 0)
                                413                 :            163 :         *sender_host = pstrdup(ret);
                                414                 :                : 
                                415                 :            163 :     ret = PQport(conn->streamConn);
                                416   [ +  -  +  - ]:            163 :     if (ret && strlen(ret) != 0)
                                417                 :            163 :         *sender_port = atoi(ret);
                                418                 :            163 : }
                                419                 :                : 
                                420                 :                : /*
                                421                 :                :  * Check that primary's system identifier matches ours, and fetch the current
                                422                 :                :  * timeline ID of the primary.
                                423                 :                :  */
                                424                 :                : static char *
   29 alvherre@kurilemu.de      425                 :            432 : libpqrcv_identify_system(WalReceiverConn *conn, TimeLineID *primary_tli,
                                426                 :                :                          XLogRecPtr *server_lsn)
                                427                 :                : {
                                428                 :                :     PGresult   *res;
                                429                 :                :     char       *primary_sysid;
                                430                 :                : 
                                431                 :                :     /*
                                432                 :                :      * Get the system identifier and timeline ID as a DataRow message from the
                                433                 :                :      * primary server.
                                434                 :                :      */
  510 heikki.linnakangas@i      435                 :            432 :     res = libpqsrv_exec(conn->streamConn,
                                436                 :                :                         "IDENTIFY_SYSTEM",
                                437                 :                :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 6063                           438         [ -  + ]:            432 :     if (PQresultStatus(res) != PGRES_TUPLES_OK)
 6063 heikki.linnakangas@i      439         [ #  # ]:UBC           0 :         ereport(ERROR,
                                440                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                441                 :                :                  errmsg("could not receive database system identifier and timeline ID from "
                                442                 :                :                         "the primary server: %s",
                                443                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
                                444                 :                : 
                                445                 :                :     /*
                                446                 :                :      * IDENTIFY_SYSTEM returns 3 columns in 9.3 and earlier, and 4 columns in
                                447                 :                :      * 9.4 and onwards.
                                448                 :                :      */
 4391 fujii@postgresql.org      449   [ +  -  -  + ]:CBC         432 :     if (PQnfields(res) < 3 || PQntuples(res) != 1)
 6063 heikki.linnakangas@i      450         [ #  # ]:UBC           0 :         ereport(ERROR,
                                451                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                452                 :                :                  errmsg("invalid response from primary server"),
                                453                 :                :                  errdetail("Could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields.",
                                454                 :                :                            PQntuples(res), PQnfields(res), 1, 3)));
 3557 peter_e@gmx.net           455                 :CBC         432 :     primary_sysid = pstrdup(PQgetvalue(res, 0, 0));
 2958 andres@anarazel.de        456                 :            432 :     *primary_tli = pg_strtoint32(PQgetvalue(res, 0, 1));
                                457                 :                : 
                                458                 :                :     /* Column 2 is the server's current WAL flush position */
   29 alvherre@kurilemu.de      459         [ +  + ]:            432 :     if (server_lsn)
                                460                 :                :     {
                                461                 :                :         uint32      hi,
                                462                 :                :                     lo;
                                463                 :                : 
                                464         [ -  + ]:            178 :         if (sscanf(PQgetvalue(res, 0, 2), "%X/%X", &hi, &lo) != 2)
   29 alvherre@kurilemu.de      465         [ #  # ]:UBC           0 :             ereport(ERROR,
                                466                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                467                 :                :                      errmsg("could not parse WAL location \"%s\"",
                                468                 :                :                             PQgetvalue(res, 0, 2))));
   29 alvherre@kurilemu.de      469                 :CBC         178 :         *server_lsn = ((uint64) hi) << 32 | lo;
                                470                 :                :     }
                                471                 :                : 
 6063 heikki.linnakangas@i      472                 :            432 :     PQclear(res);
                                473                 :                : 
 3557 peter_e@gmx.net           474                 :            432 :     return primary_sysid;
                                475                 :                : }
                                476                 :                : 
                                477                 :                : /*
                                478                 :                :  * Thin wrapper around libpq to obtain server version.
                                479                 :                :  */
                                480                 :                : static int
 2722 peter@eisentraut.org      481                 :           1090 : libpqrcv_server_version(WalReceiverConn *conn)
                                482                 :                : {
                                483                 :           1090 :     return PQserverVersion(conn->streamConn);
                                484                 :                : }
                                485                 :                : 
                                486                 :                : /*
                                487                 :                :  * Get database name from the primary server's conninfo.
                                488                 :                :  *
                                489                 :                :  * If dbname is not found in connInfo, return NULL value.
                                490                 :                :  */
                                491                 :                : static char *
  934 akapila@postgresql.o      492                 :             17 : libpqrcv_get_dbname_from_conninfo(const char *connInfo)
                                493                 :                : {
  233 fujii@postgresql.org      494                 :             17 :     return libpqrcv_get_option_from_conninfo(connInfo, "dbname");
                                495                 :                : }
                                496                 :                : 
                                497                 :                : /*
                                498                 :                :  * Get the value of the option with the given keyword from the primary
                                499                 :                :  * server's conninfo.
                                500                 :                :  *
                                501                 :                :  * If the option is not found in connInfo, return NULL value.
                                502                 :                :  */
                                503                 :                : static char *
                                504                 :            794 : libpqrcv_get_option_from_conninfo(const char *connInfo, const char *keyword)
                                505                 :                : {
                                506                 :                :     PQconninfoOption *opts;
                                507                 :            794 :     char       *option = NULL;
  934 akapila@postgresql.o      508                 :            794 :     char       *err = NULL;
                                509                 :                : 
                                510                 :            794 :     opts = PQconninfoParse(connInfo, &err);
                                511         [ -  + ]:            794 :     if (opts == NULL)
                                512                 :                :     {
                                513                 :                :         /* The error string is malloc'd, so we must free it explicitly */
  934 akapila@postgresql.o      514         [ #  # ]:UBC           0 :         char       *errcopy = err ? pstrdup(err) : "out of memory";
                                515                 :                : 
                                516                 :              0 :         PQfreemem(err);
                                517         [ #  # ]:              0 :         ereport(ERROR,
                                518                 :                :                 (errcode(ERRCODE_SYNTAX_ERROR),
                                519                 :                :                  errmsg("invalid connection string syntax: %s", errcopy)));
                                520                 :                :     }
                                521                 :                : 
  934 akapila@postgresql.o      522         [ +  + ]:CBC       42082 :     for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt)
                                523                 :                :     {
                                524                 :                :         /*
                                525                 :                :          * If the same option appears multiple times, then the last one will
                                526                 :                :          * be returned
                                527                 :                :          */
  233 fujii@postgresql.org      528   [ +  +  +  + ]:          41288 :         if (strcmp(opt->keyword, keyword) == 0 && opt->val &&
  934 akapila@postgresql.o      529         [ +  - ]:             25 :             *opt->val)
                                530                 :                :         {
  233 fujii@postgresql.org      531         [ -  + ]:             25 :             if (option)
  233 fujii@postgresql.org      532                 :UBC           0 :                 pfree(option);
                                533                 :                : 
  233 fujii@postgresql.org      534                 :CBC          25 :             option = pstrdup(opt->val);
                                535                 :                :         }
                                536                 :                :     }
                                537                 :                : 
  934 akapila@postgresql.o      538                 :            794 :     PQconninfoFree(opts);
  233 fujii@postgresql.org      539                 :            794 :     return option;
                                540                 :                : }
                                541                 :                : 
                                542                 :                : /*
                                543                 :                :  * Append a suitably-quoted identifier or string literal to buf.
                                544                 :                :  * "quote" should be either a double-quote or single-quote character.
                                545                 :                :  *
                                546                 :                :  * Caution: this quoting logic is sufficient for identifiers and literals
                                547                 :                :  * in the replication grammar, but not always in regular SQL.  Specifically,
                                548                 :                :  * it'd fail for a string literal if standard_conforming_strings is off.
                                549                 :                :  */
                                550                 :                : static void
   73 tgl@sss.pgh.pa.us         551                 :           2906 : appendQuotedString(StringInfo buf, const char *str, char quote)
                                552                 :                : {
                                553                 :           2906 :     appendStringInfoChar(buf, quote);
                                554         [ +  + ]:          43353 :     while (*str)
                                555                 :                :     {
                                556                 :          40447 :         char        c = *str++;
                                557                 :                : 
                                558         [ -  + ]:          40447 :         if (c == quote)
   73 tgl@sss.pgh.pa.us         559                 :UBC           0 :             appendStringInfoChar(buf, c);
   73 tgl@sss.pgh.pa.us         560                 :CBC       40447 :         appendStringInfoChar(buf, c);
                                561                 :                :     }
                                562                 :           2906 :     appendStringInfoChar(buf, quote);
                                563                 :           2906 : }
                                564                 :                : 
                                565                 :                : #define appendQuotedIdentifier(b, s)    appendQuotedString(b, s, '"')
                                566                 :                : #define appendQuotedLiteral(b, s)       appendQuotedString(b, s, '\'')
                                567                 :                : 
                                568                 :                : /*
                                569                 :                :  * Start streaming WAL data from given streaming options.
                                570                 :                :  *
                                571                 :                :  * Returns true if we switched successfully to copy-both mode. False
                                572                 :                :  * means the server received the command and executed it successfully, but
                                573                 :                :  * didn't switch to copy-mode.  That means that there was no WAL on the
                                574                 :                :  * requested timeline and starting point, because the server switched to
                                575                 :                :  * another timeline at or before the requested starting point. On failure,
                                576                 :                :  * throws an ERROR.
                                577                 :                :  */
                                578                 :                : static bool
 3557 peter_e@gmx.net           579                 :            629 : libpqrcv_startstreaming(WalReceiverConn *conn,
                                580                 :                :                         const WalRcvStreamOptions *options)
                                581                 :                : {
                                582                 :                :     StringInfoData cmd;
                                583                 :                :     PGresult   *res;
                                584                 :                : 
 3507                           585         [ -  + ]:            629 :     Assert(options->logical == conn->logical);
                                586   [ +  +  -  + ]:            629 :     Assert(options->slotname || !options->logical);
                                587                 :                : 
 3557                           588                 :            629 :     initStringInfo(&cmd);
                                589                 :                : 
                                590                 :                :     /* Build the command. */
 3507                           591                 :            629 :     appendStringInfoString(&cmd, "START_REPLICATION");
                                592         [ +  + ]:            629 :     if (options->slotname != NULL)
                                593                 :                :     {
   73 tgl@sss.pgh.pa.us         594                 :            505 :         appendStringInfoString(&cmd, " SLOT ");
                                595                 :            505 :         appendQuotedIdentifier(&cmd, options->slotname);
                                596                 :                :     }
                                597                 :                : 
 3507 peter_e@gmx.net           598         [ +  + ]:            629 :     if (options->logical)
 3299                           599                 :            453 :         appendStringInfoString(&cmd, " LOGICAL");
                                600                 :                : 
  416 alvherre@kurilemu.de      601                 :            629 :     appendStringInfo(&cmd, " %X/%08X", LSN_FORMAT_ARGS(options->startpoint));
                                602                 :                : 
                                603                 :                :     /*
                                604                 :                :      * Additional options are different depending on if we are doing logical
                                605                 :                :      * or physical replication.
                                606                 :                :      */
 3507 peter_e@gmx.net           607         [ +  + ]:            629 :     if (options->logical)
                                608                 :                :     {
                                609                 :                :         char       *pubnames_str;
                                610                 :                :         List       *pubnames;
                                611                 :                : 
                                612                 :            453 :         appendStringInfoString(&cmd, " (");
                                613                 :                : 
                                614                 :            453 :         appendStringInfo(&cmd, "proto_version '%u'",
                                615                 :            453 :                          options->proto.logical.proto_version);
                                616                 :                : 
 1326 akapila@postgresql.o      617         [ +  + ]:            453 :         if (options->proto.logical.streaming_str)
                                618                 :                :         {
   73 tgl@sss.pgh.pa.us         619                 :            445 :             appendStringInfoString(&cmd, ", streaming ");
                                620                 :            445 :             appendQuotedLiteral(&cmd, options->proto.logical.streaming_str);
                                621                 :                :         }
                                622                 :                : 
 1870 akapila@postgresql.o      623   [ +  +  +  - ]:            460 :         if (options->proto.logical.twophase &&
                                624                 :              7 :             PQserverVersion(conn->streamConn) >= 150000)
                                625                 :              7 :             appendStringInfoString(&cmd, ", two_phase 'on'");
                                626                 :                : 
 1498                           627   [ +  -  +  - ]:            906 :         if (options->proto.logical.origin &&
                                628                 :            453 :             PQserverVersion(conn->streamConn) >= 160000)
                                629                 :                :         {
   73 tgl@sss.pgh.pa.us         630                 :            453 :             appendStringInfoString(&cmd, ", origin ");
                                631                 :            453 :             appendQuotedLiteral(&cmd, options->proto.logical.origin);
                                632                 :                :         }
                                633                 :                : 
 3507 peter_e@gmx.net           634                 :            453 :         pubnames = options->proto.logical.publication_names;
   73 tgl@sss.pgh.pa.us         635                 :            453 :         pubnames_str = stringlist_to_identifierstr(pubnames);
                                636                 :            453 :         appendStringInfoString(&cmd, ", publication_names ");
                                637                 :            453 :         appendQuotedLiteral(&cmd, pubnames_str);
 3507 peter_e@gmx.net           638                 :            453 :         pfree(pubnames_str);
                                639                 :                : 
 2231 tgl@sss.pgh.pa.us         640   [ +  +  +  - ]:            464 :         if (options->proto.logical.binary &&
                                641                 :             11 :             PQserverVersion(conn->streamConn) >= 140000)
                                642                 :             11 :             appendStringInfoString(&cmd, ", binary 'true'");
                                643                 :                : 
 3503 peter_e@gmx.net           644                 :            453 :         appendStringInfoChar(&cmd, ')');
                                645                 :                :     }
                                646                 :                :     else
 3507                           647                 :            176 :         appendStringInfo(&cmd, " TIMELINE %u",
                                648                 :            176 :                          options->proto.physical.startpointTLI);
                                649                 :                : 
                                650                 :                :     /* Start streaming. */
  510 heikki.linnakangas@i      651                 :            629 :     res = libpqsrv_exec(conn->streamConn,
                                652                 :            629 :                         cmd.data,
                                653                 :                :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 3557 peter_e@gmx.net           654                 :            628 :     pfree(cmd.data);
                                655                 :                : 
 5005 heikki.linnakangas@i      656         [ -  + ]:            628 :     if (PQresultStatus(res) == PGRES_COMMAND_OK)
                                657                 :                :     {
 5005 heikki.linnakangas@i      658                 :UBC           0 :         PQclear(res);
                                659                 :              0 :         return false;
                                660                 :                :     }
 5005 heikki.linnakangas@i      661         [ +  + ]:CBC         628 :     else if (PQresultStatus(res) != PGRES_COPY_BOTH)
 6063                           662         [ +  - ]:              1 :         ereport(ERROR,
                                663                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                664                 :                :                  errmsg("could not start WAL streaming: %s",
                                665                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
                                666                 :            627 :     PQclear(res);
 5005                           667                 :            627 :     return true;
                                668                 :                : }
                                669                 :                : 
                                670                 :                : /*
                                671                 :                :  * Stop streaming WAL data. Returns the next timeline's ID in *next_tli, as
                                672                 :                :  * reported by the server, or 0 if it did not report it.
                                673                 :                :  */
                                674                 :                : static void
 3557 peter_e@gmx.net           675                 :            259 : libpqrcv_endstreaming(WalReceiverConn *conn, TimeLineID *next_tli)
                                676                 :                : {
                                677                 :                :     PGresult   *res;
                                678                 :                : 
                                679                 :                :     /*
                                680                 :                :      * Send copy-end message.  As in libpqsrv_exec, this could theoretically
                                681                 :                :      * block, but the risk seems small.
                                682                 :                :      */
                                683   [ +  +  -  + ]:            471 :     if (PQputCopyEnd(conn->streamConn, NULL) <= 0 ||
                                684                 :            212 :         PQflush(conn->streamConn))
 5005 heikki.linnakangas@i      685         [ +  - ]:             47 :         ereport(ERROR,
                                686                 :                :                 (errcode(ERRCODE_CONNECTION_FAILURE),
                                687                 :                :                  errmsg("could not send end-of-streaming message to primary: %s",
                                688                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
                                689                 :                : 
 3557 peter_e@gmx.net           690                 :            212 :     *next_tli = 0;
                                691                 :                : 
                                692                 :                :     /*
                                693                 :                :      * After COPY is finished, we should receive a result set indicating the
                                694                 :                :      * next timeline's ID, or just CommandComplete if the server was shut
                                695                 :                :      * down.
                                696                 :                :      *
                                697                 :                :      * If we had not yet received CopyDone from the backend, PGRES_COPY_OUT is
                                698                 :                :      * also possible in case we aborted the copy in mid-stream.
                                699                 :                :      */
  510 heikki.linnakangas@i      700                 :            212 :     res = libpqsrv_get_result(conn->streamConn,
                                701                 :                :                               WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 4969                           702         [ +  + ]:            212 :     if (PQresultStatus(res) == PGRES_TUPLES_OK)
                                703                 :                :     {
                                704                 :                :         /*
                                705                 :                :          * Read the next timeline's ID. The server also sends the timeline's
                                706                 :                :          * starting point, but it is ignored.
                                707                 :                :          */
 4859                           708   [ +  -  -  + ]:             13 :         if (PQnfields(res) < 2 || PQntuples(res) != 1)
 4969 heikki.linnakangas@i      709         [ #  # ]:UBC           0 :             ereport(ERROR,
                                710                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                711                 :                :                      errmsg("unexpected result set after end-of-streaming")));
 2958 andres@anarazel.de        712                 :CBC          13 :         *next_tli = pg_strtoint32(PQgetvalue(res, 0, 0));
 5005 heikki.linnakangas@i      713                 :             13 :         PQclear(res);
                                714                 :                : 
                                715                 :                :         /* the result set should be followed by CommandComplete */
  510                           716                 :             13 :         res = libpqsrv_get_result(conn->streamConn,
                                717                 :                :                                   WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
                                718                 :                :     }
 3557 peter_e@gmx.net           719         [ +  - ]:            199 :     else if (PQresultStatus(res) == PGRES_COPY_OUT)
                                720                 :                :     {
                                721                 :            199 :         PQclear(res);
                                722                 :                : 
                                723                 :                :         /* End the copy */
 3345 tgl@sss.pgh.pa.us         724         [ -  + ]:            199 :         if (PQendcopy(conn->streamConn))
 3345 tgl@sss.pgh.pa.us         725         [ #  # ]:UBC           0 :             ereport(ERROR,
                                726                 :                :                     (errcode(ERRCODE_CONNECTION_FAILURE),
                                727                 :                :                      errmsg("error while shutting down streaming COPY: %s",
                                728                 :                :                             pchomp(PQerrorMessage(conn->streamConn)))));
                                729                 :                : 
                                730                 :                :         /* CommandComplete should follow */
  510 heikki.linnakangas@i      731                 :CBC         199 :         res = libpqsrv_get_result(conn->streamConn,
                                732                 :                :                                   WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
                                733                 :                :     }
                                734                 :                : 
 4969                           735         [ -  + ]:            212 :     if (PQresultStatus(res) != PGRES_COMMAND_OK)
 4969 heikki.linnakangas@i      736         [ #  # ]:UBC           0 :         ereport(ERROR,
                                737                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                738                 :                :                  errmsg("error reading result of streaming command: %s",
                                739                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
 4215 tgl@sss.pgh.pa.us         740                 :CBC         212 :     PQclear(res);
                                741                 :                : 
                                742                 :                :     /* Verify that there are no more results */
  510 heikki.linnakangas@i      743                 :            212 :     res = libpqsrv_get_result(conn->streamConn,
                                744                 :                :                               WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 4969                           745         [ -  + ]:            212 :     if (res != NULL)
 4969 heikki.linnakangas@i      746         [ #  # ]:UBC           0 :         ereport(ERROR,
                                747                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                748                 :                :                  errmsg("unexpected result after CommandComplete: %s",
                                749                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
 5005 heikki.linnakangas@i      750                 :CBC         212 : }
                                751                 :                : 
                                752                 :                : /*
                                753                 :                :  * Fetch the timeline history file for 'tli' from primary.
                                754                 :                :  */
                                755                 :                : static void
 3557 peter_e@gmx.net           756                 :             12 : libpqrcv_readtimelinehistoryfile(WalReceiverConn *conn,
                                757                 :                :                                  TimeLineID tli, char **filename,
                                758                 :                :                                  char **content, size_t *len)
                                759                 :                : {
                                760                 :                :     PGresult   *res;
                                761                 :                :     char        cmd[64];
                                762                 :                : 
                                763         [ -  + ]:             12 :     Assert(!conn->logical);
                                764                 :                : 
                                765                 :                :     /*
                                766                 :                :      * Request the primary to send over the history file for given timeline.
                                767                 :                :      */
 5005 heikki.linnakangas@i      768                 :             12 :     snprintf(cmd, sizeof(cmd), "TIMELINE_HISTORY %u", tli);
  510                           769                 :             12 :     res = libpqsrv_exec(conn->streamConn,
                                770                 :                :                         cmd,
                                771                 :                :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 5005                           772         [ -  + ]:             12 :     if (PQresultStatus(res) != PGRES_TUPLES_OK)
 5005 heikki.linnakangas@i      773         [ #  # ]:UBC           0 :         ereport(ERROR,
                                774                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                775                 :                :                  errmsg("could not receive timeline history file from "
                                776                 :                :                         "the primary server: %s",
                                777                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
 5005 heikki.linnakangas@i      778   [ +  -  -  + ]:CBC          12 :     if (PQnfields(res) != 2 || PQntuples(res) != 1)
 5005 heikki.linnakangas@i      779         [ #  # ]:UBC           0 :         ereport(ERROR,
                                780                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                781                 :                :                  errmsg("invalid response from primary server"),
                                782                 :                :                  errdetail("Expected 1 tuple with 2 fields, got %d tuples with %d fields.",
                                783                 :                :                            PQntuples(res), PQnfields(res))));
 5005 heikki.linnakangas@i      784                 :CBC          12 :     *filename = pstrdup(PQgetvalue(res, 0, 0));
                                785                 :                : 
                                786                 :             12 :     *len = PQgetlength(res, 0, 1);
                                787                 :             12 :     *content = palloc(*len);
                                788                 :             12 :     memcpy(*content, PQgetvalue(res, 0, 1), *len);
                                789                 :             12 :     PQclear(res);
 6063                           790                 :             12 : }
                                791                 :                : 
                                792                 :                : /*
                                793                 :                :  * Disconnect connection to primary, if any.
                                794                 :                :  */
                                795                 :                : static void
 3557 peter_e@gmx.net           796                 :            919 : libpqrcv_disconnect(WalReceiverConn *conn)
                                797                 :                : {
  510 heikki.linnakangas@i      798                 :            919 :     libpqsrv_disconnect(conn->streamConn);
 1462 peter@eisentraut.org      799                 :            919 :     PQfreemem(conn->recvBuf);
 3557 peter_e@gmx.net           800                 :            919 :     pfree(conn);
 6063 heikki.linnakangas@i      801                 :            919 : }
                                802                 :                : 
                                803                 :                : /*
                                804                 :                :  * Receive a message available from XLOG stream.
                                805                 :                :  *
                                806                 :                :  * Returns:
                                807                 :                :  *
                                808                 :                :  *   If data was received, returns the length of the data. *buffer is set to
                                809                 :                :  *   point to a buffer holding the received message. The buffer is only valid
                                810                 :                :  *   until the next libpqrcv_* call.
                                811                 :                :  *
                                812                 :                :  *   If no data was available immediately, returns 0, and *wait_fd is set to a
                                813                 :                :  *   socket descriptor which can be waited on before trying again.
                                814                 :                :  *
                                815                 :                :  *   -1 if the server ended the COPY.
                                816                 :                :  *
                                817                 :                :  * ereports on error.
                                818                 :                :  */
                                819                 :                : static int
 3557 peter_e@gmx.net           820                 :         451304 : libpqrcv_receive(WalReceiverConn *conn, char **buffer,
                                821                 :                :                  pgsocket *wait_fd)
                                822                 :                : {
                                823                 :                :     int         rawlen;
                                824                 :                : 
 1462 peter@eisentraut.org      825                 :         451304 :     PQfreemem(conn->recvBuf);
 3557 peter_e@gmx.net           826                 :         451304 :     conn->recvBuf = NULL;
                                827                 :                : 
                                828                 :                :     /* Try to receive a CopyData message */
                                829                 :         451304 :     rawlen = PQgetCopyData(conn->streamConn, &conn->recvBuf, 1);
 5705 heikki.linnakangas@i      830         [ +  + ]:         451304 :     if (rawlen == 0)
                                831                 :                :     {
                                832                 :                :         /* Try consuming some data. */
 3557 peter_e@gmx.net           833         [ +  + ]:         253540 :         if (PQconsumeInput(conn->streamConn) == 0)
 6063 heikki.linnakangas@i      834         [ +  - ]:             47 :             ereport(ERROR,
                                835                 :                :                     (errcode(ERRCODE_CONNECTION_FAILURE),
                                836                 :                :                      errmsg("could not receive data from WAL stream: %s",
                                837                 :                :                             pchomp(PQerrorMessage(conn->streamConn)))));
                                838                 :                : 
                                839                 :                :         /* Now that we've consumed some input, try again */
 3557 peter_e@gmx.net           840                 :         253493 :         rawlen = PQgetCopyData(conn->streamConn, &conn->recvBuf, 1);
 5705 heikki.linnakangas@i      841         [ +  + ]:         253493 :         if (rawlen == 0)
                                842                 :                :         {
                                843                 :                :             /* Tell caller to try again when our socket is ready. */
 3557 peter_e@gmx.net           844                 :         112556 :             *wait_fd = PQsocket(conn->streamConn);
 5005 heikki.linnakangas@i      845                 :         112556 :             return 0;
                                846                 :                :         }
                                847                 :                :     }
 6026 bruce@momjian.us          848         [ +  + ]:         338701 :     if (rawlen == -1)           /* end-of-streaming or error */
                                849                 :                :     {
                                850                 :                :         PGresult   *res;
                                851                 :                : 
  510 heikki.linnakangas@i      852                 :            271 :         res = libpqsrv_get_result(conn->streamConn,
                                853                 :                :                                   WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 3444 peter_e@gmx.net           854         [ +  + ]:            271 :         if (PQresultStatus(res) == PGRES_COMMAND_OK)
                                855                 :                :         {
                                856                 :            255 :             PQclear(res);
                                857                 :                : 
                                858                 :                :             /* Verify that there are no more results. */
  510 heikki.linnakangas@i      859                 :            255 :             res = libpqsrv_get_result(conn->streamConn,
                                860                 :                :                                       WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 3444 peter_e@gmx.net           861         [ +  + ]:            255 :             if (res != NULL)
                                862                 :                :             {
 3367 andres@anarazel.de        863                 :             48 :                 PQclear(res);
                                864                 :                : 
                                865                 :                :                 /*
                                866                 :                :                  * If the other side closed the connection orderly (otherwise
                                867                 :                :                  * we'd seen an error, or PGRES_COPY_IN) don't report an error
                                868                 :                :                  * here, but let callers deal with it.
                                869                 :                :                  */
                                870         [ +  - ]:             48 :                 if (PQstatus(conn->streamConn) == CONNECTION_BAD)
                                871                 :             48 :                     return -1;
                                872                 :                : 
 3444 peter_e@gmx.net           873         [ #  # ]:UBC           0 :                 ereport(ERROR,
                                874                 :                :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                875                 :                :                          errmsg("unexpected result after CommandComplete: %s",
                                876                 :                :                                 PQerrorMessage(conn->streamConn))));
                                877                 :                :             }
                                878                 :                : 
 3444 peter_e@gmx.net           879                 :CBC         207 :             return -1;
                                880                 :                :         }
                                881         [ +  + ]:             16 :         else if (PQresultStatus(res) == PGRES_COPY_IN)
                                882                 :                :         {
 5005 heikki.linnakangas@i      883                 :             13 :             PQclear(res);
                                884                 :             13 :             return -1;
                                885                 :                :         }
                                886                 :                :         else
 6063                           887         [ +  - ]:              3 :             ereport(ERROR,
                                888                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                889                 :                :                      errmsg("could not receive data from WAL stream: %s",
                                890                 :                :                             pchomp(PQerrorMessage(conn->streamConn)))));
                                891                 :                :     }
                                892         [ -  + ]:         338430 :     if (rawlen < -1)
 6063 heikki.linnakangas@i      893         [ #  # ]:UBC           0 :         ereport(ERROR,
                                894                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                895                 :                :                  errmsg("could not receive data from WAL stream: %s",
                                896                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
                                897                 :                : 
                                898                 :                :     /* Return received messages to caller */
 3557 peter_e@gmx.net           899                 :CBC      338430 :     *buffer = conn->recvBuf;
 5005 heikki.linnakangas@i      900                 :         338430 :     return rawlen;
                                901                 :                : }
                                902                 :                : 
                                903                 :                : /*
                                904                 :                :  * Send a message to XLOG stream.
                                905                 :                :  *
                                906                 :                :  * ereports on error.
                                907                 :                :  */
                                908                 :                : static void
 3557 peter_e@gmx.net           909                 :         155871 : libpqrcv_send(WalReceiverConn *conn, const char *buffer, int nbytes)
                                910                 :                : {
                                911   [ +  +  +  + ]:         311741 :     if (PQputCopyData(conn->streamConn, buffer, nbytes) <= 0 ||
                                912                 :         155870 :         PQflush(conn->streamConn))
 5738 rhaas@postgresql.org      913         [ +  - ]:              2 :         ereport(ERROR,
                                914                 :                :                 (errcode(ERRCODE_CONNECTION_FAILURE),
                                915                 :                :                  errmsg("could not send data to WAL stream: %s",
                                916                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
                                917                 :         155869 : }
                                918                 :                : 
                                919                 :                : /*
                                920                 :                :  * Create new replication slot.
                                921                 :                :  * Returns the name of the exported snapshot for logical slot or NULL for
                                922                 :                :  * physical slot.
                                923                 :                :  */
                                924                 :                : static char *
 3507 peter_e@gmx.net           925                 :            333 : libpqrcv_create_slot(WalReceiverConn *conn, const char *slotname,
                                926                 :                :                      bool temporary, bool two_phase, bool failover,
                                927                 :                :                      CRSSnapshotAction snapshot_action, XLogRecPtr *lsn)
                                928                 :                : {
                                929                 :                :     PGresult   *res;
                                930                 :                :     StringInfoData cmd;
                                931                 :                :     char       *snapshot;
                                932                 :                :     int         use_new_options_syntax;
                                933                 :                : 
 1787 rhaas@postgresql.org      934                 :            333 :     use_new_options_syntax = (PQserverVersion(conn->streamConn) >= 150000);
                                935                 :                : 
 3507 peter_e@gmx.net           936                 :            333 :     initStringInfo(&cmd);
                                937                 :                : 
   73 tgl@sss.pgh.pa.us         938                 :            333 :     appendStringInfoString(&cmd, "CREATE_REPLICATION_SLOT ");
                                939                 :            333 :     appendQuotedIdentifier(&cmd, slotname);
                                940                 :                : 
 3507 peter_e@gmx.net           941         [ -  + ]:            333 :     if (temporary)
 3299 peter_e@gmx.net           942                 :UBC           0 :         appendStringInfoString(&cmd, " TEMPORARY");
                                943                 :                : 
 3507 peter_e@gmx.net           944         [ +  - ]:CBC         333 :     if (conn->logical)
                                945                 :                :     {
 1787 rhaas@postgresql.org      946                 :            333 :         appendStringInfoString(&cmd, " LOGICAL pgoutput ");
                                947         [ +  - ]:            333 :         if (use_new_options_syntax)
                                948                 :            333 :             appendStringInfoChar(&cmd, '(');
 1870 akapila@postgresql.o      949         [ +  + ]:            333 :         if (two_phase)
                                950                 :                :         {
 1787 rhaas@postgresql.org      951                 :              1 :             appendStringInfoString(&cmd, "TWO_PHASE");
                                952         [ +  - ]:              1 :             if (use_new_options_syntax)
                                953                 :              1 :                 appendStringInfoString(&cmd, ", ");
                                954                 :                :             else
 1787 rhaas@postgresql.org      955                 :UBC           0 :                 appendStringInfoChar(&cmd, ' ');
                                956                 :                :         }
                                957                 :                : 
  941 akapila@postgresql.o      958         [ +  + ]:CBC         333 :         if (failover)
                                959                 :                :         {
                                960                 :             11 :             appendStringInfoString(&cmd, "FAILOVER");
                                961         [ +  - ]:             11 :             if (use_new_options_syntax)
                                962                 :             11 :                 appendStringInfoString(&cmd, ", ");
                                963                 :                :             else
  941 akapila@postgresql.o      964                 :UBC           0 :                 appendStringInfoChar(&cmd, ' ');
                                965                 :                :         }
                                966                 :                : 
 1787 rhaas@postgresql.org      967         [ +  - ]:CBC         333 :         if (use_new_options_syntax)
                                968                 :                :         {
                                969   [ -  +  +  - ]:            333 :             switch (snapshot_action)
                                970                 :                :             {
 1787 rhaas@postgresql.org      971                 :UBC           0 :                 case CRS_EXPORT_SNAPSHOT:
                                972                 :              0 :                     appendStringInfoString(&cmd, "SNAPSHOT 'export'");
                                973                 :              0 :                     break;
 1787 rhaas@postgresql.org      974                 :CBC         122 :                 case CRS_NOEXPORT_SNAPSHOT:
                                975                 :            122 :                     appendStringInfoString(&cmd, "SNAPSHOT 'nothing'");
                                976                 :            122 :                     break;
                                977                 :            211 :                 case CRS_USE_SNAPSHOT:
                                978                 :            211 :                     appendStringInfoString(&cmd, "SNAPSHOT 'use'");
                                979                 :            211 :                     break;
                                980                 :                :             }
                                981                 :                :         }
                                982                 :                :         else
                                983                 :                :         {
 1787 rhaas@postgresql.org      984   [ #  #  #  # ]:UBC           0 :             switch (snapshot_action)
                                985                 :                :             {
                                986                 :              0 :                 case CRS_EXPORT_SNAPSHOT:
                                987                 :              0 :                     appendStringInfoString(&cmd, "EXPORT_SNAPSHOT");
                                988                 :              0 :                     break;
                                989                 :              0 :                 case CRS_NOEXPORT_SNAPSHOT:
                                990                 :              0 :                     appendStringInfoString(&cmd, "NOEXPORT_SNAPSHOT");
                                991                 :              0 :                     break;
                                992                 :              0 :                 case CRS_USE_SNAPSHOT:
                                993                 :              0 :                     appendStringInfoString(&cmd, "USE_SNAPSHOT");
                                994                 :              0 :                     break;
                                995                 :                :             }
                                996                 :                :         }
                                997                 :                : 
 1787 rhaas@postgresql.org      998         [ +  - ]:CBC         333 :         if (use_new_options_syntax)
                                999                 :            333 :             appendStringInfoChar(&cmd, ')');
                               1000                 :                :     }
                               1001                 :                :     else
                               1002                 :                :     {
 1787 rhaas@postgresql.org     1003         [ #  # ]:UBC           0 :         if (use_new_options_syntax)
                               1004                 :              0 :             appendStringInfoString(&cmd, " PHYSICAL (RESERVE_WAL)");
                               1005                 :                :         else
                               1006                 :              0 :             appendStringInfoString(&cmd, " PHYSICAL RESERVE_WAL");
                               1007                 :                :     }
                               1008                 :                : 
  510 heikki.linnakangas@i     1009                 :CBC         333 :     res = libpqsrv_exec(conn->streamConn,
                               1010                 :            333 :                         cmd.data,
                               1011                 :                :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 3507 peter_e@gmx.net          1012                 :            333 :     pfree(cmd.data);
                               1013                 :                : 
                               1014         [ -  + ]:            333 :     if (PQresultStatus(res) != PGRES_TUPLES_OK)
 3507 peter_e@gmx.net          1015         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1016                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1017                 :                :                  errmsg("could not create replication slot \"%s\": %s",
                               1018                 :                :                         slotname, pchomp(PQerrorMessage(conn->streamConn)))));
                               1019                 :                : 
                               1020                 :                :     /* CREATE_REPLICATION_SLOT returns a single row with four columns */
   42 fujii@postgresql.org     1021   [ +  -  -  + ]:CBC         333 :     if (PQnfields(res) != 4 || PQntuples(res) != 1)
   42 fujii@postgresql.org     1022         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1023                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1024                 :                :                  errmsg("invalid response from primary server"),
                               1025                 :                :                  errdetail("Could not create replication slot \"%s\": got %d rows and %d fields, expected %d rows and %d fields.",
                               1026                 :                :                            slotname, PQntuples(res), PQnfields(res), 1, 4)));
                               1027                 :                : 
 2420 peter@eisentraut.org     1028         [ +  + ]:CBC         333 :     if (lsn)
                               1029                 :            211 :         *lsn = DatumGetLSN(DirectFunctionCall1Coll(pg_lsn_in, InvalidOid,
                               1030                 :            211 :                                                    CStringGetDatum(PQgetvalue(res, 0, 1))));
                               1031                 :                : 
 3507 peter_e@gmx.net          1032         [ -  + ]:            333 :     if (!PQgetisnull(res, 0, 2))
 3507 peter_e@gmx.net          1033                 :UBC           0 :         snapshot = pstrdup(PQgetvalue(res, 0, 2));
                               1034                 :                :     else
 3507 peter_e@gmx.net          1035                 :CBC         333 :         snapshot = NULL;
                               1036                 :                : 
                               1037                 :            333 :     PQclear(res);
                               1038                 :                : 
                               1039                 :            333 :     return snapshot;
                               1040                 :                : }
                               1041                 :                : 
                               1042                 :                : /*
                               1043                 :                :  * Change the definition of the replication slot.
                               1044                 :                :  */
                               1045                 :                : static void
  941 akapila@postgresql.o     1046                 :              5 : libpqrcv_alter_slot(WalReceiverConn *conn, const char *slotname,
                               1047                 :                :                     const bool *failover, const bool *two_phase)
                               1048                 :                : {
                               1049                 :                :     StringInfoData cmd;
                               1050                 :                :     PGresult   *res;
                               1051                 :                : 
                               1052                 :              5 :     initStringInfo(&cmd);
   73 tgl@sss.pgh.pa.us        1053                 :              5 :     appendStringInfoString(&cmd, "ALTER_REPLICATION_SLOT ");
                               1054                 :              5 :     appendQuotedIdentifier(&cmd, slotname);
                               1055                 :              5 :     appendStringInfoString(&cmd, " ( ");
                               1056                 :                : 
  764 akapila@postgresql.o     1057         [ +  + ]:              5 :     if (failover)
                               1058                 :              4 :         appendStringInfo(&cmd, "FAILOVER %s",
                               1059         [ +  + ]:              4 :                          *failover ? "true" : "false");
                               1060                 :                : 
                               1061   [ +  +  -  + ]:              5 :     if (failover && two_phase)
  503 drowley@postgresql.o     1062                 :UBC           0 :         appendStringInfoString(&cmd, ", ");
                               1063                 :                : 
  764 akapila@postgresql.o     1064         [ +  + ]:CBC           5 :     if (two_phase)
                               1065                 :              1 :         appendStringInfo(&cmd, "TWO_PHASE %s",
                               1066         [ -  + ]:              1 :                          *two_phase ? "true" : "false");
                               1067                 :                : 
                               1068                 :              5 :     appendStringInfoString(&cmd, " );");
                               1069                 :                : 
  510 heikki.linnakangas@i     1070                 :              5 :     res = libpqsrv_exec(conn->streamConn, cmd.data,
                               1071                 :                :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
  941 akapila@postgresql.o     1072                 :              5 :     pfree(cmd.data);
                               1073                 :                : 
                               1074         [ -  + ]:              5 :     if (PQresultStatus(res) != PGRES_COMMAND_OK)
  941 akapila@postgresql.o     1075         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1076                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1077                 :                :                  errmsg("could not alter replication slot \"%s\": %s",
                               1078                 :                :                         slotname, pchomp(PQerrorMessage(conn->streamConn)))));
                               1079                 :                : 
  941 akapila@postgresql.o     1080                 :CBC           5 :     PQclear(res);
                               1081                 :              5 : }
                               1082                 :                : 
                               1083                 :                : /*
                               1084                 :                :  * Return PID of remote backend process.
                               1085                 :                :  */
                               1086                 :                : static pid_t
 2417 peter@eisentraut.org     1087                 :UBC           0 : libpqrcv_get_backend_pid(WalReceiverConn *conn)
                               1088                 :                : {
                               1089                 :              0 :     return PQbackendPID(conn->streamConn);
                               1090                 :                : }
                               1091                 :                : 
                               1092                 :                : /*
                               1093                 :                :  * Convert tuple query result to tuplestore.
                               1094                 :                :  */
                               1095                 :                : static void
 3444 peter_e@gmx.net          1096                 :CBC        1256 : libpqrcv_processTuples(PGresult *pgres, WalRcvExecResult *walres,
                               1097                 :                :                        const int nRetTypes, const Oid *retTypes)
                               1098                 :                : {
                               1099                 :                :     int         tupn;
                               1100                 :                :     int         coln;
 3389 bruce@momjian.us         1101                 :           1256 :     int         nfields = PQnfields(pgres);
                               1102                 :                :     HeapTuple   tuple;
                               1103                 :                :     AttInMetadata *attinmeta;
                               1104                 :                :     MemoryContext rowcontext;
                               1105                 :                :     MemoryContext oldcontext;
                               1106                 :                : 
                               1107                 :                :     /* Make sure we got expected number of fields. */
 3444 peter_e@gmx.net          1108         [ -  + ]:           1256 :     if (nfields != nRetTypes)
 3444 peter_e@gmx.net          1109         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1110                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1111                 :                :                  errmsg("invalid query response"),
                               1112                 :                :                  errdetail("Expected %d fields, got %d fields.",
                               1113                 :                :                            nRetTypes, nfields)));
                               1114                 :                : 
 3444 peter_e@gmx.net          1115                 :CBC        1256 :     walres->tuplestore = tuplestore_begin_heap(true, false, work_mem);
                               1116                 :                : 
                               1117                 :                :     /* Create tuple descriptor corresponding to expected result. */
 2837 andres@anarazel.de       1118                 :           1256 :     walres->tupledesc = CreateTemplateTupleDesc(nRetTypes);
 3444 peter_e@gmx.net          1119         [ +  + ]:           4742 :     for (coln = 0; coln < nRetTypes; coln++)
                               1120                 :           3486 :         TupleDescInitEntry(walres->tupledesc, (AttrNumber) coln + 1,
                               1121                 :           3486 :                            PQfname(pgres, coln), retTypes[coln], -1, 0);
  164 drowley@postgresql.o     1122                 :           1256 :     TupleDescFinalize(walres->tupledesc);
 3444 peter_e@gmx.net          1123                 :           1256 :     attinmeta = TupleDescGetAttInMetadata(walres->tupledesc);
                               1124                 :                : 
                               1125                 :                :     /* No point in doing more here if there were no tuples returned. */
 3443                          1126         [ +  + ]:           1256 :     if (PQntuples(pgres) == 0)
                               1127                 :             37 :         return;
                               1128                 :                : 
                               1129                 :                :     /* Create temporary context for local allocations. */
 3444                          1130                 :           1219 :     rowcontext = AllocSetContextCreate(CurrentMemoryContext,
                               1131                 :                :                                        "libpqrcv query result context",
                               1132                 :                :                                        ALLOCSET_DEFAULT_SIZES);
                               1133                 :                : 
                               1134                 :                :     /* Process returned rows. */
                               1135         [ +  + ]:           2836 :     for (tupn = 0; tupn < PQntuples(pgres); tupn++)
                               1136                 :                :     {
                               1137                 :                :         char       *cstrs[MaxTupleAttributeNumber];
                               1138                 :                : 
  510 heikki.linnakangas@i     1139         [ -  + ]:           1617 :         CHECK_FOR_INTERRUPTS();
                               1140                 :                : 
                               1141                 :                :         /* Do the allocations in temporary context. */
 3444 peter_e@gmx.net          1142                 :           1617 :         oldcontext = MemoryContextSwitchTo(rowcontext);
                               1143                 :                : 
                               1144                 :                :         /*
                               1145                 :                :          * Fill cstrs with null-terminated strings of column values.
                               1146                 :                :          */
                               1147         [ +  + ]:           6899 :         for (coln = 0; coln < nfields; coln++)
                               1148                 :                :         {
                               1149         [ +  + ]:           5282 :             if (PQgetisnull(pgres, tupn, coln))
                               1150                 :            685 :                 cstrs[coln] = NULL;
                               1151                 :                :             else
                               1152                 :           4597 :                 cstrs[coln] = PQgetvalue(pgres, tupn, coln);
                               1153                 :                :         }
                               1154                 :                : 
                               1155                 :                :         /* Convert row to a tuple, and add it to the tuplestore */
                               1156                 :           1617 :         tuple = BuildTupleFromCStrings(attinmeta, cstrs);
                               1157                 :           1617 :         tuplestore_puttuple(walres->tuplestore, tuple);
                               1158                 :                : 
                               1159                 :                :         /* Clean up */
                               1160                 :           1617 :         MemoryContextSwitchTo(oldcontext);
                               1161                 :           1617 :         MemoryContextReset(rowcontext);
                               1162                 :                :     }
                               1163                 :                : 
                               1164                 :           1219 :     MemoryContextDelete(rowcontext);
                               1165                 :                : }
                               1166                 :                : 
                               1167                 :                : /*
                               1168                 :                :  * Public interface for sending generic queries (and commands).
                               1169                 :                :  *
                               1170                 :                :  * This can only be called from process connected to database.
                               1171                 :                :  */
                               1172                 :                : static WalRcvExecResult *
                               1173                 :           2170 : libpqrcv_exec(WalReceiverConn *conn, const char *query,
                               1174                 :                :               const int nRetTypes, const Oid *retTypes)
                               1175                 :                : {
                               1176                 :           2170 :     PGresult   *pgres = NULL;
  260 michael@paquier.xyz      1177                 :           2170 :     WalRcvExecResult *walres = palloc0_object(WalRcvExecResult);
                               1178                 :                :     char       *diag_sqlstate;
                               1179                 :                : 
 3444 peter_e@gmx.net          1180         [ -  + ]:           2170 :     if (MyDatabaseId == InvalidOid)
 3444 peter_e@gmx.net          1181         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1182                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               1183                 :                :                  errmsg("the query interface requires a database connection")));
                               1184                 :                : 
  510 heikki.linnakangas@i     1185                 :CBC        2170 :     pgres = libpqsrv_exec(conn->streamConn,
                               1186                 :                :                           query,
                               1187                 :                :                           WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
                               1188                 :                : 
 3444 peter_e@gmx.net          1189   [ +  -  +  -  :           2170 :     switch (PQresultStatus(pgres))
                                        +  -  -  +  
                                                 - ]
                               1190                 :                :     {
                               1191                 :           1256 :         case PGRES_TUPLES_OK:
                               1192                 :                :         case PGRES_SINGLE_TUPLE:
                               1193                 :                :         case PGRES_TUPLES_CHUNK:
                               1194                 :           1256 :             walres->status = WALRCV_OK_TUPLES;
                               1195                 :           1256 :             libpqrcv_processTuples(pgres, walres, nRetTypes, retTypes);
                               1196                 :           1256 :             break;
                               1197                 :                : 
 3444 peter_e@gmx.net          1198                 :UBC           0 :         case PGRES_COPY_IN:
                               1199                 :              0 :             walres->status = WALRCV_OK_COPY_IN;
                               1200                 :              0 :             break;
                               1201                 :                : 
 3444 peter_e@gmx.net          1202                 :CBC         209 :         case PGRES_COPY_OUT:
                               1203                 :            209 :             walres->status = WALRCV_OK_COPY_OUT;
                               1204                 :            209 :             break;
                               1205                 :                : 
 3444 peter_e@gmx.net          1206                 :UBC           0 :         case PGRES_COPY_BOTH:
                               1207                 :              0 :             walres->status = WALRCV_OK_COPY_BOTH;
                               1208                 :              0 :             break;
                               1209                 :                : 
 3444 peter_e@gmx.net          1210                 :CBC         699 :         case PGRES_COMMAND_OK:
                               1211                 :            699 :             walres->status = WALRCV_OK_COMMAND;
                               1212                 :            699 :             break;
                               1213                 :                : 
                               1214                 :                :             /* Empty query is considered error. */
 3444 peter_e@gmx.net          1215                 :UBC           0 :         case PGRES_EMPTY_QUERY:
                               1216                 :              0 :             walres->status = WALRCV_ERROR;
                               1217                 :              0 :             walres->err = _("empty query");
                               1218                 :              0 :             break;
                               1219                 :                : 
 1991 alvherre@alvh.no-ip.     1220                 :              0 :         case PGRES_PIPELINE_SYNC:
                               1221                 :                :         case PGRES_PIPELINE_ABORTED:
                               1222                 :              0 :             walres->status = WALRCV_ERROR;
                               1223                 :              0 :             walres->err = _("unexpected pipeline mode");
                               1224                 :              0 :             break;
                               1225                 :                : 
 3444 peter_e@gmx.net          1226                 :CBC           6 :         case PGRES_NONFATAL_ERROR:
                               1227                 :                :         case PGRES_FATAL_ERROR:
                               1228                 :                :         case PGRES_BAD_RESPONSE:
                               1229                 :              6 :             walres->status = WALRCV_ERROR;
                               1230                 :              6 :             walres->err = pchomp(PQerrorMessage(conn->streamConn));
 2022 akapila@postgresql.o     1231                 :              6 :             diag_sqlstate = PQresultErrorField(pgres, PG_DIAG_SQLSTATE);
                               1232         [ +  + ]:              6 :             if (diag_sqlstate)
                               1233                 :              4 :                 walres->sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
                               1234                 :                :                                                  diag_sqlstate[1],
                               1235                 :                :                                                  diag_sqlstate[2],
                               1236                 :                :                                                  diag_sqlstate[3],
                               1237                 :                :                                                  diag_sqlstate[4]);
 3444 peter_e@gmx.net          1238                 :              6 :             break;
                               1239                 :                :     }
                               1240                 :                : 
                               1241                 :           2170 :     PQclear(pgres);
                               1242                 :                : 
                               1243                 :           2170 :     return walres;
                               1244                 :                : }
                               1245                 :                : 
                               1246                 :                : /*
                               1247                 :                :  * Given a List of strings, return it as single comma separated
                               1248                 :                :  * string, quoting identifiers as needed.
                               1249                 :                :  *
                               1250                 :                :  * This is essentially the reverse of SplitIdentifierString.
                               1251                 :                :  *
                               1252                 :                :  * The caller should pfree the result.
                               1253                 :                :  */
                               1254                 :                : static char *
   73 tgl@sss.pgh.pa.us        1255                 :            453 : stringlist_to_identifierstr(List *strings)
                               1256                 :                : {
                               1257                 :                :     ListCell   *lc;
                               1258                 :                :     StringInfoData res;
 3389 bruce@momjian.us         1259                 :            453 :     bool        first = true;
                               1260                 :                : 
 3507 peter_e@gmx.net          1261                 :            453 :     initStringInfo(&res);
                               1262                 :                : 
 3389 bruce@momjian.us         1263   [ +  -  +  +  :           1165 :     foreach(lc, strings)
                                              +  + ]
                               1264                 :                :     {
                               1265                 :            712 :         char       *val = strVal(lfirst(lc));
                               1266                 :                : 
 3507 peter_e@gmx.net          1267         [ +  + ]:            712 :         if (first)
                               1268                 :            453 :             first = false;
                               1269                 :                :         else
                               1270                 :            259 :             appendStringInfoChar(&res, ',');
   73 tgl@sss.pgh.pa.us        1271                 :            712 :         appendQuotedIdentifier(&res, val);
                               1272                 :                :     }
                               1273                 :                : 
 3507 peter_e@gmx.net          1274                 :            453 :     return res.data;
                               1275                 :                : }
        

Generated by: LCOV version 2.0-1