LCOV - differential code coverage report
Current view: top level - src/backend/replication/libpqwalreceiver - libpqwalreceiver.c (source / functions) Coverage Total Hit UBC GBC GNC CBC DUB DCB
Current: bed3ffbf9d952be6c7d739d068cdce44c046dfb7 vs 574581b50ac9c63dd9e4abebb731a3b67e5b50f6 Lines: 83.8 % 431 361 70 1 5 355 9 5
Current Date: 2026-05-05 10:23:31 +0900 Functions: 95.5 % 22 21 1 8 13
Baseline: lcov-20260505-025707-baseline Branches: 61.2 % 317 194 123 3 191
Baseline Date: 2026-05-05 10:27:06 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 95.5 % 22 21 1 5 16
(360..) days: 83.1 % 409 340 69 1 339
Function coverage date bins:
(30,360] days: 100.0 % 1 1 1
(360..) days: 95.2 % 21 20 1 8 12
Branch coverage date bins:
(30,360] days: 91.7 % 12 11 1 11
(360..) days: 60.0 % 305 183 122 3 180

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

Generated by: LCOV version 2.5.0-beta