PostgreSQL Source Code  git master
libpqwalreceiver.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <sys/time.h>
#include "access/xlog.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "libpq-fe.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "pqexpbuffer.h"
#include "replication/walreceiver.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "utils/pg_lsn.h"
#include "utils/tuplestore.h"
Include dependency graph for libpqwalreceiver.c:

Go to the source code of this file.

Data Structures

struct  WalReceiverConn
 

Functions

void _PG_init (void)
 
static WalReceiverConnlibpqrcv_connect (const char *conninfo, bool logical, const char *appname, char **err)
 
static void libpqrcv_check_conninfo (const char *conninfo)
 
static char * libpqrcv_get_conninfo (WalReceiverConn *conn)
 
static void libpqrcv_get_senderinfo (WalReceiverConn *conn, char **sender_host, int *sender_port)
 
static char * libpqrcv_identify_system (WalReceiverConn *conn, TimeLineID *primary_tli)
 
static int libpqrcv_server_version (WalReceiverConn *conn)
 
static void libpqrcv_readtimelinehistoryfile (WalReceiverConn *conn, TimeLineID tli, char **filename, char **content, int *len)
 
static bool libpqrcv_startstreaming (WalReceiverConn *conn, const WalRcvStreamOptions *options)
 
static void libpqrcv_endstreaming (WalReceiverConn *conn, TimeLineID *next_tli)
 
static int libpqrcv_receive (WalReceiverConn *conn, char **buffer, pgsocket *wait_fd)
 
static void libpqrcv_send (WalReceiverConn *conn, const char *buffer, int nbytes)
 
static char * libpqrcv_create_slot (WalReceiverConn *conn, const char *slotname, bool temporary, CRSSnapshotAction snapshot_action, XLogRecPtr *lsn)
 
static pid_t libpqrcv_get_backend_pid (WalReceiverConn *conn)
 
static WalRcvExecResultlibpqrcv_exec (WalReceiverConn *conn, const char *query, const int nRetTypes, const Oid *retTypes)
 
static void libpqrcv_disconnect (WalReceiverConn *conn)
 
static PGresultlibpqrcv_PQexec (PGconn *streamConn, const char *query)
 
static PGresultlibpqrcv_PQgetResult (PGconn *streamConn)
 
static char * stringlist_to_identifierstr (PGconn *conn, List *strings)
 
static void libpqrcv_processTuples (PGresult *pgres, WalRcvExecResult *walres, const int nRetTypes, const Oid *retTypes)
 

Variables

 PG_MODULE_MAGIC
 
static WalReceiverFunctionsType PQWalReceiverFunctions
 

Function Documentation

◆ _PG_init()

void _PG_init ( void  )

Definition at line 111 of file libpqwalreceiver.c.

References elog, ERROR, PQWalReceiverFunctions, and WalReceiverFunctions.

112 {
113  if (WalReceiverFunctions != NULL)
114  elog(ERROR, "libpqwalreceiver already loaded");
116 }
#define ERROR
Definition: elog.h:43
static WalReceiverFunctionsType PQWalReceiverFunctions
WalReceiverFunctionsType * WalReceiverFunctions
Definition: walreceiver.c:83
#define elog(elevel,...)
Definition: elog.h:228

◆ libpqrcv_check_conninfo()

static void libpqrcv_check_conninfo ( const char *  conninfo)
static

Definition at line 225 of file libpqwalreceiver.c.

References ereport, errcode(), errmsg(), ERROR, PQconninfoFree(), and PQconninfoParse().

226 {
227  PQconninfoOption *opts = NULL;
228  char *err = NULL;
229 
230  opts = PQconninfoParse(conninfo, &err);
231  if (opts == NULL)
232  ereport(ERROR,
233  (errcode(ERRCODE_SYNTAX_ERROR),
234  errmsg("invalid connection string syntax: %s", err)));
235 
236  PQconninfoFree(opts);
237 }
int errcode(int sqlerrcode)
Definition: elog.c:608
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:5286
#define ERROR
Definition: elog.h:43
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6516
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ libpqrcv_connect()

static WalReceiverConn * libpqrcv_connect ( const char *  conninfo,
bool  logical,
const char *  appname,
char **  err 
)
static

Definition at line 124 of file libpqwalreceiver.c.

References Assert, conn, CONNECTION_BAD, CONNECTION_OK, CONNECTION_STARTED, GetDatabaseEncodingName(), i, WalReceiverConn::logical, MyLatch, palloc0(), pchomp(), PGRES_POLLING_FAILED, PGRES_POLLING_OK, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PQconnectPoll(), PQconnectStartParams(), PQerrorMessage(), PQsocket(), PQstatus(), ProcessWalRcvInterrupts(), ResetLatch(), status(), WalReceiverConn::streamConn, WAIT_EVENT_LIBPQWALRECEIVER_CONNECT, WaitLatchOrSocket(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_SOCKET_CONNECTED, WL_SOCKET_READABLE, and WL_SOCKET_WRITEABLE.

126 {
129  const char *keys[5];
130  const char *vals[5];
131  int i = 0;
132 
133  /*
134  * We use the expand_dbname parameter to process the connection string (or
135  * URI), and pass some extra options.
136  */
137  keys[i] = "dbname";
138  vals[i] = conninfo;
139  keys[++i] = "replication";
140  vals[i] = logical ? "database" : "true";
141  if (!logical)
142  {
143  /*
144  * The database name is ignored by the server in replication mode, but
145  * specify "replication" for .pgpass lookup.
146  */
147  keys[++i] = "dbname";
148  vals[i] = "replication";
149  }
150  keys[++i] = "fallback_application_name";
151  vals[i] = appname;
152  if (logical)
153  {
154  keys[++i] = "client_encoding";
155  vals[i] = GetDatabaseEncodingName();
156  }
157  keys[++i] = NULL;
158  vals[i] = NULL;
159 
160  Assert(i < sizeof(keys));
161 
162  conn = palloc0(sizeof(WalReceiverConn));
163  conn->streamConn = PQconnectStartParams(keys, vals,
164  /* expand_dbname = */ true);
165  if (PQstatus(conn->streamConn) == CONNECTION_BAD)
166  {
167  *err = pchomp(PQerrorMessage(conn->streamConn));
168  return NULL;
169  }
170 
171  /*
172  * Poll connection until we have OK or FAILED status.
173  *
174  * Per spec for PQconnectPoll, first wait till socket is write-ready.
175  */
176  status = PGRES_POLLING_WRITING;
177  do
178  {
179  int io_flag;
180  int rc;
181 
182  if (status == PGRES_POLLING_READING)
183  io_flag = WL_SOCKET_READABLE;
184 #ifdef WIN32
185  /* Windows needs a different test while waiting for connection-made */
186  else if (PQstatus(conn->streamConn) == CONNECTION_STARTED)
187  io_flag = WL_SOCKET_CONNECTED;
188 #endif
189  else
190  io_flag = WL_SOCKET_WRITEABLE;
191 
193  WL_EXIT_ON_PM_DEATH | WL_LATCH_SET | io_flag,
194  PQsocket(conn->streamConn),
195  0,
197 
198  /* Interrupted? */
199  if (rc & WL_LATCH_SET)
200  {
203  }
204 
205  /* If socket is ready, advance the libpq state machine */
206  if (rc & io_flag)
207  status = PQconnectPoll(conn->streamConn);
208  } while (status != PGRES_POLLING_OK && status != PGRES_POLLING_FAILED);
209 
210  if (PQstatus(conn->streamConn) != CONNECTION_OK)
211  {
212  *err = pchomp(PQerrorMessage(conn->streamConn));
213  return NULL;
214  }
215 
216  conn->logical = logical;
217 
218  return conn;
219 }
#define WL_SOCKET_WRITEABLE
Definition: latch.h:126
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6684
void ProcessWalRcvInterrupts(void)
Definition: walreceiver.c:146
#define WL_SOCKET_READABLE
Definition: latch.h:125
void ResetLatch(Latch *latch)
Definition: latch.c:531
char * pchomp(const char *in)
Definition: mcxt.c:1214
PGconn * conn
Definition: streamutil.c:54
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:381
void * palloc0(Size size)
Definition: mcxt.c:980
PostgresPollingStatusType PQconnectPoll(PGconn *conn)
Definition: fe-connect.c:2254
#define Assert(condition)
Definition: c.h:738
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1052
PostgresPollingStatusType
Definition: libpq-fe.h:74
int i
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:743
struct Latch * MyLatch
Definition: globals.c:54
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6631
#define WL_SOCKET_CONNECTED
Definition: latch.h:134
#define WL_LATCH_SET
Definition: latch.h:124
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:6702
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

◆ libpqrcv_create_slot()

static char * libpqrcv_create_slot ( WalReceiverConn conn,
const char *  slotname,
bool  temporary,
CRSSnapshotAction  snapshot_action,
XLogRecPtr lsn 
)
static

Definition at line 806 of file libpqwalreceiver.c.

References appendStringInfo(), appendStringInfoString(), CRS_EXPORT_SNAPSHOT, CRS_NOEXPORT_SNAPSHOT, CRS_USE_SNAPSHOT, CStringGetDatum, StringInfoData::data, DatumGetLSN, DirectFunctionCall1Coll(), ereport, errmsg(), ERROR, initStringInfo(), InvalidOid, libpqrcv_PQexec(), WalReceiverConn::logical, pchomp(), pfree(), pg_lsn_in(), PGRES_TUPLES_OK, PQclear(), PQerrorMessage(), PQgetisnull(), PQgetvalue(), PQresultStatus(), pstrdup(), and WalReceiverConn::streamConn.

809 {
810  PGresult *res;
811  StringInfoData cmd;
812  char *snapshot;
813 
814  initStringInfo(&cmd);
815 
816  appendStringInfo(&cmd, "CREATE_REPLICATION_SLOT \"%s\"", slotname);
817 
818  if (temporary)
819  appendStringInfoString(&cmd, " TEMPORARY");
820 
821  if (conn->logical)
822  {
823  appendStringInfoString(&cmd, " LOGICAL pgoutput");
824  switch (snapshot_action)
825  {
826  case CRS_EXPORT_SNAPSHOT:
827  appendStringInfoString(&cmd, " EXPORT_SNAPSHOT");
828  break;
830  appendStringInfoString(&cmd, " NOEXPORT_SNAPSHOT");
831  break;
832  case CRS_USE_SNAPSHOT:
833  appendStringInfoString(&cmd, " USE_SNAPSHOT");
834  break;
835  }
836  }
837  else
838  {
839  appendStringInfoString(&cmd, " PHYSICAL RESERVE_WAL");
840  }
841 
842  res = libpqrcv_PQexec(conn->streamConn, cmd.data);
843  pfree(cmd.data);
844 
845  if (PQresultStatus(res) != PGRES_TUPLES_OK)
846  {
847  PQclear(res);
848  ereport(ERROR,
849  (errmsg("could not create replication slot \"%s\": %s",
850  slotname, pchomp(PQerrorMessage(conn->streamConn)))));
851  }
852 
853  if (lsn)
855  CStringGetDatum(PQgetvalue(res, 0, 1))));
856 
857  if (!PQgetisnull(res, 0, 2))
858  snapshot = pstrdup(PQgetvalue(res, 0, 2));
859  else
860  snapshot = NULL;
861 
862  PQclear(res);
863 
864  return snapshot;
865 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6684
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3163
char * pstrdup(const char *in)
Definition: mcxt.c:1186
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
Datum pg_lsn_in(PG_FUNCTION_ARGS)
Definition: pg_lsn.c:63
char * pchomp(const char *in)
Definition: mcxt.c:1214
void pfree(void *pointer)
Definition: mcxt.c:1056
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
#define CStringGetDatum(X)
Definition: postgres.h:578
Datum DirectFunctionCall1Coll(PGFunction func, Oid collation, Datum arg1)
Definition: fmgr.c:793
#define ereport(elevel, rest)
Definition: elog.h:141
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
static PGresult * libpqrcv_PQexec(PGconn *streamConn, const char *query)
#define InvalidOid
Definition: postgres_ext.h:36
#define DatumGetLSN(X)
Definition: pg_lsn.h:21
void PQclear(PGresult *res)
Definition: fe-exec.c:694
int errmsg(const char *fmt,...)
Definition: elog.c:822
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3188

◆ libpqrcv_disconnect()

static void libpqrcv_disconnect ( WalReceiverConn conn)
static

Definition at line 679 of file libpqwalreceiver.c.

References pfree(), PQfinish(), PQfreemem(), WalReceiverConn::recvBuf, and WalReceiverConn::streamConn.

680 {
681  PQfinish(conn->streamConn);
682  if (conn->recvBuf != NULL)
683  PQfreemem(conn->recvBuf);
684  pfree(conn);
685 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4182
void pfree(void *pointer)
Definition: mcxt.c:1056
void PQfreemem(void *ptr)
Definition: fe-exec.c:3296

◆ libpqrcv_endstreaming()

static void libpqrcv_endstreaming ( WalReceiverConn conn,
TimeLineID next_tli 
)
static

Definition at line 458 of file libpqwalreceiver.c.

References ereport, errmsg(), ERROR, libpqrcv_PQgetResult(), pchomp(), pg_strtoint32(), PGRES_COMMAND_OK, PGRES_COPY_OUT, PGRES_TUPLES_OK, PQclear(), PQendcopy(), PQerrorMessage(), PQflush(), PQgetvalue(), PQnfields(), PQntuples(), PQputCopyEnd(), PQresultStatus(), and WalReceiverConn::streamConn.

459 {
460  PGresult *res;
461 
462  /*
463  * Send copy-end message. As in libpqrcv_PQexec, this could theoretically
464  * block, but the risk seems small.
465  */
466  if (PQputCopyEnd(conn->streamConn, NULL) <= 0 ||
467  PQflush(conn->streamConn))
468  ereport(ERROR,
469  (errmsg("could not send end-of-streaming message to primary: %s",
470  pchomp(PQerrorMessage(conn->streamConn)))));
471 
472  *next_tli = 0;
473 
474  /*
475  * After COPY is finished, we should receive a result set indicating the
476  * next timeline's ID, or just CommandComplete if the server was shut
477  * down.
478  *
479  * If we had not yet received CopyDone from the backend, PGRES_COPY_OUT is
480  * also possible in case we aborted the copy in mid-stream.
481  */
482  res = libpqrcv_PQgetResult(conn->streamConn);
483  if (PQresultStatus(res) == PGRES_TUPLES_OK)
484  {
485  /*
486  * Read the next timeline's ID. The server also sends the timeline's
487  * starting point, but it is ignored.
488  */
489  if (PQnfields(res) < 2 || PQntuples(res) != 1)
490  ereport(ERROR,
491  (errmsg("unexpected result set after end-of-streaming")));
492  *next_tli = pg_strtoint32(PQgetvalue(res, 0, 0));
493  PQclear(res);
494 
495  /* the result set should be followed by CommandComplete */
496  res = libpqrcv_PQgetResult(conn->streamConn);
497  }
498  else if (PQresultStatus(res) == PGRES_COPY_OUT)
499  {
500  PQclear(res);
501 
502  /* End the copy */
503  if (PQendcopy(conn->streamConn))
504  ereport(ERROR,
505  (errmsg("error while shutting down streaming COPY: %s",
506  pchomp(PQerrorMessage(conn->streamConn)))));
507 
508  /* CommandComplete should follow */
509  res = libpqrcv_PQgetResult(conn->streamConn);
510  }
511 
512  if (PQresultStatus(res) != PGRES_COMMAND_OK)
513  ereport(ERROR,
514  (errmsg("error reading result of streaming command: %s",
515  pchomp(PQerrorMessage(conn->streamConn)))));
516  PQclear(res);
517 
518  /* Verify that there are no more results */
519  res = libpqrcv_PQgetResult(conn->streamConn);
520  if (res != NULL)
521  ereport(ERROR,
522  (errmsg("unexpected result after CommandComplete: %s",
523  pchomp(PQerrorMessage(conn->streamConn)))));
524 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2777
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6684
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3163
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2384
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2769
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
static PGresult * libpqrcv_PQgetResult(PGconn *streamConn)
char * pchomp(const char *in)
Definition: mcxt.c:1214
#define ERROR
Definition: elog.h:43
int PQflush(PGconn *conn)
Definition: fe-exec.c:3283
#define ereport(elevel, rest)
Definition: elog.h:141
void PQclear(PGresult *res)
Definition: fe-exec.c:694
int PQendcopy(PGconn *conn)
Definition: fe-exec.c:2618
int32 pg_strtoint32(const char *s)
Definition: numutils.c:261
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ libpqrcv_exec()

static WalRcvExecResult * libpqrcv_exec ( WalReceiverConn conn,
const char *  query,
const int  nRetTypes,
const Oid retTypes 
)
static

Definition at line 955 of file libpqwalreceiver.c.

References _, ereport, WalRcvExecResult::err, errcode(), errmsg(), ERROR, InvalidOid, libpqrcv_PQexec(), libpqrcv_processTuples(), MyDatabaseId, palloc0(), pchomp(), PGRES_BAD_RESPONSE, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_NONFATAL_ERROR, PGRES_SINGLE_TUPLE, PGRES_TUPLES_OK, PQclear(), PQerrorMessage(), PQresultStatus(), WalRcvExecResult::status, WalReceiverConn::streamConn, WALRCV_ERROR, WALRCV_OK_COMMAND, WALRCV_OK_COPY_BOTH, WALRCV_OK_COPY_IN, WALRCV_OK_COPY_OUT, and WALRCV_OK_TUPLES.

957 {
958  PGresult *pgres = NULL;
959  WalRcvExecResult *walres = palloc0(sizeof(WalRcvExecResult));
960 
961  if (MyDatabaseId == InvalidOid)
962  ereport(ERROR,
963  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
964  errmsg("the query interface requires a database connection")));
965 
966  pgres = libpqrcv_PQexec(conn->streamConn, query);
967 
968  switch (PQresultStatus(pgres))
969  {
970  case PGRES_SINGLE_TUPLE:
971  case PGRES_TUPLES_OK:
972  walres->status = WALRCV_OK_TUPLES;
973  libpqrcv_processTuples(pgres, walres, nRetTypes, retTypes);
974  break;
975 
976  case PGRES_COPY_IN:
977  walres->status = WALRCV_OK_COPY_IN;
978  break;
979 
980  case PGRES_COPY_OUT:
981  walres->status = WALRCV_OK_COPY_OUT;
982  break;
983 
984  case PGRES_COPY_BOTH:
985  walres->status = WALRCV_OK_COPY_BOTH;
986  break;
987 
988  case PGRES_COMMAND_OK:
989  walres->status = WALRCV_OK_COMMAND;
990  break;
991 
992  /* Empty query is considered error. */
993  case PGRES_EMPTY_QUERY:
994  walres->status = WALRCV_ERROR;
995  walres->err = _("empty query");
996  break;
997 
999  case PGRES_FATAL_ERROR:
1000  case PGRES_BAD_RESPONSE:
1001  walres->status = WALRCV_ERROR;
1002  walres->err = pchomp(PQerrorMessage(conn->streamConn));
1003  break;
1004  }
1005 
1006  PQclear(pgres);
1007 
1008  return walres;
1009 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6684
int errcode(int sqlerrcode)
Definition: elog.c:608
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
char * pchomp(const char *in)
Definition: mcxt.c:1214
#define ERROR
Definition: elog.h:43
static void libpqrcv_processTuples(PGresult *pgres, WalRcvExecResult *walres, const int nRetTypes, const Oid *retTypes)
#define ereport(elevel, rest)
Definition: elog.h:141
void * palloc0(Size size)
Definition: mcxt.c:980
Oid MyDatabaseId
Definition: globals.c:85
static PGresult * libpqrcv_PQexec(PGconn *streamConn, const char *query)
#define InvalidOid
Definition: postgres_ext.h:36
void PQclear(PGresult *res)
Definition: fe-exec.c:694
WalRcvExecStatus status
Definition: walreceiver.h:202
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define _(x)
Definition: elog.c:87

◆ libpqrcv_get_backend_pid()

static pid_t libpqrcv_get_backend_pid ( WalReceiverConn conn)
static

Definition at line 871 of file libpqwalreceiver.c.

References PQbackendPID(), and WalReceiverConn::streamConn.

872 {
873  return PQbackendPID(conn->streamConn);
874 }
int PQbackendPID(const PGconn *conn)
Definition: fe-connect.c:6710

◆ libpqrcv_get_conninfo()

static char * libpqrcv_get_conninfo ( WalReceiverConn conn)
static

Definition at line 244 of file libpqwalreceiver.c.

References _, appendPQExpBuffer(), Assert, buf, PQExpBufferData::data, _PQconninfoOption::dispchar, ereport, errmsg(), ERROR, initPQExpBuffer(), _PQconninfoOption::keyword, PQExpBufferData::len, PQconninfo(), PQconninfoFree(), PQExpBufferDataBroken, pstrdup(), WalReceiverConn::streamConn, termPQExpBuffer(), and _PQconninfoOption::val.

245 {
246  PQconninfoOption *conn_opts;
247  PQconninfoOption *conn_opt;
249  char *retval;
250 
251  Assert(conn->streamConn != NULL);
252 
253  initPQExpBuffer(&buf);
254  conn_opts = PQconninfo(conn->streamConn);
255 
256  if (conn_opts == NULL)
257  ereport(ERROR,
258  (errmsg("could not parse connection string: %s",
259  _("out of memory"))));
260 
261  /* build a clean connection string from pieces */
262  for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
263  {
264  bool obfuscate;
265 
266  /* Skip debug and empty options */
267  if (strchr(conn_opt->dispchar, 'D') ||
268  conn_opt->val == NULL ||
269  conn_opt->val[0] == '\0')
270  continue;
271 
272  /* Obfuscate security-sensitive options */
273  obfuscate = strchr(conn_opt->dispchar, '*') != NULL;
274 
275  appendPQExpBuffer(&buf, "%s%s=%s",
276  buf.len == 0 ? "" : " ",
277  conn_opt->keyword,
278  obfuscate ? "********" : conn_opt->val);
279  }
280 
281  PQconninfoFree(conn_opts);
282 
283  retval = PQExpBufferDataBroken(buf) ? NULL : pstrdup(buf.data);
284  termPQExpBuffer(&buf);
285  return retval;
286 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define ERROR
Definition: elog.h:43
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
static char * buf
Definition: pg_test_fsync.c:67
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6516
PQconninfoOption * PQconninfo(PGconn *conn)
Definition: fe-connect.c:6475
#define ereport(elevel, rest)
Definition: elog.h:141
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define Assert(condition)
Definition: c.h:738
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define _(x)
Definition: elog.c:87
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92

◆ libpqrcv_get_senderinfo()

static void libpqrcv_get_senderinfo ( WalReceiverConn conn,
char **  sender_host,
int *  sender_port 
)
static

Definition at line 292 of file libpqwalreceiver.c.

References Assert, PQhost(), PQport(), pstrdup(), and WalReceiverConn::streamConn.

294 {
295  char *ret = NULL;
296 
297  *sender_host = NULL;
298  *sender_port = 0;
299 
300  Assert(conn->streamConn != NULL);
301 
302  ret = PQhost(conn->streamConn);
303  if (ret && strlen(ret) != 0)
304  *sender_host = pstrdup(ret);
305 
306  ret = PQport(conn->streamConn);
307  if (ret && strlen(ret) != 0)
308  *sender_port = atoi(ret);
309 }
char * pstrdup(const char *in)
Definition: mcxt.c:1186
char * PQport(const PGconn *conn)
Definition: fe-connect.c:6603
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:6567
#define Assert(condition)
Definition: c.h:738

◆ libpqrcv_identify_system()

static char * libpqrcv_identify_system ( WalReceiverConn conn,
TimeLineID primary_tli 
)
static

Definition at line 316 of file libpqwalreceiver.c.

References ereport, errdetail(), errmsg(), ERROR, libpqrcv_PQexec(), pchomp(), pg_strtoint32(), PGRES_TUPLES_OK, PQclear(), PQerrorMessage(), PQgetvalue(), PQnfields(), PQntuples(), PQresultStatus(), pstrdup(), and WalReceiverConn::streamConn.

317 {
318  PGresult *res;
319  char *primary_sysid;
320 
321  /*
322  * Get the system identifier and timeline ID as a DataRow message from the
323  * primary server.
324  */
325  res = libpqrcv_PQexec(conn->streamConn, "IDENTIFY_SYSTEM");
326  if (PQresultStatus(res) != PGRES_TUPLES_OK)
327  {
328  PQclear(res);
329  ereport(ERROR,
330  (errmsg("could not receive database system identifier and timeline ID from "
331  "the primary server: %s",
332  pchomp(PQerrorMessage(conn->streamConn)))));
333  }
334  if (PQnfields(res) < 3 || PQntuples(res) != 1)
335  {
336  int ntuples = PQntuples(res);
337  int nfields = PQnfields(res);
338 
339  PQclear(res);
340  ereport(ERROR,
341  (errmsg("invalid response from primary server"),
342  errdetail("Could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields.",
343  ntuples, nfields, 3, 1)));
344  }
345  primary_sysid = pstrdup(PQgetvalue(res, 0, 0));
346  *primary_tli = pg_strtoint32(PQgetvalue(res, 0, 1));
347  PQclear(res);
348 
349  return primary_sysid;
350 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2777
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6684
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3163
char * pstrdup(const char *in)
Definition: mcxt.c:1186
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2769
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
char * pchomp(const char *in)
Definition: mcxt.c:1214
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:955
#define ereport(elevel, rest)
Definition: elog.h:141
static PGresult * libpqrcv_PQexec(PGconn *streamConn, const char *query)
void PQclear(PGresult *res)
Definition: fe-exec.c:694
int32 pg_strtoint32(const char *s)
Definition: numutils.c:261
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ libpqrcv_PQexec()

static PGresult * libpqrcv_PQexec ( PGconn streamConn,
const char *  query 
)
static

Definition at line 585 of file libpqwalreceiver.c.

References CONNECTION_BAD, libpqrcv_PQgetResult(), PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PQclear(), PQresultStatus(), PQsendQuery(), and PQstatus().

Referenced by libpqrcv_create_slot(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_readtimelinehistoryfile(), and libpqrcv_startstreaming().

586 {
587  PGresult *lastResult = NULL;
588 
589  /*
590  * PQexec() silently discards any prior query results on the connection.
591  * This is not required for this function as it's expected that the caller
592  * (which is this library in all cases) will behave correctly and we don't
593  * have to be backwards compatible with old libpq.
594  */
595 
596  /*
597  * Submit the query. Since we don't use non-blocking mode, this could
598  * theoretically block. In practice, since we don't send very long query
599  * strings, the risk seems negligible.
600  */
601  if (!PQsendQuery(streamConn, query))
602  return NULL;
603 
604  for (;;)
605  {
606  /* Wait for, and collect, the next PGresult. */
607  PGresult *result;
608 
609  result = libpqrcv_PQgetResult(streamConn);
610  if (result == NULL)
611  break; /* query is complete, or failure */
612 
613  /*
614  * Emulate PQexec()'s behavior of returning the last result when there
615  * are many. We are fine with returning just last error message.
616  */
617  PQclear(lastResult);
618  lastResult = result;
619 
620  if (PQresultStatus(lastResult) == PGRES_COPY_IN ||
621  PQresultStatus(lastResult) == PGRES_COPY_OUT ||
622  PQresultStatus(lastResult) == PGRES_COPY_BOTH ||
623  PQstatus(streamConn) == CONNECTION_BAD)
624  break;
625  }
626 
627  return lastResult;
628 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
static PGresult * libpqrcv_PQgetResult(PGconn *streamConn)
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1234
void PQclear(PGresult *res)
Definition: fe-exec.c:694
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6631

◆ libpqrcv_PQgetResult()

static PGresult * libpqrcv_PQgetResult ( PGconn streamConn)
static

Definition at line 634 of file libpqwalreceiver.c.

References MyLatch, PQconsumeInput(), PQgetResult(), PQisBusy(), PQsocket(), ProcessWalRcvInterrupts(), ResetLatch(), WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE, WaitLatchOrSocket(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_SOCKET_READABLE.

Referenced by libpqrcv_endstreaming(), libpqrcv_PQexec(), and libpqrcv_receive().

635 {
636  /*
637  * Collect data until PQgetResult is ready to get the result without
638  * blocking.
639  */
640  while (PQisBusy(streamConn))
641  {
642  int rc;
643 
644  /*
645  * We don't need to break down the sleep into smaller increments,
646  * since we'll get interrupted by signals and can handle any
647  * interrupts here.
648  */
651  WL_LATCH_SET,
652  PQsocket(streamConn),
653  0,
655 
656  /* Interrupted? */
657  if (rc & WL_LATCH_SET)
658  {
661  }
662 
663  /* Consume whatever data is available from the socket */
664  if (PQconsumeInput(streamConn) == 0)
665  {
666  /* trouble; return NULL */
667  return NULL;
668  }
669  }
670 
671  /* Now we can collect and return the next PGresult */
672  return PQgetResult(streamConn);
673 }
void ProcessWalRcvInterrupts(void)
Definition: walreceiver.c:146
#define WL_SOCKET_READABLE
Definition: latch.h:125
void ResetLatch(Latch *latch)
Definition: latch.c:531
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:381
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1704
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1754
struct Latch * MyLatch
Definition: globals.c:54
#define WL_LATCH_SET
Definition: latch.h:124
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:6702
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1778
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

◆ libpqrcv_processTuples()

static void libpqrcv_processTuples ( PGresult pgres,
WalRcvExecResult walres,
const int  nRetTypes,
const Oid retTypes 
)
static

Definition at line 880 of file libpqwalreceiver.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, BuildTupleFromCStrings(), CreateTemplateTupleDesc(), CurrentMemoryContext, ereport, errdetail(), errmsg(), ERROR, MaxTupleAttributeNumber, MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), PQfname(), PQgetisnull(), PQgetvalue(), PQnfields(), PQntuples(), ProcessWalRcvInterrupts(), WalRcvExecResult::tupledesc, TupleDescGetAttInMetadata(), TupleDescInitEntry(), WalRcvExecResult::tuplestore, tuplestore_begin_heap(), tuplestore_puttuple(), and work_mem.

Referenced by libpqrcv_exec().

882 {
883  int tupn;
884  int coln;
885  int nfields = PQnfields(pgres);
886  HeapTuple tuple;
887  AttInMetadata *attinmeta;
888  MemoryContext rowcontext;
889  MemoryContext oldcontext;
890 
891  /* Make sure we got expected number of fields. */
892  if (nfields != nRetTypes)
893  ereport(ERROR,
894  (errmsg("invalid query response"),
895  errdetail("Expected %d fields, got %d fields.",
896  nRetTypes, nfields)));
897 
898  walres->tuplestore = tuplestore_begin_heap(true, false, work_mem);
899 
900  /* Create tuple descriptor corresponding to expected result. */
901  walres->tupledesc = CreateTemplateTupleDesc(nRetTypes);
902  for (coln = 0; coln < nRetTypes; coln++)
903  TupleDescInitEntry(walres->tupledesc, (AttrNumber) coln + 1,
904  PQfname(pgres, coln), retTypes[coln], -1, 0);
905  attinmeta = TupleDescGetAttInMetadata(walres->tupledesc);
906 
907  /* No point in doing more here if there were no tuples returned. */
908  if (PQntuples(pgres) == 0)
909  return;
910 
911  /* Create temporary context for local allocations. */
913  "libpqrcv query result context",
915 
916  /* Process returned rows. */
917  for (tupn = 0; tupn < PQntuples(pgres); tupn++)
918  {
919  char *cstrs[MaxTupleAttributeNumber];
920 
922 
923  /* Do the allocations in temporary context. */
924  oldcontext = MemoryContextSwitchTo(rowcontext);
925 
926  /*
927  * Fill cstrs with null-terminated strings of column values.
928  */
929  for (coln = 0; coln < nfields; coln++)
930  {
931  if (PQgetisnull(pgres, tupn, coln))
932  cstrs[coln] = NULL;
933  else
934  cstrs[coln] = PQgetvalue(pgres, tupn, coln);
935  }
936 
937  /* Convert row to a tuple, and add it to the tuplestore */
938  tuple = BuildTupleFromCStrings(attinmeta, cstrs);
939  tuplestore_puttuple(walres->tuplestore, tuple);
940 
941  /* Clean up */
942  MemoryContextSwitchTo(oldcontext);
943  MemoryContextReset(rowcontext);
944  }
945 
946  MemoryContextDelete(rowcontext);
947 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2777
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3163
#define MaxTupleAttributeNumber
Definition: htup_details.h:33
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:44
char * PQfname(const PGresult *res, int field_num)
Definition: fe-exec.c:2855
void ProcessWalRcvInterrupts(void)
Definition: walreceiver.c:146
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:136
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2769
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2116
TupleDesc tupledesc
Definition: walreceiver.h:205
#define ERROR
Definition: elog.h:43
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:730
int errdetail(const char *fmt,...)
Definition: elog.c:955
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:603
#define ereport(elevel, rest)
Definition: elog.h:141
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2067
int work_mem
Definition: globals.c:121
Tuplestorestate * tuplestore
Definition: walreceiver.h:204
int errmsg(const char *fmt,...)
Definition: elog.c:822
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3188
int16 AttrNumber
Definition: attnum.h:21

◆ libpqrcv_readtimelinehistoryfile()

static void libpqrcv_readtimelinehistoryfile ( WalReceiverConn conn,
TimeLineID  tli,
char **  filename,
char **  content,
int *  len 
)
static

Definition at line 530 of file libpqwalreceiver.c.

References Assert, ereport, errdetail(), errmsg(), ERROR, libpqrcv_PQexec(), WalReceiverConn::logical, palloc(), pchomp(), PGRES_TUPLES_OK, PQclear(), PQerrorMessage(), PQgetlength(), PQgetvalue(), PQnfields(), PQntuples(), PQresultStatus(), pstrdup(), snprintf, and WalReceiverConn::streamConn.

533 {
534  PGresult *res;
535  char cmd[64];
536 
537  Assert(!conn->logical);
538 
539  /*
540  * Request the primary to send over the history file for given timeline.
541  */
542  snprintf(cmd, sizeof(cmd), "TIMELINE_HISTORY %u", tli);
543  res = libpqrcv_PQexec(conn->streamConn, cmd);
544  if (PQresultStatus(res) != PGRES_TUPLES_OK)
545  {
546  PQclear(res);
547  ereport(ERROR,
548  (errmsg("could not receive timeline history file from "
549  "the primary server: %s",
550  pchomp(PQerrorMessage(conn->streamConn)))));
551  }
552  if (PQnfields(res) != 2 || PQntuples(res) != 1)
553  {
554  int ntuples = PQntuples(res);
555  int nfields = PQnfields(res);
556 
557  PQclear(res);
558  ereport(ERROR,
559  (errmsg("invalid response from primary server"),
560  errdetail("Expected 1 tuple with 2 fields, got %d tuples with %d fields.",
561  ntuples, nfields)));
562  }
563  *filename = pstrdup(PQgetvalue(res, 0, 0));
564 
565  *len = PQgetlength(res, 0, 1);
566  *content = palloc(*len);
567  memcpy(*content, PQgetvalue(res, 0, 1), *len);
568  PQclear(res);
569 }
int PQgetlength(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3174
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2777
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6684
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3163
char * pstrdup(const char *in)
Definition: mcxt.c:1186
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2769
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
char * pchomp(const char *in)
Definition: mcxt.c:1214
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:955
#define ereport(elevel, rest)
Definition: elog.h:141
static PGresult * libpqrcv_PQexec(PGconn *streamConn, const char *query)
void PQclear(PGresult *res)
Definition: fe-exec.c:694
#define Assert(condition)
Definition: c.h:738
static char * filename
Definition: pg_dumpall.c:90
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define snprintf
Definition: port.h:192

◆ libpqrcv_receive()

static int libpqrcv_receive ( WalReceiverConn conn,
char **  buffer,
pgsocket wait_fd 
)
static

Definition at line 704 of file libpqwalreceiver.c.

References CONNECTION_BAD, ereport, errmsg(), ERROR, libpqrcv_PQgetResult(), pchomp(), PGRES_COMMAND_OK, PGRES_COPY_IN, PQclear(), PQconsumeInput(), PQerrorMessage(), PQfreemem(), PQgetCopyData(), PQresultStatus(), PQsocket(), PQstatus(), WalReceiverConn::recvBuf, and WalReceiverConn::streamConn.

706 {
707  int rawlen;
708 
709  if (conn->recvBuf != NULL)
710  PQfreemem(conn->recvBuf);
711  conn->recvBuf = NULL;
712 
713  /* Try to receive a CopyData message */
714  rawlen = PQgetCopyData(conn->streamConn, &conn->recvBuf, 1);
715  if (rawlen == 0)
716  {
717  /* Try consuming some data. */
718  if (PQconsumeInput(conn->streamConn) == 0)
719  ereport(ERROR,
720  (errmsg("could not receive data from WAL stream: %s",
721  pchomp(PQerrorMessage(conn->streamConn)))));
722 
723  /* Now that we've consumed some input, try again */
724  rawlen = PQgetCopyData(conn->streamConn, &conn->recvBuf, 1);
725  if (rawlen == 0)
726  {
727  /* Tell caller to try again when our socket is ready. */
728  *wait_fd = PQsocket(conn->streamConn);
729  return 0;
730  }
731  }
732  if (rawlen == -1) /* end-of-streaming or error */
733  {
734  PGresult *res;
735 
736  res = libpqrcv_PQgetResult(conn->streamConn);
737  if (PQresultStatus(res) == PGRES_COMMAND_OK)
738  {
739  PQclear(res);
740 
741  /* Verify that there are no more results. */
742  res = libpqrcv_PQgetResult(conn->streamConn);
743  if (res != NULL)
744  {
745  PQclear(res);
746 
747  /*
748  * If the other side closed the connection orderly (otherwise
749  * we'd seen an error, or PGRES_COPY_IN) don't report an error
750  * here, but let callers deal with it.
751  */
752  if (PQstatus(conn->streamConn) == CONNECTION_BAD)
753  return -1;
754 
755  ereport(ERROR,
756  (errmsg("unexpected result after CommandComplete: %s",
757  PQerrorMessage(conn->streamConn))));
758  }
759 
760  return -1;
761  }
762  else if (PQresultStatus(res) == PGRES_COPY_IN)
763  {
764  PQclear(res);
765  return -1;
766  }
767  else
768  {
769  PQclear(res);
770  ereport(ERROR,
771  (errmsg("could not receive data from WAL stream: %s",
772  pchomp(PQerrorMessage(conn->streamConn)))));
773  }
774  }
775  if (rawlen < -1)
776  ereport(ERROR,
777  (errmsg("could not receive data from WAL stream: %s",
778  pchomp(PQerrorMessage(conn->streamConn)))));
779 
780  /* Return received messages to caller */
781  *buffer = conn->recvBuf;
782  return rawlen;
783 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6684
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
int PQgetCopyData(PGconn *conn, char **buffer, int async)
Definition: fe-exec.c:2473
static PGresult * libpqrcv_PQgetResult(PGconn *streamConn)
char * pchomp(const char *in)
Definition: mcxt.c:1214
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1704
void PQclear(PGresult *res)
Definition: fe-exec.c:694
int errmsg(const char *fmt,...)
Definition: elog.c:822
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6631
void PQfreemem(void *ptr)
Definition: fe-exec.c:3296
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:6702

◆ libpqrcv_send()

static void libpqrcv_send ( WalReceiverConn conn,
const char *  buffer,
int  nbytes 
)
static

Definition at line 791 of file libpqwalreceiver.c.

References ereport, errmsg(), ERROR, pchomp(), PQerrorMessage(), PQflush(), PQputCopyData(), and WalReceiverConn::streamConn.

792 {
793  if (PQputCopyData(conn->streamConn, buffer, nbytes) <= 0 ||
794  PQflush(conn->streamConn))
795  ereport(ERROR,
796  (errmsg("could not send data to WAL stream: %s",
797  pchomp(PQerrorMessage(conn->streamConn)))));
798 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2317
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6684
char * pchomp(const char *in)
Definition: mcxt.c:1214
#define ERROR
Definition: elog.h:43
int PQflush(PGconn *conn)
Definition: fe-exec.c:3283
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ libpqrcv_server_version()

static int libpqrcv_server_version ( WalReceiverConn conn)
static

Definition at line 356 of file libpqwalreceiver.c.

References PQserverVersion(), and WalReceiverConn::streamConn.

357 {
358  return PQserverVersion(conn->streamConn);
359 }
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6674

◆ libpqrcv_startstreaming()

static bool libpqrcv_startstreaming ( WalReceiverConn conn,
const WalRcvStreamOptions options 
)
static

Definition at line 372 of file libpqwalreceiver.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert, StringInfoData::data, ereport, errmsg(), ERROR, initStringInfo(), libpqrcv_PQexec(), WalReceiverConn::logical, WalRcvStreamOptions::logical, pchomp(), pfree(), PGRES_COMMAND_OK, PGRES_COPY_BOTH, WalRcvStreamOptions::physical, PQclear(), PQerrorMessage(), PQescapeLiteral(), PQfreemem(), PQresultStatus(), WalRcvStreamOptions::proto, WalRcvStreamOptions::slotname, WalRcvStreamOptions::startpoint, WalReceiverConn::streamConn, and stringlist_to_identifierstr().

374 {
375  StringInfoData cmd;
376  PGresult *res;
377 
378  Assert(options->logical == conn->logical);
379  Assert(options->slotname || !options->logical);
380 
381  initStringInfo(&cmd);
382 
383  /* Build the command. */
384  appendStringInfoString(&cmd, "START_REPLICATION");
385  if (options->slotname != NULL)
386  appendStringInfo(&cmd, " SLOT \"%s\"",
387  options->slotname);
388 
389  if (options->logical)
390  appendStringInfoString(&cmd, " LOGICAL");
391 
392  appendStringInfo(&cmd, " %X/%X",
393  (uint32) (options->startpoint >> 32),
394  (uint32) options->startpoint);
395 
396  /*
397  * Additional options are different depending on if we are doing logical
398  * or physical replication.
399  */
400  if (options->logical)
401  {
402  char *pubnames_str;
403  List *pubnames;
404  char *pubnames_literal;
405 
406  appendStringInfoString(&cmd, " (");
407 
408  appendStringInfo(&cmd, "proto_version '%u'",
409  options->proto.logical.proto_version);
410 
411  pubnames = options->proto.logical.publication_names;
412  pubnames_str = stringlist_to_identifierstr(conn->streamConn, pubnames);
413  if (!pubnames_str)
414  ereport(ERROR,
415  (errmsg("could not start WAL streaming: %s",
416  pchomp(PQerrorMessage(conn->streamConn)))));
417  pubnames_literal = PQescapeLiteral(conn->streamConn, pubnames_str,
418  strlen(pubnames_str));
419  if (!pubnames_literal)
420  ereport(ERROR,
421  (errmsg("could not start WAL streaming: %s",
422  pchomp(PQerrorMessage(conn->streamConn)))));
423  appendStringInfo(&cmd, ", publication_names %s", pubnames_literal);
424  PQfreemem(pubnames_literal);
425  pfree(pubnames_str);
426 
427  appendStringInfoChar(&cmd, ')');
428  }
429  else
430  appendStringInfo(&cmd, " TIMELINE %u",
431  options->proto.physical.startpointTLI);
432 
433  /* Start streaming. */
434  res = libpqrcv_PQexec(conn->streamConn, cmd.data);
435  pfree(cmd.data);
436 
437  if (PQresultStatus(res) == PGRES_COMMAND_OK)
438  {
439  PQclear(res);
440  return false;
441  }
442  else if (PQresultStatus(res) != PGRES_COPY_BOTH)
443  {
444  PQclear(res);
445  ereport(ERROR,
446  (errmsg("could not start WAL streaming: %s",
447  pchomp(PQerrorMessage(conn->streamConn)))));
448  }
449  PQclear(res);
450  return true;
451 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6684
union WalRcvStreamOptions::@106 proto
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
char * pchomp(const char *in)
Definition: mcxt.c:1214
void pfree(void *pointer)
Definition: mcxt.c:1056
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
XLogRecPtr startpoint
Definition: walreceiver.h:160
unsigned int uint32
Definition: c.h:367
struct WalRcvStreamOptions::@106::@107 physical
#define ereport(elevel, rest)
Definition: elog.h:141
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:3564
static PGresult * libpqrcv_PQexec(PGconn *streamConn, const char *query)
void PQclear(PGresult *res)
Definition: fe-exec.c:694
#define Assert(condition)
Definition: c.h:738
static char * stringlist_to_identifierstr(PGconn *conn, List *strings)
int errmsg(const char *fmt,...)
Definition: elog.c:822
Definition: pg_list.h:50
void PQfreemem(void *ptr)
Definition: fe-exec.c:3296

◆ stringlist_to_identifierstr()

static char * stringlist_to_identifierstr ( PGconn conn,
List strings 
)
static

Definition at line 1020 of file libpqwalreceiver.c.

References appendStringInfoChar(), appendStringInfoString(), StringInfoData::data, free, initStringInfo(), lfirst, PQescapeIdentifier(), PQfreemem(), strVal, and val.

Referenced by libpqrcv_startstreaming().

1021 {
1022  ListCell *lc;
1023  StringInfoData res;
1024  bool first = true;
1025 
1026  initStringInfo(&res);
1027 
1028  foreach(lc, strings)
1029  {
1030  char *val = strVal(lfirst(lc));
1031  char *val_escaped;
1032 
1033  if (first)
1034  first = false;
1035  else
1036  appendStringInfoChar(&res, ',');
1037 
1038  val_escaped = PQescapeIdentifier(conn, val, strlen(val));
1039  if (!val_escaped)
1040  {
1041  free(res.data);
1042  return NULL;
1043  }
1044  appendStringInfoString(&res, val_escaped);
1045  PQfreemem(val_escaped);
1046  }
1047 
1048  return res.data;
1049 }
#define strVal(v)
Definition: value.h:54
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:3570
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define free(a)
Definition: header.h:65
#define lfirst(lc)
Definition: pg_list.h:190
void PQfreemem(void *ptr)
Definition: fe-exec.c:3296
long val
Definition: informix.c:664

Variable Documentation

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 36 of file libpqwalreceiver.c.

◆ PQWalReceiverFunctions

WalReceiverFunctionsType PQWalReceiverFunctions
static
Initial value:
= {
}
static bool libpqrcv_startstreaming(WalReceiverConn *conn, const WalRcvStreamOptions *options)
static void libpqrcv_check_conninfo(const char *conninfo)
static int libpqrcv_receive(WalReceiverConn *conn, char **buffer, pgsocket *wait_fd)
static void libpqrcv_readtimelinehistoryfile(WalReceiverConn *conn, TimeLineID tli, char **filename, char **content, int *len)
static char * libpqrcv_identify_system(WalReceiverConn *conn, TimeLineID *primary_tli)
static void libpqrcv_endstreaming(WalReceiverConn *conn, TimeLineID *next_tli)
static WalRcvExecResult * libpqrcv_exec(WalReceiverConn *conn, const char *query, const int nRetTypes, const Oid *retTypes)
static pid_t libpqrcv_get_backend_pid(WalReceiverConn *conn)
static char * libpqrcv_create_slot(WalReceiverConn *conn, const char *slotname, bool temporary, CRSSnapshotAction snapshot_action, XLogRecPtr *lsn)
static void libpqrcv_disconnect(WalReceiverConn *conn)
static int libpqrcv_server_version(WalReceiverConn *conn)
static WalReceiverConn * libpqrcv_connect(const char *conninfo, bool logical, const char *appname, char **err)
static char * libpqrcv_get_conninfo(WalReceiverConn *conn)
static void libpqrcv_send(WalReceiverConn *conn, const char *buffer, int nbytes)
static void libpqrcv_get_senderinfo(WalReceiverConn *conn, char **sender_host, int *sender_port)

Definition at line 84 of file libpqwalreceiver.c.

Referenced by _PG_init().