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: d36b728949bf4e37ada1cd23e0f2aaa94f609a70 vs 52e118fe2f7e3381bdaa479816a7f72eda2ae517 Lines: 84.6 % 434 367 67 1 7 359 9 6
Current Date: 2026-06-29 16:15:13 +0200 Functions: 95.7 % 23 22 1 8 14
Baseline: lcov-20260630-baseline Branches: 62.7 % 311 195 116 3 192
Baseline Date: 2026-06-29 13:01:57 +0200 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 96.0 % 25 24 1 24
(30,360] days: 95.8 % 24 23 1 7 16
(360..) days: 83.1 % 385 320 65 1 319
Function coverage date bins:
(7,30] days: 100.0 % 2 2 2
(30,360] days: 100.0 % 1 1 1
(360..) days: 95.0 % 20 19 1 8 11
Branch coverage date bins:
(7,30] days: 75.0 % 4 3 1 3
(30,360] days: 91.7 % 12 11 1 11
(360..) days: 61.4 % 295 181 114 3 178

 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                 :                : 
  461 tgl@sss.pgh.pa.us          40                 :CBC        1091 : 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(List *strings);
                                120                 :                : 
                                121                 :                : /*
                                122                 :                :  * Module initialization function
                                123                 :                :  */
                                124                 :                : void
 6005 heikki.linnakangas@i      125                 :           1091 : _PG_init(void)
                                126                 :                : {
 3499 peter_e@gmx.net           127         [ -  + ]:           1091 :     if (WalReceiverFunctions != NULL)
 6005 heikki.linnakangas@i      128         [ #  # ]:UBC           0 :         elog(ERROR, "libpqwalreceiver already loaded");
 3499 peter_e@gmx.net           129                 :CBC        1091 :     WalReceiverFunctions = &PQWalReceiverFunctions;
 6005 heikki.linnakangas@i      130                 :           1091 : }
                                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 *
  876 akapila@postgresql.o      148                 :           1015 : 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];
 3499 peter_e@gmx.net           154                 :           1015 :     int         i = 0;
  175 fujii@postgresql.org      155                 :           1015 :     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                 :                :      */
  900 jdavis@postgresql.or      164                 :           1015 :     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                 :                :      */
 3499 peter_e@gmx.net           170                 :           1008 :     keys[i] = "dbname";
                                171                 :           1008 :     vals[i] = conninfo;
                                172                 :                : 
                                173                 :                :     /* We can not have logical without replication */
  876 akapila@postgresql.o      174   [ +  +  -  + ]:           1008 :     Assert(replication || !logical);
                                175                 :                : 
                                176         [ +  + ]:           1008 :     if (replication)
                                177                 :                :     {
                                178                 :            993 :         keys[++i] = "replication";
                                179         [ +  + ]:            993 :         vals[i] = logical ? "database" : "true";
                                180                 :                : 
                                181         [ +  + ]:            993 :         if (logical)
                                182                 :                :         {
  175 fujii@postgresql.org      183                 :            747 :             char       *opt = NULL;
                                184                 :                : 
                                185                 :                :             /* Tell the publisher to translate to our encoding */
  876 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                 :                :              */
  175 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);
  876 akapila@postgresql.o      200                 :            747 :             keys[++i] = "options";
  175 fujii@postgresql.org      201                 :            747 :             vals[i] = options_val;
                                202         [ +  + ]:            747 :             if (opt != NULL)
                                203                 :              9 :                 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                 :                :              */
  876 akapila@postgresql.o      211                 :            246 :             keys[++i] = "dbname";
                                212                 :            246 :             vals[i] = "replication";
                                213                 :                :         }
                                214                 :                :     }
                                215                 :                : 
 3499 peter_e@gmx.net           216                 :           1008 :     keys[++i] = "fallback_application_name";
                                217                 :           1008 :     vals[i] = appname;
                                218                 :                : 
                                219                 :           1008 :     keys[++i] = NULL;
                                220                 :           1008 :     vals[i] = NULL;
                                221                 :                : 
  478 heikki.linnakangas@i      222         [ -  + ]:           1008 :     Assert(i < lengthof(keys));
                                223                 :                : 
  202 michael@paquier.xyz       224                 :GNC        1008 :     conn = palloc0_object(WalReceiverConn);
  452 heikki.linnakangas@i      225                 :CBC        1008 :     conn->streamConn =
   38 fujii@postgresql.org      226                 :GNC        1008 :         libpqsrv_connect_params_start(keys, vals,
                                227                 :                :                                        /* expand_dbname = */ true);
                                228                 :           1008 :     PQsetNoticeReceiver(conn->streamConn, libpqsrv_notice_receiver,
                                229                 :                :                         "received message via replication");
                                230                 :           1008 :     libpqsrv_connect_complete(conn->streamConn,
                                231                 :                :                               WAIT_EVENT_LIBPQWALRECEIVER_CONNECT);
                                232                 :                : 
  175 fujii@postgresql.org      233         [ +  + ]:CBC        1005 :     if (options_val != NULL)
                                234                 :            745 :         pfree(options_val);
                                235                 :                : 
 3499 peter_e@gmx.net           236         [ +  + ]:           1005 :     if (PQstatus(conn->streamConn) != CONNECTION_OK)
 1254 andres@anarazel.de        237                 :            123 :         goto bad_connection_errmsg;
                                238                 :                : 
 1188 rhaas@postgresql.org      239   [ +  +  -  + ]:            882 :     if (must_use_password && !PQconnectionUsedPassword(conn->streamConn))
                                240                 :                :     {
  452 heikki.linnakangas@i      241                 :UBC           0 :         libpqsrv_disconnect(conn->streamConn);
 1188 rhaas@postgresql.org      242                 :              0 :         pfree(conn);
                                243                 :                : 
                                244         [ #  # ]:              0 :         ereport(ERROR,
                                245                 :                :                 (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
                                246                 :                :                  errmsg("password is required"),
                                247                 :                :                  errdetail("Non-superuser cannot connect if the server does not request a password."),
                                248                 :                :                  errhint("Target server's authentication method must be changed, or set password_required=false in the subscription parameters.")));
                                249                 :                :     }
                                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                 :                :      */
  852 akapila@postgresql.o      255   [ +  +  +  + ]:CBC         882 :     if (!replication || logical)
                                256                 :                :     {
                                257                 :                :         PGresult   *res;
                                258                 :                : 
  452 heikki.linnakangas@i      259                 :            730 :         res = libpqsrv_exec(conn->streamConn,
                                260                 :                :                             ALWAYS_SECURE_SEARCH_PATH_SQL,
                                261                 :                :                             WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 2150 noah@leadboat.com         262         [ -  + ]:            730 :         if (PQresultStatus(res) != PGRES_TUPLES_OK)
                                263                 :                :         {
 2150 noah@leadboat.com         264                 :UBC           0 :             PQclear(res);
 1254 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                 :                :         }
 2150 noah@leadboat.com         269                 :CBC         730 :         PQclear(res);
                                270                 :                :     }
                                271                 :                : 
 3499 peter_e@gmx.net           272                 :            882 :     conn->logical = logical;
                                273                 :                : 
                                274                 :            882 :     return conn;
                                275                 :                : 
                                276                 :                :     /* error path, using libpq's error message */
 1254 andres@anarazel.de        277                 :            123 : bad_connection_errmsg:
                                278                 :            123 :     *err = pchomp(PQerrorMessage(conn->streamConn));
                                279                 :                : 
                                280                 :                :     /* error path, error already set */
                                281                 :            123 : bad_connection:
  452 heikki.linnakangas@i      282                 :            123 :     libpqsrv_disconnect(conn->streamConn);
 1254 andres@anarazel.de        283                 :            123 :     pfree(conn);
                                284                 :            123 :     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
 1188 rhaas@postgresql.org      296                 :           1253 : libpqrcv_check_conninfo(const char *conninfo, bool must_use_password)
                                297                 :                : {
 3331 bruce@momjian.us          298                 :           1253 :     PQconninfoOption *opts = NULL;
                                299                 :                :     PQconninfoOption *opt;
                                300                 :           1253 :     char       *err = NULL;
                                301                 :                : 
 3449 peter_e@gmx.net           302                 :           1253 :     opts = PQconninfoParse(conninfo, &err);
                                303         [ +  + ]:           1253 :     if (opts == NULL)
                                304                 :                :     {
                                305                 :                :         /* The error string is malloc'd, so we must free it explicitly */
 1930 tgl@sss.pgh.pa.us         306         [ +  - ]:             12 :         char       *errcopy = err ? pstrdup(err) : "out of memory";
                                307                 :                : 
                                308                 :             12 :         PQfreemem(err);
 3449 peter_e@gmx.net           309         [ +  - ]:             12 :         ereport(ERROR,
                                310                 :                :                 (errcode(ERRCODE_SYNTAX_ERROR),
                                311                 :                :                  errmsg("invalid connection string syntax: %s", errcopy)));
                                312                 :                :     }
                                313                 :                : 
 1188 rhaas@postgresql.org      314         [ +  + ]:           1241 :     if (must_use_password)
                                315                 :                :     {
 1138 tgl@sss.pgh.pa.us         316                 :             34 :         bool        uses_password = false;
                                317                 :                : 
 1188 rhaas@postgresql.org      318         [ +  + ]:            675 :         for (opt = opts; opt->keyword != NULL; ++opt)
                                319                 :                :         {
                                320                 :                :             /* Ignore connection options that are not present. */
                                321         [ +  + ]:            664 :             if (opt->val == NULL)
                                322                 :            603 :                 continue;
                                323                 :                : 
                                324   [ +  +  +  - ]:             61 :             if (strcmp(opt->keyword, "password") == 0 && opt->val[0] != '\0')
                                325                 :                :             {
                                326                 :             23 :                 uses_password = true;
                                327                 :             23 :                 break;
                                328                 :                :             }
                                329                 :                :         }
                                330                 :                : 
                                331         [ +  + ]:             34 :         if (!uses_password)
                                332                 :                :         {
                                333                 :                :             /* malloc'd, so we must free it explicitly */
  900 jdavis@postgresql.or      334                 :             11 :             PQconninfoFree(opts);
                                335                 :                : 
 1188 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                 :                : 
 3449 peter_e@gmx.net           343                 :           1230 :     PQconninfoFree(opts);
                                344                 :           1230 : }
                                345                 :                : 
                                346                 :                : /*
                                347                 :                :  * Return a user-displayable conninfo string.  Any security-sensitive fields
                                348                 :                :  * are obfuscated.
                                349                 :                :  */
                                350                 :                : static char *
 3499                           351                 :            152 : libpqrcv_get_conninfo(WalReceiverConn *conn)
                                352                 :                : {
                                353                 :                :     PQconninfoOption *conn_opts;
                                354                 :                :     PQconninfoOption *conn_opt;
                                355                 :                :     PQExpBufferData buf;
                                356                 :                :     char       *retval;
                                357                 :                : 
                                358         [ -  + ]:            152 :     Assert(conn->streamConn != NULL);
                                359                 :                : 
 3653 alvherre@alvh.no-ip.      360                 :            152 :     initPQExpBuffer(&buf);
 3499 peter_e@gmx.net           361                 :            152 :     conn_opts = PQconninfo(conn->streamConn);
                                362                 :                : 
 3653 alvherre@alvh.no-ip.      363         [ -  + ]:            152 :     if (conn_opts == NULL)
 3653 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 */
 3653 alvherre@alvh.no-ip.      370         [ +  + ]:CBC        8056 :     for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
                                371                 :                :     {
                                372                 :                :         bool        obfuscate;
                                373                 :                : 
                                374                 :                :         /* Skip debug and empty options */
                                375         [ +  + ]:           7904 :         if (strchr(conn_opt->dispchar, 'D') ||
                                376         [ +  + ]:           7296 :             conn_opt->val == NULL ||
                                377         [ +  + ]:           2901 :             conn_opt->val[0] == '\0')
                                378                 :           5155 :             continue;
                                379                 :                : 
                                380                 :                :         /* Obfuscate security-sensitive options */
                                381                 :           2749 :         obfuscate = strchr(conn_opt->dispchar, '*') != NULL;
                                382                 :                : 
                                383         [ +  + ]:           5498 :         appendPQExpBuffer(&buf, "%s%s=%s",
                                384         [ +  + ]:           2749 :                           buf.len == 0 ? "" : " ",
                                385                 :                :                           conn_opt->keyword,
                                386                 :                :                           obfuscate ? "********" : conn_opt->val);
                                387                 :                :     }
                                388                 :                : 
                                389                 :            152 :     PQconninfoFree(conn_opts);
                                390                 :                : 
                                391         [ +  - ]:            152 :     retval = PQExpBufferDataBroken(buf) ? NULL : pstrdup(buf.data);
                                392                 :            152 :     termPQExpBuffer(&buf);
                                393                 :            152 :     return retval;
                                394                 :                : }
                                395                 :                : 
                                396                 :                : /*
                                397                 :                :  * Provides information of sender this WAL receiver is connected to.
                                398                 :                :  */
                                399                 :                : static void
 3013 fujii@postgresql.org      400                 :            152 : libpqrcv_get_senderinfo(WalReceiverConn *conn, char **sender_host,
                                401                 :                :                         int *sender_port)
                                402                 :                : {
 2987 tgl@sss.pgh.pa.us         403                 :            152 :     char       *ret = NULL;
                                404                 :                : 
 3013 fujii@postgresql.org      405                 :            152 :     *sender_host = NULL;
                                406                 :            152 :     *sender_port = 0;
                                407                 :                : 
                                408         [ -  + ]:            152 :     Assert(conn->streamConn != NULL);
                                409                 :                : 
                                410                 :            152 :     ret = PQhost(conn->streamConn);
                                411   [ +  -  +  - ]:            152 :     if (ret && strlen(ret) != 0)
                                412                 :            152 :         *sender_host = pstrdup(ret);
                                413                 :                : 
                                414                 :            152 :     ret = PQport(conn->streamConn);
                                415   [ +  -  +  - ]:            152 :     if (ret && strlen(ret) != 0)
                                416                 :            152 :         *sender_port = atoi(ret);
                                417                 :            152 : }
                                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 *
 2664 peter@eisentraut.org      424                 :            401 : 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                 :                :      */
  452 heikki.linnakangas@i      433                 :            401 :     res = libpqsrv_exec(conn->streamConn,
                                434                 :                :                         "IDENTIFY_SYSTEM",
                                435                 :                :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 6005                           436         [ -  + ]:            401 :     if (PQresultStatus(res) != PGRES_TUPLES_OK)
 6005 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                 :                :      */
 4333 fujii@postgresql.org      447   [ +  -  -  + ]:CBC         401 :     if (PQnfields(res) < 3 || PQntuples(res) != 1)
 6005 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)));
 3499 peter_e@gmx.net           453                 :CBC         401 :     primary_sysid = pstrdup(PQgetvalue(res, 0, 0));
 2900 andres@anarazel.de        454                 :            401 :     *primary_tli = pg_strtoint32(PQgetvalue(res, 0, 1));
 6005 heikki.linnakangas@i      455                 :            401 :     PQclear(res);
                                456                 :                : 
 3499 peter_e@gmx.net           457                 :            401 :     return primary_sysid;
                                458                 :                : }
                                459                 :                : 
                                460                 :                : /*
                                461                 :                :  * Thin wrapper around libpq to obtain server version.
                                462                 :                :  */
                                463                 :                : static int
 2664 peter@eisentraut.org      464                 :           1038 : libpqrcv_server_version(WalReceiverConn *conn)
                                465                 :                : {
                                466                 :           1038 :     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 *
  876 akapila@postgresql.o      475                 :             16 : libpqrcv_get_dbname_from_conninfo(const char *connInfo)
                                476                 :                : {
  175 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;
  876 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 */
  876 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                 :                : 
  876 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                 :                :          */
  175 fujii@postgresql.org      511   [ +  +  +  + ]:          39676 :         if (strcmp(opt->keyword, keyword) == 0 && opt->val &&
  876 akapila@postgresql.o      512         [ +  - ]:             24 :             *opt->val)
                                513                 :                :         {
  175 fujii@postgresql.org      514         [ -  + ]:             24 :             if (option)
  175 fujii@postgresql.org      515                 :UBC           0 :                 pfree(option);
                                516                 :                : 
  175 fujii@postgresql.org      517                 :CBC          24 :             option = pstrdup(opt->val);
                                518                 :                :         }
                                519                 :                :     }
                                520                 :                : 
  876 akapila@postgresql.o      521                 :            763 :     PQconninfoFree(opts);
  175 fujii@postgresql.org      522                 :            763 :     return option;
                                523                 :                : }
                                524                 :                : 
                                525                 :                : /*
                                526                 :                :  * Append a suitably-quoted identifier or string literal to buf.
                                527                 :                :  * "quote" should be either a double-quote or single-quote character.
                                528                 :                :  *
                                529                 :                :  * Caution: this quoting logic is sufficient for identifiers and literals
                                530                 :                :  * in the replication grammar, but not always in regular SQL.  Specifically,
                                531                 :                :  * it'd fail for a string literal if standard_conforming_strings is off.
                                532                 :                :  */
                                533                 :                : static void
   15 tgl@sss.pgh.pa.us         534                 :           2806 : appendQuotedString(StringInfo buf, const char *str, char quote)
                                535                 :                : {
                                536                 :           2806 :     appendStringInfoChar(buf, quote);
                                537         [ +  + ]:          42302 :     while (*str)
                                538                 :                :     {
                                539                 :          39496 :         char        c = *str++;
                                540                 :                : 
                                541         [ -  + ]:          39496 :         if (c == quote)
   15 tgl@sss.pgh.pa.us         542                 :UBC           0 :             appendStringInfoChar(buf, c);
   15 tgl@sss.pgh.pa.us         543                 :CBC       39496 :         appendStringInfoChar(buf, c);
                                544                 :                :     }
                                545                 :           2806 :     appendStringInfoChar(buf, quote);
                                546                 :           2806 : }
                                547                 :                : 
                                548                 :                : #define appendQuotedIdentifier(b, s)    appendQuotedString(b, s, '"')
                                549                 :                : #define appendQuotedLiteral(b, s)       appendQuotedString(b, s, '\'')
                                550                 :                : 
                                551                 :                : /*
                                552                 :                :  * Start streaming WAL data from given streaming options.
                                553                 :                :  *
                                554                 :                :  * Returns true if we switched successfully to copy-both mode. False
                                555                 :                :  * means the server received the command and executed it successfully, but
                                556                 :                :  * didn't switch to copy-mode.  That means that there was no WAL on the
                                557                 :                :  * requested timeline and starting point, because the server switched to
                                558                 :                :  * another timeline at or before the requested starting point. On failure,
                                559                 :                :  * throws an ERROR.
                                560                 :                :  */
                                561                 :                : static bool
 3499 peter_e@gmx.net           562                 :            599 : libpqrcv_startstreaming(WalReceiverConn *conn,
                                563                 :                :                         const WalRcvStreamOptions *options)
                                564                 :                : {
                                565                 :                :     StringInfoData cmd;
                                566                 :                :     PGresult   *res;
                                567                 :                : 
 3449                           568         [ -  + ]:            599 :     Assert(options->logical == conn->logical);
                                569   [ +  +  -  + ]:            599 :     Assert(options->slotname || !options->logical);
                                570                 :                : 
 3499                           571                 :            599 :     initStringInfo(&cmd);
                                572                 :                : 
                                573                 :                :     /* Build the command. */
 3449                           574                 :            599 :     appendStringInfoString(&cmd, "START_REPLICATION");
                                575         [ +  + ]:            599 :     if (options->slotname != NULL)
                                576                 :                :     {
   15 tgl@sss.pgh.pa.us         577                 :            485 :         appendStringInfoString(&cmd, " SLOT ");
                                578                 :            485 :         appendQuotedIdentifier(&cmd, options->slotname);
                                579                 :                :     }
                                580                 :                : 
 3449 peter_e@gmx.net           581         [ +  + ]:            599 :     if (options->logical)
 3241                           582                 :            434 :         appendStringInfoString(&cmd, " LOGICAL");
                                583                 :                : 
  358 alvherre@kurilemu.de      584                 :GNC         599 :     appendStringInfo(&cmd, " %X/%08X", LSN_FORMAT_ARGS(options->startpoint));
                                585                 :                : 
                                586                 :                :     /*
                                587                 :                :      * Additional options are different depending on if we are doing logical
                                588                 :                :      * or physical replication.
                                589                 :                :      */
 3449 peter_e@gmx.net           590         [ +  + ]:CBC         599 :     if (options->logical)
                                591                 :                :     {
                                592                 :                :         char       *pubnames_str;
                                593                 :                :         List       *pubnames;
                                594                 :                : 
                                595                 :            434 :         appendStringInfoString(&cmd, " (");
                                596                 :                : 
                                597                 :            434 :         appendStringInfo(&cmd, "proto_version '%u'",
                                598                 :            434 :                          options->proto.logical.proto_version);
                                599                 :                : 
 1268 akapila@postgresql.o      600         [ +  + ]:            434 :         if (options->proto.logical.streaming_str)
                                601                 :                :         {
   15 tgl@sss.pgh.pa.us         602                 :            426 :             appendStringInfoString(&cmd, ", streaming ");
                                603                 :            426 :             appendQuotedLiteral(&cmd, options->proto.logical.streaming_str);
                                604                 :                :         }
                                605                 :                : 
 1812 akapila@postgresql.o      606   [ +  +  +  - ]:            441 :         if (options->proto.logical.twophase &&
                                607                 :              7 :             PQserverVersion(conn->streamConn) >= 150000)
                                608                 :              7 :             appendStringInfoString(&cmd, ", two_phase 'on'");
                                609                 :                : 
 1440                           610   [ +  -  +  - ]:            868 :         if (options->proto.logical.origin &&
                                611                 :            434 :             PQserverVersion(conn->streamConn) >= 160000)
                                612                 :                :         {
   15 tgl@sss.pgh.pa.us         613                 :            434 :             appendStringInfoString(&cmd, ", origin ");
                                614                 :            434 :             appendQuotedLiteral(&cmd, options->proto.logical.origin);
                                615                 :                :         }
                                616                 :                : 
 3449 peter_e@gmx.net           617                 :            434 :         pubnames = options->proto.logical.publication_names;
   15 tgl@sss.pgh.pa.us         618                 :            434 :         pubnames_str = stringlist_to_identifierstr(pubnames);
                                619                 :            434 :         appendStringInfoString(&cmd, ", publication_names ");
                                620                 :            434 :         appendQuotedLiteral(&cmd, pubnames_str);
 3449 peter_e@gmx.net           621                 :            434 :         pfree(pubnames_str);
                                622                 :                : 
 2173 tgl@sss.pgh.pa.us         623   [ +  +  +  - ]:            445 :         if (options->proto.logical.binary &&
                                624                 :             11 :             PQserverVersion(conn->streamConn) >= 140000)
                                625                 :             11 :             appendStringInfoString(&cmd, ", binary 'true'");
                                626                 :                : 
 3445 peter_e@gmx.net           627                 :            434 :         appendStringInfoChar(&cmd, ')');
                                628                 :                :     }
                                629                 :                :     else
 3449                           630                 :            165 :         appendStringInfo(&cmd, " TIMELINE %u",
                                631                 :            165 :                          options->proto.physical.startpointTLI);
                                632                 :                : 
                                633                 :                :     /* Start streaming. */
  452 heikki.linnakangas@i      634                 :            599 :     res = libpqsrv_exec(conn->streamConn,
                                635                 :            599 :                         cmd.data,
                                636                 :                :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 3499 peter_e@gmx.net           637                 :            599 :     pfree(cmd.data);
                                638                 :                : 
 4947 heikki.linnakangas@i      639         [ -  + ]:            599 :     if (PQresultStatus(res) == PGRES_COMMAND_OK)
                                640                 :                :     {
 4947 heikki.linnakangas@i      641                 :UBC           0 :         PQclear(res);
                                642                 :              0 :         return false;
                                643                 :                :     }
 4947 heikki.linnakangas@i      644         [ +  + ]:CBC         599 :     else if (PQresultStatus(res) != PGRES_COPY_BOTH)
 6005                           645         [ +  - ]:              1 :         ereport(ERROR,
                                646                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                647                 :                :                  errmsg("could not start WAL streaming: %s",
                                648                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
                                649                 :            598 :     PQclear(res);
 4947                           650                 :            598 :     return true;
                                651                 :                : }
                                652                 :                : 
                                653                 :                : /*
                                654                 :                :  * Stop streaming WAL data. Returns the next timeline's ID in *next_tli, as
                                655                 :                :  * reported by the server, or 0 if it did not report it.
                                656                 :                :  */
                                657                 :                : static void
 3499 peter_e@gmx.net           658                 :            255 : libpqrcv_endstreaming(WalReceiverConn *conn, TimeLineID *next_tli)
                                659                 :                : {
                                660                 :                :     PGresult   *res;
                                661                 :                : 
                                662                 :                :     /*
                                663                 :                :      * Send copy-end message.  As in libpqsrv_exec, this could theoretically
                                664                 :                :      * block, but the risk seems small.
                                665                 :                :      */
                                666   [ +  +  -  + ]:            466 :     if (PQputCopyEnd(conn->streamConn, NULL) <= 0 ||
                                667                 :            211 :         PQflush(conn->streamConn))
 4947 heikki.linnakangas@i      668         [ +  - ]:             44 :         ereport(ERROR,
                                669                 :                :                 (errcode(ERRCODE_CONNECTION_FAILURE),
                                670                 :                :                  errmsg("could not send end-of-streaming message to primary: %s",
                                671                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
                                672                 :                : 
 3499 peter_e@gmx.net           673                 :            211 :     *next_tli = 0;
                                674                 :                : 
                                675                 :                :     /*
                                676                 :                :      * After COPY is finished, we should receive a result set indicating the
                                677                 :                :      * next timeline's ID, or just CommandComplete if the server was shut
                                678                 :                :      * down.
                                679                 :                :      *
                                680                 :                :      * If we had not yet received CopyDone from the backend, PGRES_COPY_OUT is
                                681                 :                :      * also possible in case we aborted the copy in mid-stream.
                                682                 :                :      */
  452 heikki.linnakangas@i      683                 :            211 :     res = libpqsrv_get_result(conn->streamConn,
                                684                 :                :                               WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 4911                           685         [ +  + ]:            211 :     if (PQresultStatus(res) == PGRES_TUPLES_OK)
                                686                 :                :     {
                                687                 :                :         /*
                                688                 :                :          * Read the next timeline's ID. The server also sends the timeline's
                                689                 :                :          * starting point, but it is ignored.
                                690                 :                :          */
 4801                           691   [ +  -  -  + ]:             13 :         if (PQnfields(res) < 2 || PQntuples(res) != 1)
 4911 heikki.linnakangas@i      692         [ #  # ]:UBC           0 :             ereport(ERROR,
                                693                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                694                 :                :                      errmsg("unexpected result set after end-of-streaming")));
 2900 andres@anarazel.de        695                 :CBC          13 :         *next_tli = pg_strtoint32(PQgetvalue(res, 0, 0));
 4947 heikki.linnakangas@i      696                 :             13 :         PQclear(res);
                                697                 :                : 
                                698                 :                :         /* the result set should be followed by CommandComplete */
  452                           699                 :             13 :         res = libpqsrv_get_result(conn->streamConn,
                                700                 :                :                                   WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
                                701                 :                :     }
 3499 peter_e@gmx.net           702         [ +  - ]:            198 :     else if (PQresultStatus(res) == PGRES_COPY_OUT)
                                703                 :                :     {
                                704                 :            198 :         PQclear(res);
                                705                 :                : 
                                706                 :                :         /* End the copy */
 3287 tgl@sss.pgh.pa.us         707         [ -  + ]:            198 :         if (PQendcopy(conn->streamConn))
 3287 tgl@sss.pgh.pa.us         708         [ #  # ]:UBC           0 :             ereport(ERROR,
                                709                 :                :                     (errcode(ERRCODE_CONNECTION_FAILURE),
                                710                 :                :                      errmsg("error while shutting down streaming COPY: %s",
                                711                 :                :                             pchomp(PQerrorMessage(conn->streamConn)))));
                                712                 :                : 
                                713                 :                :         /* CommandComplete should follow */
  452 heikki.linnakangas@i      714                 :CBC         198 :         res = libpqsrv_get_result(conn->streamConn,
                                715                 :                :                                   WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
                                716                 :                :     }
                                717                 :                : 
 4911                           718         [ -  + ]:            211 :     if (PQresultStatus(res) != PGRES_COMMAND_OK)
 4911 heikki.linnakangas@i      719         [ #  # ]:UBC           0 :         ereport(ERROR,
                                720                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                721                 :                :                  errmsg("error reading result of streaming command: %s",
                                722                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
 4157 tgl@sss.pgh.pa.us         723                 :CBC         211 :     PQclear(res);
                                724                 :                : 
                                725                 :                :     /* Verify that there are no more results */
  452 heikki.linnakangas@i      726                 :            211 :     res = libpqsrv_get_result(conn->streamConn,
                                727                 :                :                               WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 4911                           728         [ -  + ]:            211 :     if (res != NULL)
 4911 heikki.linnakangas@i      729         [ #  # ]:UBC           0 :         ereport(ERROR,
                                730                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                731                 :                :                  errmsg("unexpected result after CommandComplete: %s",
                                732                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
 4947 heikki.linnakangas@i      733                 :CBC         211 : }
                                734                 :                : 
                                735                 :                : /*
                                736                 :                :  * Fetch the timeline history file for 'tli' from primary.
                                737                 :                :  */
                                738                 :                : static void
 3499 peter_e@gmx.net           739                 :             12 : libpqrcv_readtimelinehistoryfile(WalReceiverConn *conn,
                                740                 :                :                                  TimeLineID tli, char **filename,
                                741                 :                :                                  char **content, int *len)
                                742                 :                : {
                                743                 :                :     PGresult   *res;
                                744                 :                :     char        cmd[64];
                                745                 :                : 
                                746         [ -  + ]:             12 :     Assert(!conn->logical);
                                747                 :                : 
                                748                 :                :     /*
                                749                 :                :      * Request the primary to send over the history file for given timeline.
                                750                 :                :      */
 4947 heikki.linnakangas@i      751                 :             12 :     snprintf(cmd, sizeof(cmd), "TIMELINE_HISTORY %u", tli);
  452                           752                 :             12 :     res = libpqsrv_exec(conn->streamConn,
                                753                 :                :                         cmd,
                                754                 :                :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 4947                           755         [ -  + ]:             12 :     if (PQresultStatus(res) != PGRES_TUPLES_OK)
 4947 heikki.linnakangas@i      756         [ #  # ]:UBC           0 :         ereport(ERROR,
                                757                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                758                 :                :                  errmsg("could not receive timeline history file from "
                                759                 :                :                         "the primary server: %s",
                                760                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
 4947 heikki.linnakangas@i      761   [ +  -  -  + ]:CBC          12 :     if (PQnfields(res) != 2 || PQntuples(res) != 1)
 4947 heikki.linnakangas@i      762         [ #  # ]:UBC           0 :         ereport(ERROR,
                                763                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                764                 :                :                  errmsg("invalid response from primary server"),
                                765                 :                :                  errdetail("Expected 1 tuple with 2 fields, got %d tuples with %d fields.",
                                766                 :                :                            PQntuples(res), PQnfields(res))));
 4947 heikki.linnakangas@i      767                 :CBC          12 :     *filename = pstrdup(PQgetvalue(res, 0, 0));
                                768                 :                : 
                                769                 :             12 :     *len = PQgetlength(res, 0, 1);
                                770                 :             12 :     *content = palloc(*len);
                                771                 :             12 :     memcpy(*content, PQgetvalue(res, 0, 1), *len);
                                772                 :             12 :     PQclear(res);
 6005                           773                 :             12 : }
                                774                 :                : 
                                775                 :                : /*
                                776                 :                :  * Disconnect connection to primary, if any.
                                777                 :                :  */
                                778                 :                : static void
 3499 peter_e@gmx.net           779                 :            882 : libpqrcv_disconnect(WalReceiverConn *conn)
                                780                 :                : {
  452 heikki.linnakangas@i      781                 :            882 :     libpqsrv_disconnect(conn->streamConn);
 1404 peter@eisentraut.org      782                 :            882 :     PQfreemem(conn->recvBuf);
 3499 peter_e@gmx.net           783                 :            882 :     pfree(conn);
 6005 heikki.linnakangas@i      784                 :            882 : }
                                785                 :                : 
                                786                 :                : /*
                                787                 :                :  * Receive a message available from XLOG stream.
                                788                 :                :  *
                                789                 :                :  * Returns:
                                790                 :                :  *
                                791                 :                :  *   If data was received, returns the length of the data. *buffer is set to
                                792                 :                :  *   point to a buffer holding the received message. The buffer is only valid
                                793                 :                :  *   until the next libpqrcv_* call.
                                794                 :                :  *
                                795                 :                :  *   If no data was available immediately, returns 0, and *wait_fd is set to a
                                796                 :                :  *   socket descriptor which can be waited on before trying again.
                                797                 :                :  *
                                798                 :                :  *   -1 if the server ended the COPY.
                                799                 :                :  *
                                800                 :                :  * ereports on error.
                                801                 :                :  */
                                802                 :                : static int
 3499 peter_e@gmx.net           803                 :         446145 : libpqrcv_receive(WalReceiverConn *conn, char **buffer,
                                804                 :                :                  pgsocket *wait_fd)
                                805                 :                : {
                                806                 :                :     int         rawlen;
                                807                 :                : 
 1404 peter@eisentraut.org      808                 :         446145 :     PQfreemem(conn->recvBuf);
 3499 peter_e@gmx.net           809                 :         446145 :     conn->recvBuf = NULL;
                                810                 :                : 
                                811                 :                :     /* Try to receive a CopyData message */
                                812                 :         446145 :     rawlen = PQgetCopyData(conn->streamConn, &conn->recvBuf, 1);
 5647 heikki.linnakangas@i      813         [ +  + ]:         446145 :     if (rawlen == 0)
                                814                 :                :     {
                                815                 :                :         /* Try consuming some data. */
 3499 peter_e@gmx.net           816         [ +  + ]:         250317 :         if (PQconsumeInput(conn->streamConn) == 0)
 6005 heikki.linnakangas@i      817         [ +  - ]:             38 :             ereport(ERROR,
                                818                 :                :                     (errcode(ERRCODE_CONNECTION_FAILURE),
                                819                 :                :                      errmsg("could not receive data from WAL stream: %s",
                                820                 :                :                             pchomp(PQerrorMessage(conn->streamConn)))));
                                821                 :                : 
                                822                 :                :         /* Now that we've consumed some input, try again */
 3499 peter_e@gmx.net           823                 :         250279 :         rawlen = PQgetCopyData(conn->streamConn, &conn->recvBuf, 1);
 5647 heikki.linnakangas@i      824         [ +  + ]:         250279 :         if (rawlen == 0)
                                825                 :                :         {
                                826                 :                :             /* Tell caller to try again when our socket is ready. */
 3499 peter_e@gmx.net           827                 :         109210 :             *wait_fd = PQsocket(conn->streamConn);
 4947 heikki.linnakangas@i      828                 :         109210 :             return 0;
                                829                 :                :         }
                                830                 :                :     }
 5968 bruce@momjian.us          831         [ +  + ]:         336897 :     if (rawlen == -1)           /* end-of-streaming or error */
                                832                 :                :     {
                                833                 :                :         PGresult   *res;
                                834                 :                : 
  452 heikki.linnakangas@i      835                 :            267 :         res = libpqsrv_get_result(conn->streamConn,
                                836                 :                :                                   WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 3386 peter_e@gmx.net           837         [ +  + ]:            267 :         if (PQresultStatus(res) == PGRES_COMMAND_OK)
                                838                 :                :         {
                                839                 :            251 :             PQclear(res);
                                840                 :                : 
                                841                 :                :             /* Verify that there are no more results. */
  452 heikki.linnakangas@i      842                 :            251 :             res = libpqsrv_get_result(conn->streamConn,
                                843                 :                :                                       WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 3386 peter_e@gmx.net           844         [ +  + ]:            251 :             if (res != NULL)
                                845                 :                :             {
 3309 andres@anarazel.de        846                 :             45 :                 PQclear(res);
                                847                 :                : 
                                848                 :                :                 /*
                                849                 :                :                  * If the other side closed the connection orderly (otherwise
                                850                 :                :                  * we'd seen an error, or PGRES_COPY_IN) don't report an error
                                851                 :                :                  * here, but let callers deal with it.
                                852                 :                :                  */
                                853         [ +  - ]:             45 :                 if (PQstatus(conn->streamConn) == CONNECTION_BAD)
                                854                 :             45 :                     return -1;
                                855                 :                : 
 3386 peter_e@gmx.net           856         [ #  # ]:UBC           0 :                 ereport(ERROR,
                                857                 :                :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                858                 :                :                          errmsg("unexpected result after CommandComplete: %s",
                                859                 :                :                                 PQerrorMessage(conn->streamConn))));
                                860                 :                :             }
                                861                 :                : 
 3386 peter_e@gmx.net           862                 :CBC         206 :             return -1;
                                863                 :                :         }
                                864         [ +  + ]:             16 :         else if (PQresultStatus(res) == PGRES_COPY_IN)
                                865                 :                :         {
 4947 heikki.linnakangas@i      866                 :             13 :             PQclear(res);
                                867                 :             13 :             return -1;
                                868                 :                :         }
                                869                 :                :         else
 6005                           870         [ +  - ]:              3 :             ereport(ERROR,
                                871                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                872                 :                :                      errmsg("could not receive data from WAL stream: %s",
                                873                 :                :                             pchomp(PQerrorMessage(conn->streamConn)))));
                                874                 :                :     }
                                875         [ -  + ]:         336630 :     if (rawlen < -1)
 6005 heikki.linnakangas@i      876         [ #  # ]:UBC           0 :         ereport(ERROR,
                                877                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                878                 :                :                  errmsg("could not receive data from WAL stream: %s",
                                879                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
                                880                 :                : 
                                881                 :                :     /* Return received messages to caller */
 3499 peter_e@gmx.net           882                 :CBC      336630 :     *buffer = conn->recvBuf;
 4947 heikki.linnakangas@i      883                 :         336630 :     return rawlen;
                                884                 :                : }
                                885                 :                : 
                                886                 :                : /*
                                887                 :                :  * Send a message to XLOG stream.
                                888                 :                :  *
                                889                 :                :  * ereports on error.
                                890                 :                :  */
                                891                 :                : static void
 3499 peter_e@gmx.net           892                 :         148603 : libpqrcv_send(WalReceiverConn *conn, const char *buffer, int nbytes)
                                893                 :                : {
                                894   [ +  +  +  + ]:         297205 :     if (PQputCopyData(conn->streamConn, buffer, nbytes) <= 0 ||
                                895                 :         148602 :         PQflush(conn->streamConn))
 5680 rhaas@postgresql.org      896         [ +  - ]:GBC           2 :         ereport(ERROR,
                                897                 :                :                 (errcode(ERRCODE_CONNECTION_FAILURE),
                                898                 :                :                  errmsg("could not send data to WAL stream: %s",
                                899                 :                :                         pchomp(PQerrorMessage(conn->streamConn)))));
 5680 rhaas@postgresql.org      900                 :CBC      148601 : }
                                901                 :                : 
                                902                 :                : /*
                                903                 :                :  * Create new replication slot.
                                904                 :                :  * Returns the name of the exported snapshot for logical slot or NULL for
                                905                 :                :  * physical slot.
                                906                 :                :  */
                                907                 :                : static char *
 3449 peter_e@gmx.net           908                 :            330 : libpqrcv_create_slot(WalReceiverConn *conn, const char *slotname,
                                909                 :                :                      bool temporary, bool two_phase, bool failover,
                                910                 :                :                      CRSSnapshotAction snapshot_action, XLogRecPtr *lsn)
                                911                 :                : {
                                912                 :                :     PGresult   *res;
                                913                 :                :     StringInfoData cmd;
                                914                 :                :     char       *snapshot;
                                915                 :                :     int         use_new_options_syntax;
                                916                 :                : 
 1729 rhaas@postgresql.org      917                 :            330 :     use_new_options_syntax = (PQserverVersion(conn->streamConn) >= 150000);
                                918                 :                : 
 3449 peter_e@gmx.net           919                 :            330 :     initStringInfo(&cmd);
                                920                 :                : 
   15 tgl@sss.pgh.pa.us         921                 :            330 :     appendStringInfoString(&cmd, "CREATE_REPLICATION_SLOT ");
                                922                 :            330 :     appendQuotedIdentifier(&cmd, slotname);
                                923                 :                : 
 3449 peter_e@gmx.net           924         [ -  + ]:            330 :     if (temporary)
 3241 peter_e@gmx.net           925                 :UBC           0 :         appendStringInfoString(&cmd, " TEMPORARY");
                                926                 :                : 
 3449 peter_e@gmx.net           927         [ +  - ]:CBC         330 :     if (conn->logical)
                                928                 :                :     {
 1729 rhaas@postgresql.org      929                 :            330 :         appendStringInfoString(&cmd, " LOGICAL pgoutput ");
                                930         [ +  - ]:            330 :         if (use_new_options_syntax)
                                931                 :            330 :             appendStringInfoChar(&cmd, '(');
 1812 akapila@postgresql.o      932         [ +  + ]:            330 :         if (two_phase)
                                933                 :                :         {
 1729 rhaas@postgresql.org      934                 :              1 :             appendStringInfoString(&cmd, "TWO_PHASE");
                                935         [ +  - ]:              1 :             if (use_new_options_syntax)
                                936                 :              1 :                 appendStringInfoString(&cmd, ", ");
                                937                 :                :             else
 1729 rhaas@postgresql.org      938                 :UBC           0 :                 appendStringInfoChar(&cmd, ' ');
                                939                 :                :         }
                                940                 :                : 
  883 akapila@postgresql.o      941         [ +  + ]:CBC         330 :         if (failover)
                                942                 :                :         {
                                943                 :             11 :             appendStringInfoString(&cmd, "FAILOVER");
                                944         [ +  - ]:             11 :             if (use_new_options_syntax)
                                945                 :             11 :                 appendStringInfoString(&cmd, ", ");
                                946                 :                :             else
  883 akapila@postgresql.o      947                 :UBC           0 :                 appendStringInfoChar(&cmd, ' ');
                                948                 :                :         }
                                949                 :                : 
 1729 rhaas@postgresql.org      950         [ +  - ]:CBC         330 :         if (use_new_options_syntax)
                                951                 :                :         {
                                952   [ -  +  +  - ]:            330 :             switch (snapshot_action)
                                953                 :                :             {
 1729 rhaas@postgresql.org      954                 :UBC           0 :                 case CRS_EXPORT_SNAPSHOT:
                                955                 :              0 :                     appendStringInfoString(&cmd, "SNAPSHOT 'export'");
                                956                 :              0 :                     break;
 1729 rhaas@postgresql.org      957                 :CBC         120 :                 case CRS_NOEXPORT_SNAPSHOT:
                                958                 :            120 :                     appendStringInfoString(&cmd, "SNAPSHOT 'nothing'");
                                959                 :            120 :                     break;
                                960                 :            210 :                 case CRS_USE_SNAPSHOT:
                                961                 :            210 :                     appendStringInfoString(&cmd, "SNAPSHOT 'use'");
                                962                 :            210 :                     break;
                                963                 :                :             }
                                964                 :                :         }
                                965                 :                :         else
                                966                 :                :         {
 1729 rhaas@postgresql.org      967   [ #  #  #  # ]:UBC           0 :             switch (snapshot_action)
                                968                 :                :             {
                                969                 :              0 :                 case CRS_EXPORT_SNAPSHOT:
                                970                 :              0 :                     appendStringInfoString(&cmd, "EXPORT_SNAPSHOT");
                                971                 :              0 :                     break;
                                972                 :              0 :                 case CRS_NOEXPORT_SNAPSHOT:
                                973                 :              0 :                     appendStringInfoString(&cmd, "NOEXPORT_SNAPSHOT");
                                974                 :              0 :                     break;
                                975                 :              0 :                 case CRS_USE_SNAPSHOT:
                                976                 :              0 :                     appendStringInfoString(&cmd, "USE_SNAPSHOT");
                                977                 :              0 :                     break;
                                978                 :                :             }
                                979                 :                :         }
                                980                 :                : 
 1729 rhaas@postgresql.org      981         [ +  - ]:CBC         330 :         if (use_new_options_syntax)
                                982                 :            330 :             appendStringInfoChar(&cmd, ')');
                                983                 :                :     }
                                984                 :                :     else
                                985                 :                :     {
 1729 rhaas@postgresql.org      986         [ #  # ]:UBC           0 :         if (use_new_options_syntax)
                                987                 :              0 :             appendStringInfoString(&cmd, " PHYSICAL (RESERVE_WAL)");
                                988                 :                :         else
                                989                 :              0 :             appendStringInfoString(&cmd, " PHYSICAL RESERVE_WAL");
                                990                 :                :     }
                                991                 :                : 
  452 heikki.linnakangas@i      992                 :CBC         330 :     res = libpqsrv_exec(conn->streamConn,
                                993                 :            330 :                         cmd.data,
                                994                 :                :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
 3449 peter_e@gmx.net           995                 :            330 :     pfree(cmd.data);
                                996                 :                : 
                                997         [ -  + ]:            330 :     if (PQresultStatus(res) != PGRES_TUPLES_OK)
 3449 peter_e@gmx.net           998         [ #  # ]:UBC           0 :         ereport(ERROR,
                                999                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1000                 :                :                  errmsg("could not create replication slot \"%s\": %s",
                               1001                 :                :                         slotname, pchomp(PQerrorMessage(conn->streamConn)))));
                               1002                 :                : 
 2362 peter@eisentraut.org     1003         [ +  + ]:CBC         330 :     if (lsn)
                               1004                 :            210 :         *lsn = DatumGetLSN(DirectFunctionCall1Coll(pg_lsn_in, InvalidOid,
                               1005                 :            210 :                                                    CStringGetDatum(PQgetvalue(res, 0, 1))));
                               1006                 :                : 
 3449 peter_e@gmx.net          1007         [ -  + ]:            330 :     if (!PQgetisnull(res, 0, 2))
 3449 peter_e@gmx.net          1008                 :UBC           0 :         snapshot = pstrdup(PQgetvalue(res, 0, 2));
                               1009                 :                :     else
 3449 peter_e@gmx.net          1010                 :CBC         330 :         snapshot = NULL;
                               1011                 :                : 
                               1012                 :            330 :     PQclear(res);
                               1013                 :                : 
                               1014                 :            330 :     return snapshot;
                               1015                 :                : }
                               1016                 :                : 
                               1017                 :                : /*
                               1018                 :                :  * Change the definition of the replication slot.
                               1019                 :                :  */
                               1020                 :                : static void
  883 akapila@postgresql.o     1021                 :              5 : libpqrcv_alter_slot(WalReceiverConn *conn, const char *slotname,
                               1022                 :                :                     const bool *failover, const bool *two_phase)
                               1023                 :                : {
                               1024                 :                :     StringInfoData cmd;
                               1025                 :                :     PGresult   *res;
                               1026                 :                : 
                               1027                 :              5 :     initStringInfo(&cmd);
   15 tgl@sss.pgh.pa.us        1028                 :              5 :     appendStringInfoString(&cmd, "ALTER_REPLICATION_SLOT ");
                               1029                 :              5 :     appendQuotedIdentifier(&cmd, slotname);
                               1030                 :              5 :     appendStringInfoString(&cmd, " ( ");
                               1031                 :                : 
  706 akapila@postgresql.o     1032         [ +  + ]:              5 :     if (failover)
                               1033                 :              4 :         appendStringInfo(&cmd, "FAILOVER %s",
                               1034         [ +  + ]:              4 :                          *failover ? "true" : "false");
                               1035                 :                : 
                               1036   [ +  +  -  + ]:              5 :     if (failover && two_phase)
  445 drowley@postgresql.o     1037                 :UBC           0 :         appendStringInfoString(&cmd, ", ");
                               1038                 :                : 
  706 akapila@postgresql.o     1039         [ +  + ]:CBC           5 :     if (two_phase)
                               1040                 :              1 :         appendStringInfo(&cmd, "TWO_PHASE %s",
                               1041         [ -  + ]:              1 :                          *two_phase ? "true" : "false");
                               1042                 :                : 
                               1043                 :              5 :     appendStringInfoString(&cmd, " );");
                               1044                 :                : 
  452 heikki.linnakangas@i     1045                 :              5 :     res = libpqsrv_exec(conn->streamConn, cmd.data,
                               1046                 :                :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
  883 akapila@postgresql.o     1047                 :              5 :     pfree(cmd.data);
                               1048                 :                : 
                               1049         [ -  + ]:              5 :     if (PQresultStatus(res) != PGRES_COMMAND_OK)
  883 akapila@postgresql.o     1050         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1051                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1052                 :                :                  errmsg("could not alter replication slot \"%s\": %s",
                               1053                 :                :                         slotname, pchomp(PQerrorMessage(conn->streamConn)))));
                               1054                 :                : 
  883 akapila@postgresql.o     1055                 :CBC           5 :     PQclear(res);
                               1056                 :              5 : }
                               1057                 :                : 
                               1058                 :                : /*
                               1059                 :                :  * Return PID of remote backend process.
                               1060                 :                :  */
                               1061                 :                : static pid_t
 2359 peter@eisentraut.org     1062                 :UBC           0 : libpqrcv_get_backend_pid(WalReceiverConn *conn)
                               1063                 :                : {
                               1064                 :              0 :     return PQbackendPID(conn->streamConn);
                               1065                 :                : }
                               1066                 :                : 
                               1067                 :                : /*
                               1068                 :                :  * Convert tuple query result to tuplestore.
                               1069                 :                :  */
                               1070                 :                : static void
 3386 peter_e@gmx.net          1071                 :CBC        1230 : libpqrcv_processTuples(PGresult *pgres, WalRcvExecResult *walres,
                               1072                 :                :                        const int nRetTypes, const Oid *retTypes)
                               1073                 :                : {
                               1074                 :                :     int         tupn;
                               1075                 :                :     int         coln;
 3331 bruce@momjian.us         1076                 :           1230 :     int         nfields = PQnfields(pgres);
                               1077                 :                :     HeapTuple   tuple;
                               1078                 :                :     AttInMetadata *attinmeta;
                               1079                 :                :     MemoryContext rowcontext;
                               1080                 :                :     MemoryContext oldcontext;
                               1081                 :                : 
                               1082                 :                :     /* Make sure we got expected number of fields. */
 3386 peter_e@gmx.net          1083         [ -  + ]:           1230 :     if (nfields != nRetTypes)
 3386 peter_e@gmx.net          1084         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1085                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1086                 :                :                  errmsg("invalid query response"),
                               1087                 :                :                  errdetail("Expected %d fields, got %d fields.",
                               1088                 :                :                            nRetTypes, nfields)));
                               1089                 :                : 
 3386 peter_e@gmx.net          1090                 :CBC        1230 :     walres->tuplestore = tuplestore_begin_heap(true, false, work_mem);
                               1091                 :                : 
                               1092                 :                :     /* Create tuple descriptor corresponding to expected result. */
 2779 andres@anarazel.de       1093                 :           1230 :     walres->tupledesc = CreateTemplateTupleDesc(nRetTypes);
 3386 peter_e@gmx.net          1094         [ +  + ]:           4598 :     for (coln = 0; coln < nRetTypes; coln++)
                               1095                 :           3368 :         TupleDescInitEntry(walres->tupledesc, (AttrNumber) coln + 1,
                               1096                 :           3368 :                            PQfname(pgres, coln), retTypes[coln], -1, 0);
  106 drowley@postgresql.o     1097                 :GNC        1230 :     TupleDescFinalize(walres->tupledesc);
 3386 peter_e@gmx.net          1098                 :CBC        1230 :     attinmeta = TupleDescGetAttInMetadata(walres->tupledesc);
                               1099                 :                : 
                               1100                 :                :     /* No point in doing more here if there were no tuples returned. */
 3385                          1101         [ +  + ]:           1230 :     if (PQntuples(pgres) == 0)
                               1102                 :             34 :         return;
                               1103                 :                : 
                               1104                 :                :     /* Create temporary context for local allocations. */
 3386                          1105                 :           1196 :     rowcontext = AllocSetContextCreate(CurrentMemoryContext,
                               1106                 :                :                                        "libpqrcv query result context",
                               1107                 :                :                                        ALLOCSET_DEFAULT_SIZES);
                               1108                 :                : 
                               1109                 :                :     /* Process returned rows. */
                               1110         [ +  + ]:           2778 :     for (tupn = 0; tupn < PQntuples(pgres); tupn++)
                               1111                 :                :     {
                               1112                 :                :         char       *cstrs[MaxTupleAttributeNumber];
                               1113                 :                : 
  452 heikki.linnakangas@i     1114         [ -  + ]:           1582 :         CHECK_FOR_INTERRUPTS();
                               1115                 :                : 
                               1116                 :                :         /* Do the allocations in temporary context. */
 3386 peter_e@gmx.net          1117                 :           1582 :         oldcontext = MemoryContextSwitchTo(rowcontext);
                               1118                 :                : 
                               1119                 :                :         /*
                               1120                 :                :          * Fill cstrs with null-terminated strings of column values.
                               1121                 :                :          */
                               1122         [ +  + ]:           6655 :         for (coln = 0; coln < nfields; coln++)
                               1123                 :                :         {
                               1124         [ +  + ]:           5073 :             if (PQgetisnull(pgres, tupn, coln))
                               1125                 :            664 :                 cstrs[coln] = NULL;
                               1126                 :                :             else
                               1127                 :           4409 :                 cstrs[coln] = PQgetvalue(pgres, tupn, coln);
                               1128                 :                :         }
                               1129                 :                : 
                               1130                 :                :         /* Convert row to a tuple, and add it to the tuplestore */
                               1131                 :           1582 :         tuple = BuildTupleFromCStrings(attinmeta, cstrs);
                               1132                 :           1582 :         tuplestore_puttuple(walres->tuplestore, tuple);
                               1133                 :                : 
                               1134                 :                :         /* Clean up */
                               1135                 :           1582 :         MemoryContextSwitchTo(oldcontext);
                               1136                 :           1582 :         MemoryContextReset(rowcontext);
                               1137                 :                :     }
                               1138                 :                : 
                               1139                 :           1196 :     MemoryContextDelete(rowcontext);
                               1140                 :                : }
                               1141                 :                : 
                               1142                 :                : /*
                               1143                 :                :  * Public interface for sending generic queries (and commands).
                               1144                 :                :  *
                               1145                 :                :  * This can only be called from process connected to database.
                               1146                 :                :  */
                               1147                 :                : static WalRcvExecResult *
                               1148                 :           2136 : libpqrcv_exec(WalReceiverConn *conn, const char *query,
                               1149                 :                :               const int nRetTypes, const Oid *retTypes)
                               1150                 :                : {
                               1151                 :           2136 :     PGresult   *pgres = NULL;
  202 michael@paquier.xyz      1152                 :GNC        2136 :     WalRcvExecResult *walres = palloc0_object(WalRcvExecResult);
                               1153                 :                :     char       *diag_sqlstate;
                               1154                 :                : 
 3386 peter_e@gmx.net          1155         [ -  + ]:CBC        2136 :     if (MyDatabaseId == InvalidOid)
 3386 peter_e@gmx.net          1156         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1157                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               1158                 :                :                  errmsg("the query interface requires a database connection")));
                               1159                 :                : 
  452 heikki.linnakangas@i     1160                 :CBC        2136 :     pgres = libpqsrv_exec(conn->streamConn,
                               1161                 :                :                           query,
                               1162                 :                :                           WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
                               1163                 :                : 
 3386 peter_e@gmx.net          1164   [ +  -  +  -  :           2136 :     switch (PQresultStatus(pgres))
                                        +  -  -  +  
                                                 - ]
                               1165                 :                :     {
                               1166                 :           1230 :         case PGRES_TUPLES_OK:
                               1167                 :                :         case PGRES_SINGLE_TUPLE:
                               1168                 :                :         case PGRES_TUPLES_CHUNK:
                               1169                 :           1230 :             walres->status = WALRCV_OK_TUPLES;
                               1170                 :           1230 :             libpqrcv_processTuples(pgres, walres, nRetTypes, retTypes);
                               1171                 :           1230 :             break;
                               1172                 :                : 
 3386 peter_e@gmx.net          1173                 :UBC           0 :         case PGRES_COPY_IN:
                               1174                 :              0 :             walres->status = WALRCV_OK_COPY_IN;
                               1175                 :              0 :             break;
                               1176                 :                : 
 3386 peter_e@gmx.net          1177                 :CBC         208 :         case PGRES_COPY_OUT:
                               1178                 :            208 :             walres->status = WALRCV_OK_COPY_OUT;
                               1179                 :            208 :             break;
                               1180                 :                : 
 3386 peter_e@gmx.net          1181                 :UBC           0 :         case PGRES_COPY_BOTH:
                               1182                 :              0 :             walres->status = WALRCV_OK_COPY_BOTH;
                               1183                 :              0 :             break;
                               1184                 :                : 
 3386 peter_e@gmx.net          1185                 :CBC         693 :         case PGRES_COMMAND_OK:
                               1186                 :            693 :             walres->status = WALRCV_OK_COMMAND;
                               1187                 :            693 :             break;
                               1188                 :                : 
                               1189                 :                :             /* Empty query is considered error. */
 3386 peter_e@gmx.net          1190                 :UBC           0 :         case PGRES_EMPTY_QUERY:
                               1191                 :              0 :             walres->status = WALRCV_ERROR;
                               1192                 :              0 :             walres->err = _("empty query");
                               1193                 :              0 :             break;
                               1194                 :                : 
 1933 alvherre@alvh.no-ip.     1195                 :              0 :         case PGRES_PIPELINE_SYNC:
                               1196                 :                :         case PGRES_PIPELINE_ABORTED:
                               1197                 :              0 :             walres->status = WALRCV_ERROR;
                               1198                 :              0 :             walres->err = _("unexpected pipeline mode");
                               1199                 :              0 :             break;
                               1200                 :                : 
 3386 peter_e@gmx.net          1201                 :CBC           5 :         case PGRES_NONFATAL_ERROR:
                               1202                 :                :         case PGRES_FATAL_ERROR:
                               1203                 :                :         case PGRES_BAD_RESPONSE:
                               1204                 :              5 :             walres->status = WALRCV_ERROR;
                               1205                 :              5 :             walres->err = pchomp(PQerrorMessage(conn->streamConn));
 1964 akapila@postgresql.o     1206                 :              5 :             diag_sqlstate = PQresultErrorField(pgres, PG_DIAG_SQLSTATE);
                               1207         [ +  + ]:              5 :             if (diag_sqlstate)
                               1208                 :              3 :                 walres->sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
                               1209                 :                :                                                  diag_sqlstate[1],
                               1210                 :                :                                                  diag_sqlstate[2],
                               1211                 :                :                                                  diag_sqlstate[3],
                               1212                 :                :                                                  diag_sqlstate[4]);
 3386 peter_e@gmx.net          1213                 :              5 :             break;
                               1214                 :                :     }
                               1215                 :                : 
                               1216                 :           2136 :     PQclear(pgres);
                               1217                 :                : 
                               1218                 :           2136 :     return walres;
                               1219                 :                : }
                               1220                 :                : 
                               1221                 :                : /*
                               1222                 :                :  * Given a List of strings, return it as single comma separated
                               1223                 :                :  * string, quoting identifiers as needed.
                               1224                 :                :  *
                               1225                 :                :  * This is essentially the reverse of SplitIdentifierString.
                               1226                 :                :  *
                               1227                 :                :  * The caller should pfree the result.
                               1228                 :                :  */
                               1229                 :                : static char *
   15 tgl@sss.pgh.pa.us        1230                 :            434 : stringlist_to_identifierstr(List *strings)
                               1231                 :                : {
                               1232                 :                :     ListCell   *lc;
                               1233                 :                :     StringInfoData res;
 3331 bruce@momjian.us         1234                 :            434 :     bool        first = true;
                               1235                 :                : 
 3449 peter_e@gmx.net          1236                 :            434 :     initStringInfo(&res);
                               1237                 :                : 
 3331 bruce@momjian.us         1238   [ +  -  +  +  :           1126 :     foreach(lc, strings)
                                              +  + ]
                               1239                 :                :     {
                               1240                 :            692 :         char       *val = strVal(lfirst(lc));
                               1241                 :                : 
 3449 peter_e@gmx.net          1242         [ +  + ]:            692 :         if (first)
                               1243                 :            434 :             first = false;
                               1244                 :                :         else
                               1245                 :            258 :             appendStringInfoChar(&res, ',');
   15 tgl@sss.pgh.pa.us        1246                 :            692 :         appendQuotedIdentifier(&res, val);
                               1247                 :                :     }
                               1248                 :                : 
 3449 peter_e@gmx.net          1249                 :            434 :     return res.data;
                               1250                 :                : }
        

Generated by: LCOV version 2.0-1