From d4b9fb485110a5a27d9f85eff23a8ffca550eaf2 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Wed, 20 Sep 2017 01:12:32 -0700
Subject: [PATCH 1/3] Add ability to force libpq to negotiate a specific
 version of the protocol.

Author: Andres Freund
Discussion: https://postgr.es/m/20170918095303.g766pdnvviqlewph@alap3.anarazel.de
---
 src/interfaces/libpq/fe-connect.c | 13 ++++++++++++-
 src/interfaces/libpq/libpq-int.h  |  3 +++
 2 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index c580d91135..a9dd14d48b 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -323,6 +323,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = {
 		"Target-Session-Attrs", "", 11, /* sizeof("read-write") = 11 */
 	offsetof(struct pg_conn, target_session_attrs)},
 
+	{"forced_protocol_version", "PGFORCEPROTOCOLVERSION", NULL, NULL,
+	 "Forced-version", "D", sizeof("Forced-version"),
+	offsetof(struct pg_conn, forced_protocol_version)},
+
 	/* Terminating entry --- MUST BE LAST */
 	{NULL, NULL, NULL, NULL,
 	NULL, NULL, 0}
@@ -1803,7 +1807,14 @@ connectDBStart(PGconn *conn)
 	 */
 	conn->whichhost = 0;
 	conn->addr_cur = conn->connhost[0].addrlist;
-	conn->pversion = PG_PROTOCOL(3, 0);
+	if (conn->forced_protocol_version != NULL)
+	{
+		conn->pversion = atoi(conn->forced_protocol_version);
+	}
+	else
+	{
+		conn->pversion = PG_PROTOCOL(3, 0);
+	}
 	conn->send_appname = true;
 	conn->status = CONNECTION_NEEDED;
 
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 42913604e3..7bfc09ec71 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -364,6 +364,9 @@ struct pg_conn
 	/* Type of connection to make.  Possible values: any, read-write. */
 	char	   *target_session_attrs;
 
+	char	   *forced_protocol_version; /* for testing: force protocol to a
+										  * specific version */
+
 	/* Optional file to write trace info to */
 	FILE	   *Pfdebug;
 
-- 
2.14.1.536.g6867272d5b.dirty

