From 3267a4da8d41761a6ddb1880e57dbfb109a3eeb3 Mon Sep 17 00:00:00 2001
From: shruthi gowda <shruthi.kc@enterprisedb.com>
Date: Mon, 19 Jan 2026 10:32:23 +0000
Subject: [PATCH v3] Add missing connection validation in ECPG

Ensure that ECPG connections are validated before use to prevent
application crashes. This allows the system to handle disconnected
states gracefully by throwing a proper error instead of
segfaulting.
---
 src/interfaces/ecpg/ecpglib/descriptor.c |  9 +++++++--
 src/interfaces/ecpg/ecpglib/prepare.c    | 17 +++++++++++++----
 2 files changed, 20 insertions(+), 6 deletions(-)

diff --git a/src/interfaces/ecpg/ecpglib/descriptor.c b/src/interfaces/ecpg/ecpglib/descriptor.c
index 39cd5130ec9..128fddd167c 100644
--- a/src/interfaces/ecpg/ecpglib/descriptor.c
+++ b/src/interfaces/ecpg/ecpglib/descriptor.c
@@ -235,6 +235,7 @@ ECPGget_desc(int lineno, const char *desc_name, int index,...)
 {
 	va_list		args;
 	PGresult   *ECPGresult;
+	struct connection *con;
 	enum ECPGdtype type;
 	int			ntuples,
 				act_tuple;
@@ -249,8 +250,12 @@ ECPGget_desc(int lineno, const char *desc_name, int index,...)
 		return false;
 	}
 
+	con = ecpg_get_connection(NULL);
+	if (!ecpg_init(con, NULL, lineno))
+		return false;
+
 	va_start(args, index);
-	ecpg_init_sqlca(sqlca);
+
 	ECPGresult = ecpg_result_by_descriptor(lineno, desc_name);
 	if (!ECPGresult)
 	{
@@ -506,7 +511,7 @@ ECPGget_desc(int lineno, const char *desc_name, int index,...)
 #endif
 
 		/* desperate try to guess something sensible */
-		stmt.connection = ecpg_get_connection(NULL);
+		stmt.connection = con;
 		ecpg_store_result(ECPGresult, index, &stmt, &data_var);
 
 #ifdef HAVE_USELOCALE
diff --git a/src/interfaces/ecpg/ecpglib/prepare.c b/src/interfaces/ecpg/ecpglib/prepare.c
index 5c7c5397535..6bcd34cdf81 100644
--- a/src/interfaces/ecpg/ecpglib/prepare.c
+++ b/src/interfaces/ecpg/ecpglib/prepare.c
@@ -381,8 +381,13 @@ ecpg_deallocate_all_conn(int lineno, enum COMPAT_MODE c, struct connection *con)
 bool
 ECPGdeallocate_all(int lineno, int compat, const char *connection_name)
 {
-	return ecpg_deallocate_all_conn(lineno, compat,
-									ecpg_get_connection(connection_name));
+	struct connection *con;
+
+	con = ecpg_get_connection(connection_name);
+	if (!ecpg_init(con, connection_name, lineno))
+		return false;
+
+	return ecpg_deallocate_all_conn(lineno, compat, con);
 }
 
 char *
@@ -399,9 +404,13 @@ ecpg_prepared(const char *name, struct connection *con)
 char *
 ECPGprepared_statement(const char *connection_name, const char *name, int lineno)
 {
-	(void) lineno;				/* keep the compiler quiet */
+	struct connection *con;
+
+	con = ecpg_get_connection(connection_name);
+	if (!ecpg_init(con, connection_name, lineno))
+		return false;
 
-	return ecpg_prepared(name, ecpg_get_connection(connection_name));
+	return ecpg_prepared(name, con);
 }
 
 /*
-- 
2.43.0

