LCOV - differential code coverage report
Current view: top level - src/backend/replication/libpqwalreceiver - libpqwalreceiver.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 85.7 % 446 382 64 1 381 2
Current Date: 2026-11-28 16:48:44 +0900 Functions: 100.0 % 23 23 2 21
Baseline: lcov-20261128-baseline Branches: 63.9 % 335 214 1 120 1 1 212
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 7 7 7
(30,360] days: 92.6 % 54 50 4 1 49
(360..) days: 84.4 % 385 325 60 325
Function coverage date bins:
(30,360] days: 100.0 % 4 4 1 3
(360..) days: 100.0 % 19 19 1 18
Branch coverage date bins:
(7,30] days: 83.3 % 12 10 2 10
(30,360] days: 67.9 % 28 19 1 8 1 18
(360..) days: 62.7 % 295 185 110 1 184

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

Generated by: LCOV version 2.0-1