PostgreSQL Source Code git master
libpqwalreceiver.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <sys/time.h>
#include "common/connect.h"
#include "funcapi.h"
#include "libpq-fe.h"
#include "libpq/libpq-be-fe-helpers.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "pqexpbuffer.h"
#include "replication/walreceiver.h"
#include "storage/latch.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

 PG_MODULE_MAGIC_EXT (.name="libpqwalreceiver",.version=PG_VERSION)
 
static WalReceiverConnlibpqrcv_connect (const char *conninfo, bool replication, bool logical, bool must_use_password, const char *appname, char **err)
 
static void libpqrcv_check_conninfo (const char *conninfo, bool must_use_password)
 
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 char * libpqrcv_get_dbname_from_conninfo (const char *connInfo)
 
static char * libpqrcv_get_option_from_conninfo (const char *connInfo, const char *keyword)
 
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, bool two_phase, bool failover, CRSSnapshotAction snapshot_action, XLogRecPtr *lsn)
 
static void libpqrcv_alter_slot (WalReceiverConn *conn, const char *slotname, const bool *failover, const bool *two_phase)
 
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 char * stringlist_to_identifierstr (PGconn *conn, List *strings)
 
void _PG_init (void)
 
static void libpqrcv_processTuples (PGresult *pgres, WalRcvExecResult *walres, const int nRetTypes, const Oid *retTypes)
 

Variables

static WalReceiverFunctionsType PQWalReceiverFunctions
 

Function Documentation

◆ _PG_init()

void _PG_init ( void  )

Definition at line 125 of file libpqwalreceiver.c.

126{
127 if (WalReceiverFunctions != NULL)
128 elog(ERROR, "libpqwalreceiver already loaded");
130}
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
static WalReceiverFunctionsType PQWalReceiverFunctions
WalReceiverFunctionsType * WalReceiverFunctions
Definition: walreceiver.c:95

References elog, ERROR, PQWalReceiverFunctions, and WalReceiverFunctions.

◆ libpqrcv_alter_slot()

static void libpqrcv_alter_slot ( WalReceiverConn conn,
const char *  slotname,
const bool *  failover,
const bool *  two_phase 
)
static

Definition at line 1001 of file libpqwalreceiver.c.

1003{
1004 StringInfoData cmd;
1005 PGresult *res;
1006
1007 initStringInfo(&cmd);
1008 appendStringInfo(&cmd, "ALTER_REPLICATION_SLOT %s ( ",
1009 quote_identifier(slotname));
1010
1011 if (failover)
1012 appendStringInfo(&cmd, "FAILOVER %s",
1013 *failover ? "true" : "false");
1014
1015 if (failover && two_phase)
1016 appendStringInfoString(&cmd, ", ");
1017
1018 if (two_phase)
1019 appendStringInfo(&cmd, "TWO_PHASE %s",
1020 *two_phase ? "true" : "false");
1021
1022 appendStringInfoString(&cmd, " );");
1023
1024 res = libpqsrv_exec(conn->streamConn, cmd.data,
1025 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
1026 pfree(cmd.data);
1027
1028 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1029 ereport(ERROR,
1030 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1031 errmsg("could not alter replication slot \"%s\": %s",
1032 slotname, pchomp(PQerrorMessage(conn->streamConn)))));
1033
1034 PQclear(res);
1035}
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define ereport(elevel,...)
Definition: elog.h:150
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7704
static PGresult * libpqsrv_exec(PGconn *conn, const char *query, uint32 wait_event_info)
#define PQclear
Definition: libpq-be-fe.h:245
#define PQresultStatus
Definition: libpq-be-fe.h:247
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:125
void pfree(void *pointer)
Definition: mcxt.c:1616
char * pchomp(const char *in)
Definition: mcxt.c:1809
static bool two_phase
static bool failover
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:13062
PGconn * conn
Definition: streamutil.c:52
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97

References appendStringInfo(), appendStringInfoString(), conn, StringInfoData::data, ereport, errcode(), errmsg(), ERROR, failover, initStringInfo(), libpqsrv_exec(), pchomp(), pfree(), PGRES_COMMAND_OK, PQclear, PQerrorMessage(), PQresultStatus, quote_identifier(), and two_phase.

◆ libpqrcv_check_conninfo()

static void libpqrcv_check_conninfo ( const char *  conninfo,
bool  must_use_password 
)
static

Definition at line 296 of file libpqwalreceiver.c.

297{
298 PQconninfoOption *opts = NULL;
299 PQconninfoOption *opt;
300 char *err = NULL;
301
302 opts = PQconninfoParse(conninfo, &err);
303 if (opts == NULL)
304 {
305 /* The error string is malloc'd, so we must free it explicitly */
306 char *errcopy = err ? pstrdup(err) : "out of memory";
307
308 PQfreemem(err);
310 (errcode(ERRCODE_SYNTAX_ERROR),
311 errmsg("invalid connection string syntax: %s", errcopy)));
312 }
313
314 if (must_use_password)
315 {
316 bool uses_password = false;
317
318 for (opt = opts; opt->keyword != NULL; ++opt)
319 {
320 /* Ignore connection options that are not present. */
321 if (opt->val == NULL)
322 continue;
323
324 if (strcmp(opt->keyword, "password") == 0 && opt->val[0] != '\0')
325 {
326 uses_password = true;
327 break;
328 }
329 }
330
331 if (!uses_password)
332 {
333 /* malloc'd, so we must free it explicitly */
335
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
344}
int errdetail(const char *fmt,...)
Definition: elog.c:1216
void err(int eval, const char *fmt,...)
Definition: err.c:43
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:7525
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:6241
void PQfreemem(void *ptr)
Definition: fe-exec.c:4049
char * pstrdup(const char *in)
Definition: mcxt.c:1781
static AmcheckOptions opts
Definition: pg_amcheck.c:112

References ereport, err(), errcode(), errdetail(), errmsg(), ERROR, _PQconninfoOption::keyword, opts, PQconninfoFree(), PQconninfoParse(), PQfreemem(), pstrdup(), and _PQconninfoOption::val.

Referenced by libpqrcv_connect().

◆ libpqrcv_connect()

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

Definition at line 148 of file libpqwalreceiver.c.

150{
152 const char *keys[6];
153 const char *vals[6];
154 int i = 0;
155 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 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 keys[i] = "dbname";
171 vals[i] = conninfo;
172
173 /* We can not have logical without replication */
174 Assert(replication || !logical);
175
176 if (replication)
177 {
178 keys[++i] = "replication";
179 vals[i] = logical ? "database" : "true";
180
181 if (logical)
182 {
183 char *opt = NULL;
184
185 /* Tell the publisher to translate to our encoding */
186 keys[++i] = "client_encoding";
187 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 opt = libpqrcv_get_option_from_conninfo(conninfo, "options");
198 options_val = psprintf("%s -c datestyle=ISO -c intervalstyle=postgres -c extra_float_digits=3",
199 (opt == NULL) ? "" : opt);
200 keys[++i] = "options";
201 vals[i] = options_val;
202 if (opt != NULL)
203 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 keys[++i] = "dbname";
212 vals[i] = "replication";
213 }
214 }
215
216 keys[++i] = "fallback_application_name";
217 vals[i] = appname;
218
219 keys[++i] = NULL;
220 vals[i] = NULL;
221
222 Assert(i < lengthof(keys));
223
225 conn->streamConn =
226 libpqsrv_connect_params(keys, vals,
227 /* expand_dbname = */ true,
228 WAIT_EVENT_LIBPQWALRECEIVER_CONNECT);
229
230 if (options_val != NULL)
231 pfree(options_val);
232
233 if (PQstatus(conn->streamConn) != CONNECTION_OK)
234 goto bad_connection_errmsg;
235
236 if (must_use_password && !PQconnectionUsedPassword(conn->streamConn))
237 {
238 libpqsrv_disconnect(conn->streamConn);
239 pfree(conn);
240
242 (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
243 errmsg("password is required"),
244 errdetail("Non-superuser cannot connect if the server does not request a password."),
245 errhint("Target server's authentication method must be changed, or set password_required=false in the subscription parameters.")));
246 }
247
249 "received message via replication");
250
251 /*
252 * Set always-secure search path for the cases where the connection is
253 * used to run SQL queries, so malicious users can't get control.
254 */
255 if (!replication || logical)
256 {
257 PGresult *res;
258
259 res = libpqsrv_exec(conn->streamConn,
261 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
263 {
264 PQclear(res);
265 *err = psprintf(_("could not clear search path: %s"),
266 pchomp(PQerrorMessage(conn->streamConn)));
267 goto bad_connection;
268 }
269 PQclear(res);
270 }
271
272 conn->logical = logical;
273
274 return conn;
275
276 /* error path, using libpq's error message */
277bad_connection_errmsg:
278 *err = pchomp(PQerrorMessage(conn->streamConn));
279
280 /* error path, error already set */
281bad_connection:
282 libpqsrv_disconnect(conn->streamConn);
283 pfree(conn);
284 return NULL;
285}
#define lengthof(array)
Definition: c.h:809
#define ALWAYS_SECURE_SEARCH_PATH_SQL
Definition: connect.h:25
int errhint(const char *fmt,...)
Definition: elog.c:1330
#define _(x)
Definition: elog.c:91
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:7772
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7641
PQnoticeReceiver PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
Definition: fe-connect.c:7868
#define palloc0_object(type)
Definition: fe_memutils.h:75
Assert(PointerIsAligned(start, uint64))
int i
Definition: isn.c:77
static PGconn * libpqsrv_connect_params(const char *const *keywords, const char *const *values, int expand_dbname, uint32 wait_event_info)
static void libpqsrv_notice_receiver(void *arg, const PGresult *res)
static void libpqsrv_disconnect(PGconn *conn)
@ CONNECTION_OK
Definition: libpq-fe.h:84
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:128
static void libpqrcv_check_conninfo(const char *conninfo, bool must_use_password)
static char * libpqrcv_get_option_from_conninfo(const char *connInfo, const char *keyword)
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1270
char * psprintf(const char *fmt,...)
Definition: psprintf.c:43

References _, ALWAYS_SECURE_SEARCH_PATH_SQL, Assert(), conn, CONNECTION_OK, ereport, err(), errcode(), errdetail(), errhint(), errmsg(), ERROR, GetDatabaseEncodingName(), i, lengthof, libpqrcv_check_conninfo(), libpqrcv_get_option_from_conninfo(), libpqsrv_connect_params(), libpqsrv_disconnect(), libpqsrv_exec(), libpqsrv_notice_receiver(), palloc0_object, pchomp(), pfree(), PGRES_TUPLES_OK, PQclear, PQconnectionUsedPassword(), PQerrorMessage(), PQresultStatus, PQsetNoticeReceiver(), PQstatus(), and psprintf().

◆ libpqrcv_create_slot()

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

Definition at line 889 of file libpqwalreceiver.c.

892{
893 PGresult *res;
894 StringInfoData cmd;
895 char *snapshot;
896 int use_new_options_syntax;
897
898 use_new_options_syntax = (PQserverVersion(conn->streamConn) >= 150000);
899
900 initStringInfo(&cmd);
901
902 appendStringInfo(&cmd, "CREATE_REPLICATION_SLOT \"%s\"", slotname);
903
904 if (temporary)
905 appendStringInfoString(&cmd, " TEMPORARY");
906
907 if (conn->logical)
908 {
909 appendStringInfoString(&cmd, " LOGICAL pgoutput ");
910 if (use_new_options_syntax)
911 appendStringInfoChar(&cmd, '(');
912 if (two_phase)
913 {
914 appendStringInfoString(&cmd, "TWO_PHASE");
915 if (use_new_options_syntax)
916 appendStringInfoString(&cmd, ", ");
917 else
918 appendStringInfoChar(&cmd, ' ');
919 }
920
921 if (failover)
922 {
923 appendStringInfoString(&cmd, "FAILOVER");
924 if (use_new_options_syntax)
925 appendStringInfoString(&cmd, ", ");
926 else
927 appendStringInfoChar(&cmd, ' ');
928 }
929
930 if (use_new_options_syntax)
931 {
932 switch (snapshot_action)
933 {
935 appendStringInfoString(&cmd, "SNAPSHOT 'export'");
936 break;
938 appendStringInfoString(&cmd, "SNAPSHOT 'nothing'");
939 break;
940 case CRS_USE_SNAPSHOT:
941 appendStringInfoString(&cmd, "SNAPSHOT 'use'");
942 break;
943 }
944 }
945 else
946 {
947 switch (snapshot_action)
948 {
950 appendStringInfoString(&cmd, "EXPORT_SNAPSHOT");
951 break;
953 appendStringInfoString(&cmd, "NOEXPORT_SNAPSHOT");
954 break;
955 case CRS_USE_SNAPSHOT:
956 appendStringInfoString(&cmd, "USE_SNAPSHOT");
957 break;
958 }
959 }
960
961 if (use_new_options_syntax)
962 appendStringInfoChar(&cmd, ')');
963 }
964 else
965 {
966 if (use_new_options_syntax)
967 appendStringInfoString(&cmd, " PHYSICAL (RESERVE_WAL)");
968 else
969 appendStringInfoString(&cmd, " PHYSICAL RESERVE_WAL");
970 }
971
972 res = libpqsrv_exec(conn->streamConn,
973 cmd.data,
974 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
975 pfree(cmd.data);
976
979 (errcode(ERRCODE_PROTOCOL_VIOLATION),
980 errmsg("could not create replication slot \"%s\": %s",
981 slotname, pchomp(PQerrorMessage(conn->streamConn)))));
982
983 if (lsn)
985 CStringGetDatum(PQgetvalue(res, 0, 1))));
986
987 if (!PQgetisnull(res, 0, 2))
988 snapshot = pstrdup(PQgetvalue(res, 0, 2));
989 else
990 snapshot = NULL;
991
992 PQclear(res);
993
994 return snapshot;
995}
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7694
Datum DirectFunctionCall1Coll(PGFunction func, Oid collation, Datum arg1)
Definition: fmgr.c:793
#define PQgetvalue
Definition: libpq-be-fe.h:253
#define PQgetisnull
Definition: libpq-be-fe.h:255
Datum pg_lsn_in(PG_FUNCTION_ARGS)
Definition: pg_lsn.c:64
static XLogRecPtr DatumGetLSN(Datum X)
Definition: pg_lsn.h:25
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:380
#define InvalidOid
Definition: postgres_ext.h:37
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:242
@ CRS_USE_SNAPSHOT
Definition: walsender.h:24
@ CRS_NOEXPORT_SNAPSHOT
Definition: walsender.h:23
@ CRS_EXPORT_SNAPSHOT
Definition: walsender.h:22

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), conn, CRS_EXPORT_SNAPSHOT, CRS_NOEXPORT_SNAPSHOT, CRS_USE_SNAPSHOT, CStringGetDatum(), StringInfoData::data, DatumGetLSN(), DirectFunctionCall1Coll(), ereport, errcode(), errmsg(), ERROR, failover, initStringInfo(), InvalidOid, libpqsrv_exec(), pchomp(), pfree(), pg_lsn_in(), PGRES_TUPLES_OK, PQclear, PQerrorMessage(), PQgetisnull, PQgetvalue, PQresultStatus, PQserverVersion(), pstrdup(), and two_phase.

◆ libpqrcv_disconnect()

static void libpqrcv_disconnect ( WalReceiverConn conn)
static

Definition at line 760 of file libpqwalreceiver.c.

761{
762 libpqsrv_disconnect(conn->streamConn);
763 PQfreemem(conn->recvBuf);
764 pfree(conn);
765}

References conn, libpqsrv_disconnect(), pfree(), and PQfreemem().

◆ libpqrcv_endstreaming()

static void libpqrcv_endstreaming ( WalReceiverConn conn,
TimeLineID next_tli 
)
static

Definition at line 639 of file libpqwalreceiver.c.

640{
641 PGresult *res;
642
643 /*
644 * Send copy-end message. As in libpqsrv_exec, this could theoretically
645 * block, but the risk seems small.
646 */
647 if (PQputCopyEnd(conn->streamConn, NULL) <= 0 ||
648 PQflush(conn->streamConn))
650 (errcode(ERRCODE_CONNECTION_FAILURE),
651 errmsg("could not send end-of-streaming message to primary: %s",
652 pchomp(PQerrorMessage(conn->streamConn)))));
653
654 *next_tli = 0;
655
656 /*
657 * After COPY is finished, we should receive a result set indicating the
658 * next timeline's ID, or just CommandComplete if the server was shut
659 * down.
660 *
661 * If we had not yet received CopyDone from the backend, PGRES_COPY_OUT is
662 * also possible in case we aborted the copy in mid-stream.
663 */
664 res = libpqsrv_get_result(conn->streamConn,
665 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
667 {
668 /*
669 * Read the next timeline's ID. The server also sends the timeline's
670 * starting point, but it is ignored.
671 */
672 if (PQnfields(res) < 2 || PQntuples(res) != 1)
674 (errcode(ERRCODE_PROTOCOL_VIOLATION),
675 errmsg("unexpected result set after end-of-streaming")));
676 *next_tli = pg_strtoint32(PQgetvalue(res, 0, 0));
677 PQclear(res);
678
679 /* the result set should be followed by CommandComplete */
680 res = libpqsrv_get_result(conn->streamConn,
681 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
682 }
683 else if (PQresultStatus(res) == PGRES_COPY_OUT)
684 {
685 PQclear(res);
686
687 /* End the copy */
688 if (PQendcopy(conn->streamConn))
690 (errcode(ERRCODE_CONNECTION_FAILURE),
691 errmsg("error while shutting down streaming COPY: %s",
692 pchomp(PQerrorMessage(conn->streamConn)))));
693
694 /* CommandComplete should follow */
695 res = libpqsrv_get_result(conn->streamConn,
696 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
697 }
698
701 (errcode(ERRCODE_PROTOCOL_VIOLATION),
702 errmsg("error reading result of streaming command: %s",
703 pchomp(PQerrorMessage(conn->streamConn)))));
704 PQclear(res);
705
706 /* Verify that there are no more results */
707 res = libpqsrv_get_result(conn->streamConn,
708 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
709 if (res != NULL)
711 (errcode(ERRCODE_PROTOCOL_VIOLATION),
712 errmsg("unexpected result after CommandComplete: %s",
713 pchomp(PQerrorMessage(conn->streamConn)))));
714}
int PQflush(PGconn *conn)
Definition: fe-exec.c:4017
int PQendcopy(PGconn *conn)
Definition: fe-exec.c:2966
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2766
static PGresult * libpqsrv_get_result(PGconn *conn, uint32 wait_event_info)
#define PQnfields
Definition: libpq-be-fe.h:252
#define PQntuples
Definition: libpq-be-fe.h:251
@ PGRES_COPY_OUT
Definition: libpq-fe.h:131
int32 pg_strtoint32(const char *s)
Definition: numutils.c:383

References conn, ereport, errcode(), errmsg(), ERROR, libpqsrv_get_result(), pchomp(), pg_strtoint32(), PGRES_COMMAND_OK, PGRES_COPY_OUT, PGRES_TUPLES_OK, PQclear, PQendcopy(), PQerrorMessage(), PQflush(), PQgetvalue, PQnfields, PQntuples, PQputCopyEnd(), and PQresultStatus.

◆ libpqrcv_exec()

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

Definition at line 1126 of file libpqwalreceiver.c.

1128{
1129 PGresult *pgres = NULL;
1131 char *diag_sqlstate;
1132
1133 if (MyDatabaseId == InvalidOid)
1134 ereport(ERROR,
1135 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1136 errmsg("the query interface requires a database connection")));
1137
1138 pgres = libpqsrv_exec(conn->streamConn,
1139 query,
1140 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
1141
1142 switch (PQresultStatus(pgres))
1143 {
1144 case PGRES_TUPLES_OK:
1145 case PGRES_SINGLE_TUPLE:
1146 case PGRES_TUPLES_CHUNK:
1147 walres->status = WALRCV_OK_TUPLES;
1148 libpqrcv_processTuples(pgres, walres, nRetTypes, retTypes);
1149 break;
1150
1151 case PGRES_COPY_IN:
1152 walres->status = WALRCV_OK_COPY_IN;
1153 break;
1154
1155 case PGRES_COPY_OUT:
1156 walres->status = WALRCV_OK_COPY_OUT;
1157 break;
1158
1159 case PGRES_COPY_BOTH:
1160 walres->status = WALRCV_OK_COPY_BOTH;
1161 break;
1162
1163 case PGRES_COMMAND_OK:
1164 walres->status = WALRCV_OK_COMMAND;
1165 break;
1166
1167 /* Empty query is considered error. */
1168 case PGRES_EMPTY_QUERY:
1169 walres->status = WALRCV_ERROR;
1170 walres->err = _("empty query");
1171 break;
1172
1175 walres->status = WALRCV_ERROR;
1176 walres->err = _("unexpected pipeline mode");
1177 break;
1178
1180 case PGRES_FATAL_ERROR:
1181 case PGRES_BAD_RESPONSE:
1182 walres->status = WALRCV_ERROR;
1183 walres->err = pchomp(PQerrorMessage(conn->streamConn));
1184 diag_sqlstate = PQresultErrorField(pgres, PG_DIAG_SQLSTATE);
1185 if (diag_sqlstate)
1186 walres->sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
1187 diag_sqlstate[1],
1188 diag_sqlstate[2],
1189 diag_sqlstate[3],
1190 diag_sqlstate[4]);
1191 break;
1192 }
1193
1194 PQclear(pgres);
1195
1196 return walres;
1197}
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition: elog.h:56
Oid MyDatabaseId
Definition: globals.c:94
#define PQresultErrorField
Definition: libpq-be-fe.h:249
@ PGRES_COPY_IN
Definition: libpq-fe.h:132
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:137
@ PGRES_TUPLES_CHUNK
Definition: libpq-fe.h:142
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:136
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:138
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:124
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:139
@ PGRES_BAD_RESPONSE
Definition: libpq-fe.h:133
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:140
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:135
static void libpqrcv_processTuples(PGresult *pgres, WalRcvExecResult *walres, const int nRetTypes, const Oid *retTypes)
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
WalRcvExecStatus status
Definition: walreceiver.h:220
@ WALRCV_OK_COPY_IN
Definition: walreceiver.h:208
@ WALRCV_OK_COMMAND
Definition: walreceiver.h:205
@ WALRCV_ERROR
Definition: walreceiver.h:204
@ WALRCV_OK_TUPLES
Definition: walreceiver.h:207
@ WALRCV_OK_COPY_OUT
Definition: walreceiver.h:209
@ WALRCV_OK_COPY_BOTH
Definition: walreceiver.h:210

References _, conn, ereport, WalRcvExecResult::err, errcode(), errmsg(), ERROR, InvalidOid, libpqrcv_processTuples(), libpqsrv_exec(), MAKE_SQLSTATE, MyDatabaseId, palloc0_object, pchomp(), PG_DIAG_SQLSTATE, 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_PIPELINE_ABORTED, PGRES_PIPELINE_SYNC, PGRES_SINGLE_TUPLE, PGRES_TUPLES_CHUNK, PGRES_TUPLES_OK, PQclear, PQerrorMessage(), PQresultErrorField, PQresultStatus, WalRcvExecResult::sqlstate, WalRcvExecResult::status, WALRCV_ERROR, WALRCV_OK_COMMAND, WALRCV_OK_COPY_BOTH, WALRCV_OK_COPY_IN, WALRCV_OK_COPY_OUT, and WALRCV_OK_TUPLES.

◆ libpqrcv_get_backend_pid()

static pid_t libpqrcv_get_backend_pid ( WalReceiverConn conn)
static

Definition at line 1041 of file libpqwalreceiver.c.

1042{
1043 return PQbackendPID(conn->streamConn);
1044}
int PQbackendPID(const PGconn *conn)
Definition: fe-connect.c:7740

References conn, and PQbackendPID().

◆ libpqrcv_get_conninfo()

static char * libpqrcv_get_conninfo ( WalReceiverConn conn)
static

Definition at line 351 of file libpqwalreceiver.c.

352{
353 PQconninfoOption *conn_opts;
354 PQconninfoOption *conn_opt;
356 char *retval;
357
358 Assert(conn->streamConn != NULL);
359
361 conn_opts = PQconninfo(conn->streamConn);
362
363 if (conn_opts == NULL)
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 for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
371 {
372 bool obfuscate;
373
374 /* Skip debug and empty options */
375 if (strchr(conn_opt->dispchar, 'D') ||
376 conn_opt->val == NULL ||
377 conn_opt->val[0] == '\0')
378 continue;
379
380 /* Obfuscate security-sensitive options */
381 obfuscate = strchr(conn_opt->dispchar, '*') != NULL;
382
383 appendPQExpBuffer(&buf, "%s%s=%s",
384 buf.len == 0 ? "" : " ",
385 conn_opt->keyword,
386 obfuscate ? "********" : conn_opt->val);
387 }
388
389 PQconninfoFree(conn_opts);
390
391 retval = PQExpBufferDataBroken(buf) ? NULL : pstrdup(buf.data);
393 return retval;
394}
PQconninfoOption * PQconninfo(PGconn *conn)
Definition: fe-connect.c:7481
static char buf[DEFAULT_XLOG_SEG_SIZE]
Definition: pg_test_fsync.c:71
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67

References _, appendPQExpBuffer(), Assert(), buf, conn, _PQconninfoOption::dispchar, ereport, errcode(), errmsg(), ERROR, initPQExpBuffer(), _PQconninfoOption::keyword, PQconninfo(), PQconninfoFree(), PQExpBufferDataBroken, pstrdup(), termPQExpBuffer(), and _PQconninfoOption::val.

◆ libpqrcv_get_dbname_from_conninfo()

static char * libpqrcv_get_dbname_from_conninfo ( const char *  connInfo)
static

Definition at line 475 of file libpqwalreceiver.c.

476{
477 return libpqrcv_get_option_from_conninfo(connInfo, "dbname");
478}

References libpqrcv_get_option_from_conninfo().

◆ libpqrcv_get_option_from_conninfo()

static char * libpqrcv_get_option_from_conninfo ( const char *  connInfo,
const char *  keyword 
)
static

Definition at line 487 of file libpqwalreceiver.c.

488{
490 char *option = NULL;
491 char *err = NULL;
492
493 opts = PQconninfoParse(connInfo, &err);
494 if (opts == NULL)
495 {
496 /* The error string is malloc'd, so we must free it explicitly */
497 char *errcopy = err ? pstrdup(err) : "out of memory";
498
499 PQfreemem(err);
501 (errcode(ERRCODE_SYNTAX_ERROR),
502 errmsg("invalid connection string syntax: %s", errcopy)));
503 }
504
505 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 if (strcmp(opt->keyword, keyword) == 0 && opt->val &&
512 *opt->val)
513 {
514 if (option)
515 pfree(option);
516
517 option = pstrdup(opt->val);
518 }
519 }
520
522 return option;
523}

References ereport, err(), errcode(), errmsg(), ERROR, opts, pfree(), PQconninfoFree(), PQconninfoParse(), PQfreemem(), and pstrdup().

Referenced by libpqrcv_connect(), and libpqrcv_get_dbname_from_conninfo().

◆ libpqrcv_get_senderinfo()

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

Definition at line 400 of file libpqwalreceiver.c.

402{
403 char *ret = NULL;
404
405 *sender_host = NULL;
406 *sender_port = 0;
407
408 Assert(conn->streamConn != NULL);
409
410 ret = PQhost(conn->streamConn);
411 if (ret && strlen(ret) != 0)
412 *sender_host = pstrdup(ret);
413
414 ret = PQport(conn->streamConn);
415 if (ret && strlen(ret) != 0)
416 *sender_port = atoi(ret);
417}
char * PQport(const PGconn *conn)
Definition: fe-connect.c:7607
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:7571

References Assert(), conn, PQhost(), PQport(), and pstrdup().

◆ libpqrcv_identify_system()

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

Definition at line 424 of file libpqwalreceiver.c.

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 res = libpqsrv_exec(conn->streamConn,
434 "IDENTIFY_SYSTEM",
435 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
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 if (PQnfields(res) < 3 || PQntuples(res) != 1)
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 primary_sysid = pstrdup(PQgetvalue(res, 0, 0));
454 *primary_tli = pg_strtoint32(PQgetvalue(res, 0, 1));
455 PQclear(res);
456
457 return primary_sysid;
458}

References conn, ereport, errcode(), errdetail(), errmsg(), ERROR, libpqsrv_exec(), pchomp(), pg_strtoint32(), PGRES_TUPLES_OK, PQclear, PQerrorMessage(), PQgetvalue, PQnfields, PQntuples, PQresultStatus, and pstrdup().

◆ libpqrcv_processTuples()

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

Definition at line 1050 of file libpqwalreceiver.c.

1052{
1053 int tupn;
1054 int coln;
1055 int nfields = PQnfields(pgres);
1056 HeapTuple tuple;
1057 AttInMetadata *attinmeta;
1058 MemoryContext rowcontext;
1059 MemoryContext oldcontext;
1060
1061 /* Make sure we got expected number of fields. */
1062 if (nfields != nRetTypes)
1063 ereport(ERROR,
1064 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1065 errmsg("invalid query response"),
1066 errdetail("Expected %d fields, got %d fields.",
1067 nRetTypes, nfields)));
1068
1069 walres->tuplestore = tuplestore_begin_heap(true, false, work_mem);
1070
1071 /* Create tuple descriptor corresponding to expected result. */
1072 walres->tupledesc = CreateTemplateTupleDesc(nRetTypes);
1073 for (coln = 0; coln < nRetTypes; coln++)
1074 TupleDescInitEntry(walres->tupledesc, (AttrNumber) coln + 1,
1075 PQfname(pgres, coln), retTypes[coln], -1, 0);
1076 attinmeta = TupleDescGetAttInMetadata(walres->tupledesc);
1077
1078 /* No point in doing more here if there were no tuples returned. */
1079 if (PQntuples(pgres) == 0)
1080 return;
1081
1082 /* Create temporary context for local allocations. */
1084 "libpqrcv query result context",
1086
1087 /* Process returned rows. */
1088 for (tupn = 0; tupn < PQntuples(pgres); tupn++)
1089 {
1090 char *cstrs[MaxTupleAttributeNumber];
1091
1093
1094 /* Do the allocations in temporary context. */
1095 oldcontext = MemoryContextSwitchTo(rowcontext);
1096
1097 /*
1098 * Fill cstrs with null-terminated strings of column values.
1099 */
1100 for (coln = 0; coln < nfields; coln++)
1101 {
1102 if (PQgetisnull(pgres, tupn, coln))
1103 cstrs[coln] = NULL;
1104 else
1105 cstrs[coln] = PQgetvalue(pgres, tupn, coln);
1106 }
1107
1108 /* Convert row to a tuple, and add it to the tuplestore */
1109 tuple = BuildTupleFromCStrings(attinmeta, cstrs);
1110 tuplestore_puttuple(walres->tuplestore, tuple);
1111
1112 /* Clean up */
1113 MemoryContextSwitchTo(oldcontext);
1114 MemoryContextReset(rowcontext);
1115 }
1116
1117 MemoryContextDelete(rowcontext);
1118}
int16 AttrNumber
Definition: attnum.h:21
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2324
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2275
int work_mem
Definition: globals.c:131
#define MaxTupleAttributeNumber
Definition: htup_details.h:34
#define PQfname
Definition: libpq-be-fe.h:256
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:403
MemoryContext CurrentMemoryContext
Definition: mcxt.c:160
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:472
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:123
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
Tuplestorestate * tuplestore
Definition: walreceiver.h:223
TupleDesc tupledesc
Definition: walreceiver.h:224
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:182
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:842
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:330
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:764

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

Referenced by libpqrcv_exec().

◆ libpqrcv_readtimelinehistoryfile()

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

Definition at line 720 of file libpqwalreceiver.c.

723{
724 PGresult *res;
725 char cmd[64];
726
727 Assert(!conn->logical);
728
729 /*
730 * Request the primary to send over the history file for given timeline.
731 */
732 snprintf(cmd, sizeof(cmd), "TIMELINE_HISTORY %u", tli);
733 res = libpqsrv_exec(conn->streamConn,
734 cmd,
735 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
738 (errcode(ERRCODE_PROTOCOL_VIOLATION),
739 errmsg("could not receive timeline history file from "
740 "the primary server: %s",
741 pchomp(PQerrorMessage(conn->streamConn)))));
742 if (PQnfields(res) != 2 || PQntuples(res) != 1)
744 (errcode(ERRCODE_PROTOCOL_VIOLATION),
745 errmsg("invalid response from primary server"),
746 errdetail("Expected 1 tuple with 2 fields, got %d tuples with %d fields.",
747 PQntuples(res), PQnfields(res))));
748 *filename = pstrdup(PQgetvalue(res, 0, 0));
749
750 *len = PQgetlength(res, 0, 1);
751 *content = palloc(*len);
752 memcpy(*content, PQgetvalue(res, 0, 1), *len);
753 PQclear(res);
754}
#define PQgetlength
Definition: libpq-be-fe.h:254
void * palloc(Size size)
Definition: mcxt.c:1387
const void size_t len
static char * filename
Definition: pg_dumpall.c:120
#define snprintf
Definition: port.h:260

References Assert(), conn, ereport, errcode(), errdetail(), errmsg(), ERROR, filename, len, libpqsrv_exec(), palloc(), pchomp(), PGRES_TUPLES_OK, PQclear, PQerrorMessage(), PQgetlength, PQgetvalue, PQnfields, PQntuples, PQresultStatus, pstrdup(), and snprintf.

◆ libpqrcv_receive()

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

Definition at line 784 of file libpqwalreceiver.c.

786{
787 int rawlen;
788
789 PQfreemem(conn->recvBuf);
790 conn->recvBuf = NULL;
791
792 /* Try to receive a CopyData message */
793 rawlen = PQgetCopyData(conn->streamConn, &conn->recvBuf, 1);
794 if (rawlen == 0)
795 {
796 /* Try consuming some data. */
797 if (PQconsumeInput(conn->streamConn) == 0)
799 (errcode(ERRCODE_CONNECTION_FAILURE),
800 errmsg("could not receive data from WAL stream: %s",
801 pchomp(PQerrorMessage(conn->streamConn)))));
802
803 /* Now that we've consumed some input, try again */
804 rawlen = PQgetCopyData(conn->streamConn, &conn->recvBuf, 1);
805 if (rawlen == 0)
806 {
807 /* Tell caller to try again when our socket is ready. */
808 *wait_fd = PQsocket(conn->streamConn);
809 return 0;
810 }
811 }
812 if (rawlen == -1) /* end-of-streaming or error */
813 {
814 PGresult *res;
815
816 res = libpqsrv_get_result(conn->streamConn,
817 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
819 {
820 PQclear(res);
821
822 /* Verify that there are no more results. */
823 res = libpqsrv_get_result(conn->streamConn,
824 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
825 if (res != NULL)
826 {
827 PQclear(res);
828
829 /*
830 * If the other side closed the connection orderly (otherwise
831 * we'd seen an error, or PGRES_COPY_IN) don't report an error
832 * here, but let callers deal with it.
833 */
834 if (PQstatus(conn->streamConn) == CONNECTION_BAD)
835 return -1;
836
838 (errcode(ERRCODE_PROTOCOL_VIOLATION),
839 errmsg("unexpected result after CommandComplete: %s",
840 PQerrorMessage(conn->streamConn))));
841 }
842
843 return -1;
844 }
845 else if (PQresultStatus(res) == PGRES_COPY_IN)
846 {
847 PQclear(res);
848 return -1;
849 }
850 else
852 (errcode(ERRCODE_PROTOCOL_VIOLATION),
853 errmsg("could not receive data from WAL stream: %s",
854 pchomp(PQerrorMessage(conn->streamConn)))));
855 }
856 if (rawlen < -1)
858 (errcode(ERRCODE_PROTOCOL_VIOLATION),
859 errmsg("could not receive data from WAL stream: %s",
860 pchomp(PQerrorMessage(conn->streamConn)))));
861
862 /* Return received messages to caller */
863 *buffer = conn->recvBuf;
864 return rawlen;
865}
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:7730
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:2001
int PQgetCopyData(PGconn *conn, char **buffer, int async)
Definition: fe-exec.c:2833
@ CONNECTION_BAD
Definition: libpq-fe.h:85

References conn, CONNECTION_BAD, ereport, errcode(), errmsg(), ERROR, libpqsrv_get_result(), pchomp(), PGRES_COMMAND_OK, PGRES_COPY_IN, PQclear, PQconsumeInput(), PQerrorMessage(), PQfreemem(), PQgetCopyData(), PQresultStatus, PQsocket(), and PQstatus().

◆ libpqrcv_send()

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

Definition at line 873 of file libpqwalreceiver.c.

874{
875 if (PQputCopyData(conn->streamConn, buffer, nbytes) <= 0 ||
876 PQflush(conn->streamConn))
878 (errcode(ERRCODE_CONNECTION_FAILURE),
879 errmsg("could not send data to WAL stream: %s",
880 pchomp(PQerrorMessage(conn->streamConn)))));
881}
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2712

References conn, ereport, errcode(), errmsg(), ERROR, pchomp(), PQerrorMessage(), PQflush(), and PQputCopyData().

◆ libpqrcv_server_version()

static int libpqrcv_server_version ( WalReceiverConn conn)
static

Definition at line 464 of file libpqwalreceiver.c.

465{
466 return PQserverVersion(conn->streamConn);
467}

References conn, and PQserverVersion().

◆ libpqrcv_startstreaming()

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

Definition at line 536 of file libpqwalreceiver.c.

538{
539 StringInfoData cmd;
540 PGresult *res;
541
542 Assert(options->logical == conn->logical);
543 Assert(options->slotname || !options->logical);
544
545 initStringInfo(&cmd);
546
547 /* Build the command. */
548 appendStringInfoString(&cmd, "START_REPLICATION");
549 if (options->slotname != NULL)
550 appendStringInfo(&cmd, " SLOT \"%s\"",
551 options->slotname);
552
553 if (options->logical)
554 appendStringInfoString(&cmd, " LOGICAL");
555
556 appendStringInfo(&cmd, " %X/%08X", LSN_FORMAT_ARGS(options->startpoint));
557
558 /*
559 * Additional options are different depending on if we are doing logical
560 * or physical replication.
561 */
562 if (options->logical)
563 {
564 char *pubnames_str;
565 List *pubnames;
566 char *pubnames_literal;
567
568 appendStringInfoString(&cmd, " (");
569
570 appendStringInfo(&cmd, "proto_version '%u'",
571 options->proto.logical.proto_version);
572
573 if (options->proto.logical.streaming_str)
574 appendStringInfo(&cmd, ", streaming '%s'",
575 options->proto.logical.streaming_str);
576
577 if (options->proto.logical.twophase &&
578 PQserverVersion(conn->streamConn) >= 150000)
579 appendStringInfoString(&cmd, ", two_phase 'on'");
580
581 if (options->proto.logical.origin &&
582 PQserverVersion(conn->streamConn) >= 160000)
583 appendStringInfo(&cmd, ", origin '%s'",
584 options->proto.logical.origin);
585
586 pubnames = options->proto.logical.publication_names;
587 pubnames_str = stringlist_to_identifierstr(conn->streamConn, pubnames);
588 if (!pubnames_str)
590 (errcode(ERRCODE_OUT_OF_MEMORY), /* likely guess */
591 errmsg("could not start WAL streaming: %s",
592 pchomp(PQerrorMessage(conn->streamConn)))));
593 pubnames_literal = PQescapeLiteral(conn->streamConn, pubnames_str,
594 strlen(pubnames_str));
595 if (!pubnames_literal)
597 (errcode(ERRCODE_OUT_OF_MEMORY), /* likely guess */
598 errmsg("could not start WAL streaming: %s",
599 pchomp(PQerrorMessage(conn->streamConn)))));
600 appendStringInfo(&cmd, ", publication_names %s", pubnames_literal);
601 PQfreemem(pubnames_literal);
602 pfree(pubnames_str);
603
604 if (options->proto.logical.binary &&
605 PQserverVersion(conn->streamConn) >= 140000)
606 appendStringInfoString(&cmd, ", binary 'true'");
607
608 appendStringInfoChar(&cmd, ')');
609 }
610 else
611 appendStringInfo(&cmd, " TIMELINE %u",
612 options->proto.physical.startpointTLI);
613
614 /* Start streaming. */
615 res = libpqsrv_exec(conn->streamConn,
616 cmd.data,
617 WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
618 pfree(cmd.data);
619
621 {
622 PQclear(res);
623 return false;
624 }
625 else if (PQresultStatus(res) != PGRES_COPY_BOTH)
627 (errcode(ERRCODE_PROTOCOL_VIOLATION),
628 errmsg("could not start WAL streaming: %s",
629 pchomp(PQerrorMessage(conn->streamConn)))));
630 PQclear(res);
631 return true;
632}
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4399
static char * stringlist_to_identifierstr(PGconn *conn, List *strings)
Definition: pg_list.h:54
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:47

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert(), conn, StringInfoData::data, ereport, errcode(), errmsg(), ERROR, initStringInfo(), libpqsrv_exec(), LSN_FORMAT_ARGS, pchomp(), pfree(), PGRES_COMMAND_OK, PGRES_COPY_BOTH, PQclear, PQerrorMessage(), PQescapeLiteral(), PQfreemem(), PQresultStatus, PQserverVersion(), and stringlist_to_identifierstr().

◆ PG_MODULE_MAGIC_EXT()

PG_MODULE_MAGIC_EXT ( name = "libpqwalreceiver",
version = PG_VERSION 
)

◆ stringlist_to_identifierstr()

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

Definition at line 1208 of file libpqwalreceiver.c.

1209{
1210 ListCell *lc;
1211 StringInfoData res;
1212 bool first = true;
1213
1214 initStringInfo(&res);
1215
1216 foreach(lc, strings)
1217 {
1218 char *val = strVal(lfirst(lc));
1219 char *val_escaped;
1220
1221 if (first)
1222 first = false;
1223 else
1224 appendStringInfoChar(&res, ',');
1225
1226 val_escaped = PQescapeIdentifier(conn, val, strlen(val));
1227 if (!val_escaped)
1228 {
1229 free(res.data);
1230 return NULL;
1231 }
1232 appendStringInfoString(&res, val_escaped);
1233 PQfreemem(val_escaped);
1234 }
1235
1236 return res.data;
1237}
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4405
long val
Definition: informix.c:689
#define lfirst(lc)
Definition: pg_list.h:172
#define free(a)
#define strVal(v)
Definition: value.h:82

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

Referenced by libpqrcv_startstreaming().

Variable Documentation

◆ PQWalReceiverFunctions

WalReceiverFunctionsType PQWalReceiverFunctions
static
Initial value:
= {
.walrcv_connect = libpqrcv_connect,
.walrcv_check_conninfo = libpqrcv_check_conninfo,
.walrcv_get_conninfo = libpqrcv_get_conninfo,
.walrcv_get_senderinfo = libpqrcv_get_senderinfo,
.walrcv_identify_system = libpqrcv_identify_system,
.walrcv_server_version = libpqrcv_server_version,
.walrcv_readtimelinehistoryfile = libpqrcv_readtimelinehistoryfile,
.walrcv_startstreaming = libpqrcv_startstreaming,
.walrcv_endstreaming = libpqrcv_endstreaming,
.walrcv_receive = libpqrcv_receive,
.walrcv_send = libpqrcv_send,
.walrcv_create_slot = libpqrcv_create_slot,
.walrcv_alter_slot = libpqrcv_alter_slot,
.walrcv_get_dbname_from_conninfo = libpqrcv_get_dbname_from_conninfo,
.walrcv_get_backend_pid = libpqrcv_get_backend_pid,
.walrcv_exec = libpqrcv_exec,
.walrcv_disconnect = libpqrcv_disconnect
}
static WalReceiverConn * libpqrcv_connect(const char *conninfo, bool replication, bool logical, bool must_use_password, const char *appname, char **err)
static void libpqrcv_readtimelinehistoryfile(WalReceiverConn *conn, TimeLineID tli, char **filename, char **content, int *len)
static pid_t libpqrcv_get_backend_pid(WalReceiverConn *conn)
static void libpqrcv_send(WalReceiverConn *conn, const char *buffer, int nbytes)
static void libpqrcv_disconnect(WalReceiverConn *conn)
static char * libpqrcv_identify_system(WalReceiverConn *conn, TimeLineID *primary_tli)
static char * libpqrcv_create_slot(WalReceiverConn *conn, const char *slotname, bool temporary, bool two_phase, bool failover, CRSSnapshotAction snapshot_action, XLogRecPtr *lsn)
static WalRcvExecResult * libpqrcv_exec(WalReceiverConn *conn, const char *query, const int nRetTypes, const Oid *retTypes)
static void libpqrcv_endstreaming(WalReceiverConn *conn, TimeLineID *next_tli)
static void libpqrcv_get_senderinfo(WalReceiverConn *conn, char **sender_host, int *sender_port)
static int libpqrcv_server_version(WalReceiverConn *conn)
static bool libpqrcv_startstreaming(WalReceiverConn *conn, const WalRcvStreamOptions *options)
static int libpqrcv_receive(WalReceiverConn *conn, char **buffer, pgsocket *wait_fd)
static void libpqrcv_alter_slot(WalReceiverConn *conn, const char *slotname, const bool *failover, const bool *two_phase)
static char * libpqrcv_get_conninfo(WalReceiverConn *conn)
static char * libpqrcv_get_dbname_from_conninfo(const char *connInfo)

Definition at line 98 of file libpqwalreceiver.c.

Referenced by _PG_init().