From d99f589b08817f1ccf15d53a81ae0285a54c662f Mon Sep 17 00:00:00 2001
From: Tobias Bussmann <t.bussmann@gmx.net>
Date: Thu, 14 Sep 2023 20:52:33 +0200
Subject: [PATCH] psql: fix \bind when FETCH_COUNT is used

Respect bind parameters when declaring the cursor in ExecQueryUsingCursor() (used when
FETCH_COUNT is set).

---
 src/bin/psql/common.c              |  6 +++++-
 src/test/regress/expected/psql.out | 21 +++++++++++++++++++++
 src/test/regress/sql/psql.sql      |  7 +++++++
 3 files changed, 33 insertions(+), 1 deletion(-)

diff --git a/src/bin/psql/common.c b/src/bin/psql/common.c
index ede197bebe..49830934a0 100644
--- a/src/bin/psql/common.c
+++ b/src/bin/psql/common.c
@@ -1755,7 +1755,11 @@ ExecQueryUsingCursor(const char *query, double *elapsed_msec)
 	appendPQExpBuffer(&buf, "DECLARE _psql_cursor NO SCROLL CURSOR FOR\n%s",
 					  query);
 
-	result = PQexec(pset.db, buf.data);
+    if (pset.bind_flag)
+        result = PQexecParams(pset.db, buf.data, pset.bind_nparams, NULL, (const char * const *) pset.bind_params, NULL, NULL, 0);
+    else
+        result = PQexec(pset.db, buf.data);
+    
 	OK = AcceptResult(result, true) &&
 		(PQresultStatus(result) == PGRES_COMMAND_OK);
 	if (!OK)
diff --git a/src/test/regress/expected/psql.out b/src/test/regress/expected/psql.out
index 7cd0c27cca..200910392e 100644
--- a/src/test/regress/expected/psql.out
+++ b/src/test/regress/expected/psql.out
@@ -117,6 +117,27 @@ SELECT $1, $2 \bind 'foo' 'bar' \g
  foo      | bar
 (1 row)
 
+-- should work in FETCH_COUNT mode too
+\set FETCH_COUNT 1
+SELECT 1 \bind \g
+ ?column? 
+----------
+        1
+(1 row)
+
+SELECT $1 \bind 'foo' \g
+ ?column? 
+----------
+ foo
+(1 row)
+
+SELECT $1, $2 \bind 'foo' 'bar' \g
+ ?column? | ?column? 
+----------+----------
+ foo      | bar
+(1 row)
+
+\unset FETCH_COUNT
 -- errors
 -- parse error
 SELECT foo \bind \g
diff --git a/src/test/regress/sql/psql.sql b/src/test/regress/sql/psql.sql
index f3bc6cd07e..b116237365 100644
--- a/src/test/regress/sql/psql.sql
+++ b/src/test/regress/sql/psql.sql
@@ -51,6 +51,13 @@ SELECT 1 \bind \g
 SELECT $1 \bind 'foo' \g
 SELECT $1, $2 \bind 'foo' 'bar' \g
 
+-- should work in FETCH_COUNT mode too
+\set FETCH_COUNT 1
+SELECT 1 \bind \g
+SELECT $1 \bind 'foo' \g
+SELECT $1, $2 \bind 'foo' 'bar' \g
+\unset FETCH_COUNT
+
 -- errors
 -- parse error
 SELECT foo \bind \g
-- 
2.37.5

