LCOV - code coverage report
Current view: top level - src/backend/replication/libpqwalreceiver - libpqwalreceiver.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 84.3 % 427 360
Test Date: 2026-07-03 19:57:34 Functions: 95.7 % 23 22
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 62.8 % 293 184

             Branch data     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                 :             : 
      40                 :        1117 : 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
     125                 :        1117 : _PG_init(void)
     126                 :             : {
     127         [ -  + ]:        1117 :     if (WalReceiverFunctions != NULL)
     128         [ #  # ]:           0 :         elog(ERROR, "libpqwalreceiver already loaded");
     129                 :        1117 :     WalReceiverFunctions = &PQWalReceiverFunctions;
     130                 :        1117 : }
     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 *
     148                 :        1039 : 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];
     154                 :        1039 :     int         i = 0;
     155                 :        1039 :     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                 :             :      */
     164                 :        1039 :     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                 :             :      */
     170                 :        1029 :     keys[i] = "dbname";
     171                 :        1029 :     vals[i] = conninfo;
     172                 :             : 
     173                 :             :     /* We can not have logical without replication */
     174                 :             :     Assert(replication || !logical);
     175                 :             : 
     176         [ +  + ]:        1029 :     if (replication)
     177                 :             :     {
     178                 :        1014 :         keys[++i] = "replication";
     179         [ +  + ]:        1014 :         vals[i] = logical ? "database" : "true";
     180                 :             : 
     181         [ +  + ]:        1014 :         if (logical)
     182                 :             :         {
     183                 :         753 :             char       *opt = NULL;
     184                 :             : 
     185                 :             :             /* Tell the publisher to translate to our encoding */
     186                 :         753 :             keys[++i] = "client_encoding";
     187                 :         753 :             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                 :             :              */
     197                 :         753 :             opt = libpqrcv_get_option_from_conninfo(conninfo, "options");
     198         [ +  + ]:         753 :             options_val = psprintf("%s -c datestyle=ISO -c intervalstyle=postgres -c extra_float_digits=3",
     199                 :             :                                    (opt == NULL) ? "" : opt);
     200                 :         753 :             keys[++i] = "options";
     201                 :         753 :             vals[i] = options_val;
     202         [ +  + ]:         753 :             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                 :             :              */
     211                 :         261 :             keys[++i] = "dbname";
     212                 :         261 :             vals[i] = "replication";
     213                 :             :         }
     214                 :             :     }
     215                 :             : 
     216                 :        1029 :     keys[++i] = "fallback_application_name";
     217                 :        1029 :     vals[i] = appname;
     218                 :             : 
     219                 :        1029 :     keys[++i] = NULL;
     220                 :        1029 :     vals[i] = NULL;
     221                 :             : 
     222                 :             :     Assert(i < lengthof(keys));
     223                 :             : 
     224                 :        1029 :     conn = palloc0_object(WalReceiverConn);
     225                 :        1029 :     conn->streamConn =
     226                 :        1029 :         libpqsrv_connect_params_start(keys, vals,
     227                 :             :                                        /* expand_dbname = */ true);
     228                 :        1029 :     PQsetNoticeReceiver(conn->streamConn, libpqsrv_notice_receiver,
     229                 :             :                         "received message via replication");
     230                 :        1029 :     libpqsrv_connect_complete(conn->streamConn,
     231                 :             :                               WAIT_EVENT_LIBPQWALRECEIVER_CONNECT);
     232                 :             : 
     233         [ +  + ]:        1028 :     if (options_val != NULL)
     234                 :         753 :         pfree(options_val);
     235                 :             : 
     236         [ +  + ]:        1028 :     if (PQstatus(conn->streamConn) != CONNECTION_OK)
     237                 :         143 :         goto bad_connection_errmsg;
     238                 :             : 
     239   [ +  +  -  + ]:         885 :     if (must_use_password && !PQconnectionUsedPassword(conn->streamConn))
     240                 :             :     {
     241                 :           0 :         libpqsrv_disconnect(conn->streamConn);
     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                 :             :      */
     255   [ +  +  +  + ]:         885 :     if (!replication || logical)
     256                 :             :     {
     257                 :             :         PGresult   *res;
     258                 :             : 
     259                 :         735 :         res = libpqsrv_exec(conn->streamConn,
     260                 :             :                             ALWAYS_SECURE_SEARCH_PATH_SQL,
     261                 :             :                             WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
     262         [ -  + ]:         735 :         if (PQresultStatus(res) != PGRES_TUPLES_OK)
     263                 :             :         {
     264                 :           0 :             PQclear(res);
     265                 :           0 :             *err = psprintf(_("could not clear search path: %s"),
     266                 :           0 :                             pchomp(PQerrorMessage(conn->streamConn)));
     267                 :           0 :             goto bad_connection;
     268                 :             :         }
     269                 :         735 :         PQclear(res);
     270                 :             :     }
     271                 :             : 
     272                 :         885 :     conn->logical = logical;
     273                 :             : 
     274                 :         885 :     return conn;
     275                 :             : 
     276                 :             :     /* error path, using libpq's error message */
     277                 :         143 : bad_connection_errmsg:
     278                 :         143 :     *err = pchomp(PQerrorMessage(conn->streamConn));
     279                 :             : 
     280                 :             :     /* error path, error already set */
     281                 :         143 : bad_connection:
     282                 :         143 :     libpqsrv_disconnect(conn->streamConn);
     283                 :         143 :     pfree(conn);
     284                 :         143 :     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
     296                 :        1294 : libpqrcv_check_conninfo(const char *conninfo, bool must_use_password)
     297                 :             : {
     298                 :        1294 :     PQconninfoOption *opts = NULL;
     299                 :             :     PQconninfoOption *opt;
     300                 :        1294 :     char       *err = NULL;
     301                 :             : 
     302                 :        1294 :     opts = PQconninfoParse(conninfo, &err);
     303         [ +  + ]:        1294 :     if (opts == NULL)
     304                 :             :     {
     305                 :             :         /* The error string is malloc'd, so we must free it explicitly */
     306         [ +  - ]:          12 :         char       *errcopy = err ? pstrdup(err) : "out of memory";
     307                 :             : 
     308                 :          12 :         PQfreemem(err);
     309         [ +  - ]:          12 :         ereport(ERROR,
     310                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
     311                 :             :                  errmsg("invalid connection string syntax: %s", errcopy)));
     312                 :             :     }
     313                 :             : 
     314         [ +  + ]:        1282 :     if (must_use_password)
     315                 :             :     {
     316                 :          36 :         bool        uses_password = false;
     317                 :             : 
     318         [ +  + ]:         830 :         for (opt = opts; opt->keyword != NULL; ++opt)
     319                 :             :         {
     320                 :             :             /* Ignore connection options that are not present. */
     321         [ +  + ]:         816 :             if (opt->val == NULL)
     322                 :         748 :                 continue;
     323                 :             : 
     324   [ +  +  +  - ]:          68 :             if (strcmp(opt->keyword, "password") == 0 && opt->val[0] != '\0')
     325                 :             :             {
     326                 :          22 :                 uses_password = true;
     327                 :          22 :                 break;
     328                 :             :             }
     329                 :             :         }
     330                 :             : 
     331         [ +  + ]:          36 :         if (!uses_password)
     332                 :             :         {
     333                 :             :             /* malloc'd, so we must free it explicitly */
     334                 :          14 :             PQconninfoFree(opts);
     335                 :             : 
     336         [ +  - ]:          14 :             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                 :             : 
     343                 :        1268 :     PQconninfoFree(opts);
     344                 :        1268 : }
     345                 :             : 
     346                 :             : /*
     347                 :             :  * Return a user-displayable conninfo string.  Any security-sensitive fields
     348                 :             :  * are obfuscated.
     349                 :             :  */
     350                 :             : static char *
     351                 :         150 : libpqrcv_get_conninfo(WalReceiverConn *conn)
     352                 :             : {
     353                 :             :     PQconninfoOption *conn_opts;
     354                 :             :     PQconninfoOption *conn_opt;
     355                 :             :     PQExpBufferData buf;
     356                 :             :     char       *retval;
     357                 :             : 
     358                 :             :     Assert(conn->streamConn != NULL);
     359                 :             : 
     360                 :         150 :     initPQExpBuffer(&buf);
     361                 :         150 :     conn_opts = PQconninfo(conn->streamConn);
     362                 :             : 
     363         [ -  + ]:         150 :     if (conn_opts == NULL)
     364         [ #  # ]:           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 */
     370         [ +  + ]:        7950 :     for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
     371                 :             :     {
     372                 :             :         bool        obfuscate;
     373                 :             : 
     374                 :             :         /* Skip debug and empty options */
     375         [ +  + ]:        7800 :         if (strchr(conn_opt->dispchar, 'D') ||
     376         [ +  + ]:        7200 :             conn_opt->val == NULL ||
     377         [ +  + ]:        2863 :             conn_opt->val[0] == '\0')
     378                 :        5087 :             continue;
     379                 :             : 
     380                 :             :         /* Obfuscate security-sensitive options */
     381                 :        2713 :         obfuscate = strchr(conn_opt->dispchar, '*') != NULL;
     382                 :             : 
     383         [ +  + ]:        5426 :         appendPQExpBuffer(&buf, "%s%s=%s",
     384         [ +  + ]:        2713 :                           buf.len == 0 ? "" : " ",
     385                 :             :                           conn_opt->keyword,
     386                 :             :                           obfuscate ? "********" : conn_opt->val);
     387                 :             :     }
     388                 :             : 
     389                 :         150 :     PQconninfoFree(conn_opts);
     390                 :             : 
     391         [ +  - ]:         150 :     retval = PQExpBufferDataBroken(buf) ? NULL : pstrdup(buf.data);
     392                 :         150 :     termPQExpBuffer(&buf);
     393                 :         150 :     return retval;
     394                 :             : }
     395                 :             : 
     396                 :             : /*
     397                 :             :  * Provides information of sender this WAL receiver is connected to.
     398                 :             :  */
     399                 :             : static void
     400                 :         150 : libpqrcv_get_senderinfo(WalReceiverConn *conn, char **sender_host,
     401                 :             :                         int *sender_port)
     402                 :             : {
     403                 :         150 :     char       *ret = NULL;
     404                 :             : 
     405                 :         150 :     *sender_host = NULL;
     406                 :         150 :     *sender_port = 0;
     407                 :             : 
     408                 :             :     Assert(conn->streamConn != NULL);
     409                 :             : 
     410                 :         150 :     ret = PQhost(conn->streamConn);
     411   [ +  -  +  - ]:         150 :     if (ret && strlen(ret) != 0)
     412                 :         150 :         *sender_host = pstrdup(ret);
     413                 :             : 
     414                 :         150 :     ret = PQport(conn->streamConn);
     415   [ +  -  +  - ]:         150 :     if (ret && strlen(ret) != 0)
     416                 :         150 :         *sender_port = atoi(ret);
     417                 :         150 : }
     418                 :             : 
     419                 :             : /*
     420                 :             :  * Check that primary's system identifier matches ours, and fetch the current
     421                 :             :  * timeline ID of the primary.
     422                 :             :  */
     423                 :             : static char *
     424                 :         403 : 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                 :             :      */
     433                 :         403 :     res = libpqsrv_exec(conn->streamConn,
     434                 :             :                         "IDENTIFY_SYSTEM",
     435                 :             :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
     436         [ -  + ]:         403 :     if (PQresultStatus(res) != PGRES_TUPLES_OK)
     437         [ #  # ]:           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                 :             :      */
     447   [ +  -  -  + ]:         403 :     if (PQnfields(res) < 3 || PQntuples(res) != 1)
     448         [ #  # ]:           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)));
     453                 :         403 :     primary_sysid = pstrdup(PQgetvalue(res, 0, 0));
     454                 :         403 :     *primary_tli = pg_strtoint32(PQgetvalue(res, 0, 1));
     455                 :         403 :     PQclear(res);
     456                 :             : 
     457                 :         403 :     return primary_sysid;
     458                 :             : }
     459                 :             : 
     460                 :             : /*
     461                 :             :  * Thin wrapper around libpq to obtain server version.
     462                 :             :  */
     463                 :             : static int
     464                 :        1044 : libpqrcv_server_version(WalReceiverConn *conn)
     465                 :             : {
     466                 :        1044 :     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 *
     475                 :          16 : libpqrcv_get_dbname_from_conninfo(const char *connInfo)
     476                 :             : {
     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                 :         769 : libpqrcv_get_option_from_conninfo(const char *connInfo, const char *keyword)
     488                 :             : {
     489                 :             :     PQconninfoOption *opts;
     490                 :         769 :     char       *option = NULL;
     491                 :         769 :     char       *err = NULL;
     492                 :             : 
     493                 :         769 :     opts = PQconninfoParse(connInfo, &err);
     494         [ -  + ]:         769 :     if (opts == NULL)
     495                 :             :     {
     496                 :             :         /* The error string is malloc'd, so we must free it explicitly */
     497         [ #  # ]:           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                 :             : 
     505         [ +  + ]:       40757 :     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                 :             :          */
     511   [ +  +  +  + ]:       39988 :         if (strcmp(opt->keyword, keyword) == 0 && opt->val &&
     512         [ +  - ]:          24 :             *opt->val)
     513                 :             :         {
     514         [ -  + ]:          24 :             if (option)
     515                 :           0 :                 pfree(option);
     516                 :             : 
     517                 :          24 :             option = pstrdup(opt->val);
     518                 :             :         }
     519                 :             :     }
     520                 :             : 
     521                 :         769 :     PQconninfoFree(opts);
     522                 :         769 :     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
     534                 :        2822 : appendQuotedString(StringInfo buf, const char *str, char quote)
     535                 :             : {
     536                 :        2822 :     appendStringInfoChar(buf, quote);
     537         [ +  + ]:       42496 :     while (*str)
     538                 :             :     {
     539                 :       39674 :         char        c = *str++;
     540                 :             : 
     541         [ -  + ]:       39674 :         if (c == quote)
     542                 :           0 :             appendStringInfoChar(buf, c);
     543                 :       39674 :         appendStringInfoChar(buf, c);
     544                 :             :     }
     545                 :        2822 :     appendStringInfoChar(buf, quote);
     546                 :        2822 : }
     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
     562                 :         601 : libpqrcv_startstreaming(WalReceiverConn *conn,
     563                 :             :                         const WalRcvStreamOptions *options)
     564                 :             : {
     565                 :             :     StringInfoData cmd;
     566                 :             :     PGresult   *res;
     567                 :             : 
     568                 :             :     Assert(options->logical == conn->logical);
     569                 :             :     Assert(options->slotname || !options->logical);
     570                 :             : 
     571                 :         601 :     initStringInfo(&cmd);
     572                 :             : 
     573                 :             :     /* Build the command. */
     574                 :         601 :     appendStringInfoString(&cmd, "START_REPLICATION");
     575         [ +  + ]:         601 :     if (options->slotname != NULL)
     576                 :             :     {
     577                 :         487 :         appendStringInfoString(&cmd, " SLOT ");
     578                 :         487 :         appendQuotedIdentifier(&cmd, options->slotname);
     579                 :             :     }
     580                 :             : 
     581         [ +  + ]:         601 :     if (options->logical)
     582                 :         437 :         appendStringInfoString(&cmd, " LOGICAL");
     583                 :             : 
     584                 :         601 :     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                 :             :      */
     590         [ +  + ]:         601 :     if (options->logical)
     591                 :             :     {
     592                 :             :         char       *pubnames_str;
     593                 :             :         List       *pubnames;
     594                 :             : 
     595                 :         437 :         appendStringInfoString(&cmd, " (");
     596                 :             : 
     597                 :         437 :         appendStringInfo(&cmd, "proto_version '%u'",
     598                 :         437 :                          options->proto.logical.proto_version);
     599                 :             : 
     600         [ +  + ]:         437 :         if (options->proto.logical.streaming_str)
     601                 :             :         {
     602                 :         429 :             appendStringInfoString(&cmd, ", streaming ");
     603                 :         429 :             appendQuotedLiteral(&cmd, options->proto.logical.streaming_str);
     604                 :             :         }
     605                 :             : 
     606   [ +  +  +  - ]:         444 :         if (options->proto.logical.twophase &&
     607                 :           7 :             PQserverVersion(conn->streamConn) >= 150000)
     608                 :           7 :             appendStringInfoString(&cmd, ", two_phase 'on'");
     609                 :             : 
     610   [ +  -  +  - ]:         874 :         if (options->proto.logical.origin &&
     611                 :         437 :             PQserverVersion(conn->streamConn) >= 160000)
     612                 :             :         {
     613                 :         437 :             appendStringInfoString(&cmd, ", origin ");
     614                 :         437 :             appendQuotedLiteral(&cmd, options->proto.logical.origin);
     615                 :             :         }
     616                 :             : 
     617                 :         437 :         pubnames = options->proto.logical.publication_names;
     618                 :         437 :         pubnames_str = stringlist_to_identifierstr(pubnames);
     619                 :         437 :         appendStringInfoString(&cmd, ", publication_names ");
     620                 :         437 :         appendQuotedLiteral(&cmd, pubnames_str);
     621                 :         437 :         pfree(pubnames_str);
     622                 :             : 
     623   [ +  +  +  - ]:         447 :         if (options->proto.logical.binary &&
     624                 :          10 :             PQserverVersion(conn->streamConn) >= 140000)
     625                 :          10 :             appendStringInfoString(&cmd, ", binary 'true'");
     626                 :             : 
     627                 :         437 :         appendStringInfoChar(&cmd, ')');
     628                 :             :     }
     629                 :             :     else
     630                 :         164 :         appendStringInfo(&cmd, " TIMELINE %u",
     631                 :         164 :                          options->proto.physical.startpointTLI);
     632                 :             : 
     633                 :             :     /* Start streaming. */
     634                 :         601 :     res = libpqsrv_exec(conn->streamConn,
     635                 :         601 :                         cmd.data,
     636                 :             :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
     637                 :         601 :     pfree(cmd.data);
     638                 :             : 
     639         [ -  + ]:         601 :     if (PQresultStatus(res) == PGRES_COMMAND_OK)
     640                 :             :     {
     641                 :           0 :         PQclear(res);
     642                 :           0 :         return false;
     643                 :             :     }
     644         [ +  + ]:         601 :     else if (PQresultStatus(res) != PGRES_COPY_BOTH)
     645         [ +  - ]:           1 :         ereport(ERROR,
     646                 :             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
     647                 :             :                  errmsg("could not start WAL streaming: %s",
     648                 :             :                         pchomp(PQerrorMessage(conn->streamConn)))));
     649                 :         600 :     PQclear(res);
     650                 :         600 :     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
     658                 :         256 : 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   [ +  +  -  + ]:         468 :     if (PQputCopyEnd(conn->streamConn, NULL) <= 0 ||
     667                 :         212 :         PQflush(conn->streamConn))
     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                 :             : 
     673                 :         212 :     *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                 :             :      */
     683                 :         212 :     res = libpqsrv_get_result(conn->streamConn,
     684                 :             :                               WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
     685         [ +  + ]:         212 :     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                 :             :          */
     691   [ +  -  -  + ]:          14 :         if (PQnfields(res) < 2 || PQntuples(res) != 1)
     692         [ #  # ]:           0 :             ereport(ERROR,
     693                 :             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
     694                 :             :                      errmsg("unexpected result set after end-of-streaming")));
     695                 :          14 :         *next_tli = pg_strtoint32(PQgetvalue(res, 0, 0));
     696                 :          14 :         PQclear(res);
     697                 :             : 
     698                 :             :         /* the result set should be followed by CommandComplete */
     699                 :          14 :         res = libpqsrv_get_result(conn->streamConn,
     700                 :             :                                   WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
     701                 :             :     }
     702         [ +  - ]:         198 :     else if (PQresultStatus(res) == PGRES_COPY_OUT)
     703                 :             :     {
     704                 :         198 :         PQclear(res);
     705                 :             : 
     706                 :             :         /* End the copy */
     707         [ -  + ]:         198 :         if (PQendcopy(conn->streamConn))
     708         [ #  # ]:           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 */
     714                 :         198 :         res = libpqsrv_get_result(conn->streamConn,
     715                 :             :                                   WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
     716                 :             :     }
     717                 :             : 
     718         [ -  + ]:         212 :     if (PQresultStatus(res) != PGRES_COMMAND_OK)
     719         [ #  # ]:           0 :         ereport(ERROR,
     720                 :             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
     721                 :             :                  errmsg("error reading result of streaming command: %s",
     722                 :             :                         pchomp(PQerrorMessage(conn->streamConn)))));
     723                 :         212 :     PQclear(res);
     724                 :             : 
     725                 :             :     /* Verify that there are no more results */
     726                 :         212 :     res = libpqsrv_get_result(conn->streamConn,
     727                 :             :                               WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
     728         [ -  + ]:         212 :     if (res != NULL)
     729         [ #  # ]:           0 :         ereport(ERROR,
     730                 :             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
     731                 :             :                  errmsg("unexpected result after CommandComplete: %s",
     732                 :             :                         pchomp(PQerrorMessage(conn->streamConn)))));
     733                 :         212 : }
     734                 :             : 
     735                 :             : /*
     736                 :             :  * Fetch the timeline history file for 'tli' from primary.
     737                 :             :  */
     738                 :             : static void
     739                 :          13 : libpqrcv_readtimelinehistoryfile(WalReceiverConn *conn,
     740                 :             :                                  TimeLineID tli, char **filename,
     741                 :             :                                  char **content, int *len)
     742                 :             : {
     743                 :             :     PGresult   *res;
     744                 :             :     char        cmd[64];
     745                 :             : 
     746                 :             :     Assert(!conn->logical);
     747                 :             : 
     748                 :             :     /*
     749                 :             :      * Request the primary to send over the history file for given timeline.
     750                 :             :      */
     751                 :          13 :     snprintf(cmd, sizeof(cmd), "TIMELINE_HISTORY %u", tli);
     752                 :          13 :     res = libpqsrv_exec(conn->streamConn,
     753                 :             :                         cmd,
     754                 :             :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
     755         [ -  + ]:          13 :     if (PQresultStatus(res) != PGRES_TUPLES_OK)
     756         [ #  # ]:           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)))));
     761   [ +  -  -  + ]:          13 :     if (PQnfields(res) != 2 || PQntuples(res) != 1)
     762         [ #  # ]:           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))));
     767                 :          13 :     *filename = pstrdup(PQgetvalue(res, 0, 0));
     768                 :             : 
     769                 :          13 :     *len = PQgetlength(res, 0, 1);
     770                 :          13 :     *content = palloc(*len);
     771                 :          13 :     memcpy(*content, PQgetvalue(res, 0, 1), *len);
     772                 :          13 :     PQclear(res);
     773                 :          13 : }
     774                 :             : 
     775                 :             : /*
     776                 :             :  * Disconnect connection to primary, if any.
     777                 :             :  */
     778                 :             : static void
     779                 :         885 : libpqrcv_disconnect(WalReceiverConn *conn)
     780                 :             : {
     781                 :         885 :     libpqsrv_disconnect(conn->streamConn);
     782                 :         885 :     PQfreemem(conn->recvBuf);
     783                 :         885 :     pfree(conn);
     784                 :         885 : }
     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
     803                 :      410308 : libpqrcv_receive(WalReceiverConn *conn, char **buffer,
     804                 :             :                  pgsocket *wait_fd)
     805                 :             : {
     806                 :             :     int         rawlen;
     807                 :             : 
     808                 :      410308 :     PQfreemem(conn->recvBuf);
     809                 :      410308 :     conn->recvBuf = NULL;
     810                 :             : 
     811                 :             :     /* Try to receive a CopyData message */
     812                 :      410308 :     rawlen = PQgetCopyData(conn->streamConn, &conn->recvBuf, 1);
     813         [ +  + ]:      410308 :     if (rawlen == 0)
     814                 :             :     {
     815                 :             :         /* Try consuming some data. */
     816         [ +  + ]:      201648 :         if (PQconsumeInput(conn->streamConn) == 0)
     817         [ +  - ]:          36 :             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 */
     823                 :      201612 :         rawlen = PQgetCopyData(conn->streamConn, &conn->recvBuf, 1);
     824         [ +  + ]:      201612 :         if (rawlen == 0)
     825                 :             :         {
     826                 :             :             /* Tell caller to try again when our socket is ready. */
     827                 :       79504 :             *wait_fd = PQsocket(conn->streamConn);
     828                 :       79504 :             return 0;
     829                 :             :         }
     830                 :             :     }
     831         [ +  + ]:      330768 :     if (rawlen == -1)           /* end-of-streaming or error */
     832                 :             :     {
     833                 :             :         PGresult   *res;
     834                 :             : 
     835                 :         269 :         res = libpqsrv_get_result(conn->streamConn,
     836                 :             :                                   WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
     837         [ +  + ]:         269 :         if (PQresultStatus(res) == PGRES_COMMAND_OK)
     838                 :             :         {
     839                 :         252 :             PQclear(res);
     840                 :             : 
     841                 :             :             /* Verify that there are no more results. */
     842                 :         252 :             res = libpqsrv_get_result(conn->streamConn,
     843                 :             :                                       WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
     844         [ +  + ]:         252 :             if (res != NULL)
     845                 :             :             {
     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                 :             : 
     856         [ #  # ]:           0 :                 ereport(ERROR,
     857                 :             :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
     858                 :             :                          errmsg("unexpected result after CommandComplete: %s",
     859                 :             :                                 PQerrorMessage(conn->streamConn))));
     860                 :             :             }
     861                 :             : 
     862                 :         207 :             return -1;
     863                 :             :         }
     864         [ +  + ]:          17 :         else if (PQresultStatus(res) == PGRES_COPY_IN)
     865                 :             :         {
     866                 :          14 :             PQclear(res);
     867                 :          14 :             return -1;
     868                 :             :         }
     869                 :             :         else
     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         [ -  + ]:      330499 :     if (rawlen < -1)
     876         [ #  # ]:           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 */
     882                 :      330499 :     *buffer = conn->recvBuf;
     883                 :      330499 :     return rawlen;
     884                 :             : }
     885                 :             : 
     886                 :             : /*
     887                 :             :  * Send a message to XLOG stream.
     888                 :             :  *
     889                 :             :  * ereports on error.
     890                 :             :  */
     891                 :             : static void
     892                 :      118571 : libpqrcv_send(WalReceiverConn *conn, const char *buffer, int nbytes)
     893                 :             : {
     894   [ +  +  +  + ]:      237141 :     if (PQputCopyData(conn->streamConn, buffer, nbytes) <= 0 ||
     895                 :      118570 :         PQflush(conn->streamConn))
     896         [ +  - ]:           2 :         ereport(ERROR,
     897                 :             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
     898                 :             :                  errmsg("could not send data to WAL stream: %s",
     899                 :             :                         pchomp(PQerrorMessage(conn->streamConn)))));
     900                 :      118569 : }
     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 *
     908                 :         332 : 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                 :             : 
     917                 :         332 :     use_new_options_syntax = (PQserverVersion(conn->streamConn) >= 150000);
     918                 :             : 
     919                 :         332 :     initStringInfo(&cmd);
     920                 :             : 
     921                 :         332 :     appendStringInfoString(&cmd, "CREATE_REPLICATION_SLOT ");
     922                 :         332 :     appendQuotedIdentifier(&cmd, slotname);
     923                 :             : 
     924         [ -  + ]:         332 :     if (temporary)
     925                 :           0 :         appendStringInfoString(&cmd, " TEMPORARY");
     926                 :             : 
     927         [ +  - ]:         332 :     if (conn->logical)
     928                 :             :     {
     929                 :         332 :         appendStringInfoString(&cmd, " LOGICAL pgoutput ");
     930         [ +  - ]:         332 :         if (use_new_options_syntax)
     931                 :         332 :             appendStringInfoChar(&cmd, '(');
     932         [ +  + ]:         332 :         if (two_phase)
     933                 :             :         {
     934                 :           1 :             appendStringInfoString(&cmd, "TWO_PHASE");
     935         [ +  - ]:           1 :             if (use_new_options_syntax)
     936                 :           1 :                 appendStringInfoString(&cmd, ", ");
     937                 :             :             else
     938                 :           0 :                 appendStringInfoChar(&cmd, ' ');
     939                 :             :         }
     940                 :             : 
     941         [ +  + ]:         332 :         if (failover)
     942                 :             :         {
     943                 :          11 :             appendStringInfoString(&cmd, "FAILOVER");
     944         [ +  - ]:          11 :             if (use_new_options_syntax)
     945                 :          11 :                 appendStringInfoString(&cmd, ", ");
     946                 :             :             else
     947                 :           0 :                 appendStringInfoChar(&cmd, ' ');
     948                 :             :         }
     949                 :             : 
     950         [ +  - ]:         332 :         if (use_new_options_syntax)
     951                 :             :         {
     952   [ -  +  +  - ]:         332 :             switch (snapshot_action)
     953                 :             :             {
     954                 :           0 :                 case CRS_EXPORT_SNAPSHOT:
     955                 :           0 :                     appendStringInfoString(&cmd, "SNAPSHOT 'export'");
     956                 :           0 :                     break;
     957                 :         120 :                 case CRS_NOEXPORT_SNAPSHOT:
     958                 :         120 :                     appendStringInfoString(&cmd, "SNAPSHOT 'nothing'");
     959                 :         120 :                     break;
     960                 :         212 :                 case CRS_USE_SNAPSHOT:
     961                 :         212 :                     appendStringInfoString(&cmd, "SNAPSHOT 'use'");
     962                 :         212 :                     break;
     963                 :             :             }
     964                 :             :         }
     965                 :             :         else
     966                 :             :         {
     967   [ #  #  #  # ]:           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                 :             : 
     981         [ +  - ]:         332 :         if (use_new_options_syntax)
     982                 :         332 :             appendStringInfoChar(&cmd, ')');
     983                 :             :     }
     984                 :             :     else
     985                 :             :     {
     986         [ #  # ]:           0 :         if (use_new_options_syntax)
     987                 :           0 :             appendStringInfoString(&cmd, " PHYSICAL (RESERVE_WAL)");
     988                 :             :         else
     989                 :           0 :             appendStringInfoString(&cmd, " PHYSICAL RESERVE_WAL");
     990                 :             :     }
     991                 :             : 
     992                 :         332 :     res = libpqsrv_exec(conn->streamConn,
     993                 :         332 :                         cmd.data,
     994                 :             :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
     995                 :         332 :     pfree(cmd.data);
     996                 :             : 
     997         [ -  + ]:         332 :     if (PQresultStatus(res) != PGRES_TUPLES_OK)
     998         [ #  # ]:           0 :         ereport(ERROR,
     999                 :             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1000                 :             :                  errmsg("could not create replication slot \"%s\": %s",
    1001                 :             :                         slotname, pchomp(PQerrorMessage(conn->streamConn)))));
    1002                 :             : 
    1003         [ +  + ]:         332 :     if (lsn)
    1004                 :         212 :         *lsn = DatumGetLSN(DirectFunctionCall1Coll(pg_lsn_in, InvalidOid,
    1005                 :         212 :                                                    CStringGetDatum(PQgetvalue(res, 0, 1))));
    1006                 :             : 
    1007         [ -  + ]:         332 :     if (!PQgetisnull(res, 0, 2))
    1008                 :           0 :         snapshot = pstrdup(PQgetvalue(res, 0, 2));
    1009                 :             :     else
    1010                 :         332 :         snapshot = NULL;
    1011                 :             : 
    1012                 :         332 :     PQclear(res);
    1013                 :             : 
    1014                 :         332 :     return snapshot;
    1015                 :             : }
    1016                 :             : 
    1017                 :             : /*
    1018                 :             :  * Change the definition of the replication slot.
    1019                 :             :  */
    1020                 :             : static void
    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);
    1028                 :           5 :     appendStringInfoString(&cmd, "ALTER_REPLICATION_SLOT ");
    1029                 :           5 :     appendQuotedIdentifier(&cmd, slotname);
    1030                 :           5 :     appendStringInfoString(&cmd, " ( ");
    1031                 :             : 
    1032         [ +  + ]:           5 :     if (failover)
    1033                 :           4 :         appendStringInfo(&cmd, "FAILOVER %s",
    1034         [ +  + ]:           4 :                          *failover ? "true" : "false");
    1035                 :             : 
    1036   [ +  +  -  + ]:           5 :     if (failover && two_phase)
    1037                 :           0 :         appendStringInfoString(&cmd, ", ");
    1038                 :             : 
    1039         [ +  + ]:           5 :     if (two_phase)
    1040                 :           1 :         appendStringInfo(&cmd, "TWO_PHASE %s",
    1041         [ -  + ]:           1 :                          *two_phase ? "true" : "false");
    1042                 :             : 
    1043                 :           5 :     appendStringInfoString(&cmd, " );");
    1044                 :             : 
    1045                 :           5 :     res = libpqsrv_exec(conn->streamConn, cmd.data,
    1046                 :             :                         WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
    1047                 :           5 :     pfree(cmd.data);
    1048                 :             : 
    1049         [ -  + ]:           5 :     if (PQresultStatus(res) != PGRES_COMMAND_OK)
    1050         [ #  # ]:           0 :         ereport(ERROR,
    1051                 :             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1052                 :             :                  errmsg("could not alter replication slot \"%s\": %s",
    1053                 :             :                         slotname, pchomp(PQerrorMessage(conn->streamConn)))));
    1054                 :             : 
    1055                 :           5 :     PQclear(res);
    1056                 :           5 : }
    1057                 :             : 
    1058                 :             : /*
    1059                 :             :  * Return PID of remote backend process.
    1060                 :             :  */
    1061                 :             : static pid_t
    1062                 :           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
    1071                 :        1232 : libpqrcv_processTuples(PGresult *pgres, WalRcvExecResult *walres,
    1072                 :             :                        const int nRetTypes, const Oid *retTypes)
    1073                 :             : {
    1074                 :             :     int         tupn;
    1075                 :             :     int         coln;
    1076                 :        1232 :     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. */
    1083         [ -  + ]:        1232 :     if (nfields != nRetTypes)
    1084         [ #  # ]:           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                 :             : 
    1090                 :        1232 :     walres->tuplestore = tuplestore_begin_heap(true, false, work_mem);
    1091                 :             : 
    1092                 :             :     /* Create tuple descriptor corresponding to expected result. */
    1093                 :        1232 :     walres->tupledesc = CreateTemplateTupleDesc(nRetTypes);
    1094         [ +  + ]:        4582 :     for (coln = 0; coln < nRetTypes; coln++)
    1095                 :        3350 :         TupleDescInitEntry(walres->tupledesc, (AttrNumber) coln + 1,
    1096                 :        3350 :                            PQfname(pgres, coln), retTypes[coln], -1, 0);
    1097                 :        1232 :     TupleDescFinalize(walres->tupledesc);
    1098                 :        1232 :     attinmeta = TupleDescGetAttInMetadata(walres->tupledesc);
    1099                 :             : 
    1100                 :             :     /* No point in doing more here if there were no tuples returned. */
    1101         [ +  + ]:        1232 :     if (PQntuples(pgres) == 0)
    1102                 :          35 :         return;
    1103                 :             : 
    1104                 :             :     /* Create temporary context for local allocations. */
    1105                 :        1197 :     rowcontext = AllocSetContextCreate(CurrentMemoryContext,
    1106                 :             :                                        "libpqrcv query result context",
    1107                 :             :                                        ALLOCSET_DEFAULT_SIZES);
    1108                 :             : 
    1109                 :             :     /* Process returned rows. */
    1110         [ +  + ]:        2777 :     for (tupn = 0; tupn < PQntuples(pgres); tupn++)
    1111                 :             :     {
    1112                 :             :         char       *cstrs[MaxTupleAttributeNumber];
    1113                 :             : 
    1114         [ -  + ]:        1580 :         CHECK_FOR_INTERRUPTS();
    1115                 :             : 
    1116                 :             :         /* Do the allocations in temporary context. */
    1117                 :        1580 :         oldcontext = MemoryContextSwitchTo(rowcontext);
    1118                 :             : 
    1119                 :             :         /*
    1120                 :             :          * Fill cstrs with null-terminated strings of column values.
    1121                 :             :          */
    1122         [ +  + ]:        6599 :         for (coln = 0; coln < nfields; coln++)
    1123                 :             :         {
    1124         [ +  + ]:        5019 :             if (PQgetisnull(pgres, tupn, coln))
    1125                 :         662 :                 cstrs[coln] = NULL;
    1126                 :             :             else
    1127                 :        4357 :                 cstrs[coln] = PQgetvalue(pgres, tupn, coln);
    1128                 :             :         }
    1129                 :             : 
    1130                 :             :         /* Convert row to a tuple, and add it to the tuplestore */
    1131                 :        1580 :         tuple = BuildTupleFromCStrings(attinmeta, cstrs);
    1132                 :        1580 :         tuplestore_puttuple(walres->tuplestore, tuple);
    1133                 :             : 
    1134                 :             :         /* Clean up */
    1135                 :        1580 :         MemoryContextSwitchTo(oldcontext);
    1136                 :        1580 :         MemoryContextReset(rowcontext);
    1137                 :             :     }
    1138                 :             : 
    1139                 :        1197 :     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                 :        2145 : libpqrcv_exec(WalReceiverConn *conn, const char *query,
    1149                 :             :               const int nRetTypes, const Oid *retTypes)
    1150                 :             : {
    1151                 :        2145 :     PGresult   *pgres = NULL;
    1152                 :        2145 :     WalRcvExecResult *walres = palloc0_object(WalRcvExecResult);
    1153                 :             :     char       *diag_sqlstate;
    1154                 :             : 
    1155         [ -  + ]:        2145 :     if (MyDatabaseId == InvalidOid)
    1156         [ #  # ]:           0 :         ereport(ERROR,
    1157                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1158                 :             :                  errmsg("the query interface requires a database connection")));
    1159                 :             : 
    1160                 :        2145 :     pgres = libpqsrv_exec(conn->streamConn,
    1161                 :             :                           query,
    1162                 :             :                           WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
    1163                 :             : 
    1164   [ +  -  +  -  :        2144 :     switch (PQresultStatus(pgres))
             +  -  -  +  
                      - ]
    1165                 :             :     {
    1166                 :        1232 :         case PGRES_TUPLES_OK:
    1167                 :             :         case PGRES_SINGLE_TUPLE:
    1168                 :             :         case PGRES_TUPLES_CHUNK:
    1169                 :        1232 :             walres->status = WALRCV_OK_TUPLES;
    1170                 :        1232 :             libpqrcv_processTuples(pgres, walres, nRetTypes, retTypes);
    1171                 :        1232 :             break;
    1172                 :             : 
    1173                 :           0 :         case PGRES_COPY_IN:
    1174                 :           0 :             walres->status = WALRCV_OK_COPY_IN;
    1175                 :           0 :             break;
    1176                 :             : 
    1177                 :         209 :         case PGRES_COPY_OUT:
    1178                 :         209 :             walres->status = WALRCV_OK_COPY_OUT;
    1179                 :         209 :             break;
    1180                 :             : 
    1181                 :           0 :         case PGRES_COPY_BOTH:
    1182                 :           0 :             walres->status = WALRCV_OK_COPY_BOTH;
    1183                 :           0 :             break;
    1184                 :             : 
    1185                 :         698 :         case PGRES_COMMAND_OK:
    1186                 :         698 :             walres->status = WALRCV_OK_COMMAND;
    1187                 :         698 :             break;
    1188                 :             : 
    1189                 :             :             /* Empty query is considered error. */
    1190                 :           0 :         case PGRES_EMPTY_QUERY:
    1191                 :           0 :             walres->status = WALRCV_ERROR;
    1192                 :           0 :             walres->err = _("empty query");
    1193                 :           0 :             break;
    1194                 :             : 
    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                 :             : 
    1201                 :           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));
    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]);
    1213                 :           5 :             break;
    1214                 :             :     }
    1215                 :             : 
    1216                 :        2144 :     PQclear(pgres);
    1217                 :             : 
    1218                 :        2144 :     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 *
    1230                 :         437 : stringlist_to_identifierstr(List *strings)
    1231                 :             : {
    1232                 :             :     ListCell   *lc;
    1233                 :             :     StringInfoData res;
    1234                 :         437 :     bool        first = true;
    1235                 :             : 
    1236                 :         437 :     initStringInfo(&res);
    1237                 :             : 
    1238   [ +  -  +  +  :        1132 :     foreach(lc, strings)
                   +  + ]
    1239                 :             :     {
    1240                 :         695 :         char       *val = strVal(lfirst(lc));
    1241                 :             : 
    1242         [ +  + ]:         695 :         if (first)
    1243                 :         437 :             first = false;
    1244                 :             :         else
    1245                 :         258 :             appendStringInfoChar(&res, ',');
    1246                 :         695 :         appendQuotedIdentifier(&res, val);
    1247                 :             :     }
    1248                 :             : 
    1249                 :         437 :     return res.data;
    1250                 :             : }
        

Generated by: LCOV version 2.0-1