From 1b37c4ed49b84ce646a59d3bd615e89c02b7638f Mon Sep 17 00:00:00 2001
From: shruthi gowda <shruthi.kc@enterprisedb.com>
Date: Wed, 7 Jan 2026 12:42:47 +0000
Subject: [PATCH v2] 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 |  8 ++++++++
 src/interfaces/ecpg/ecpglib/prepare.c    | 24 ++++++++++++++++++++----
 2 files changed, 28 insertions(+), 4 deletions(-)

diff --git a/src/interfaces/ecpg/ecpglib/descriptor.c b/src/interfaces/ecpg/ecpglib/descriptor.c
index 39cd5130ec9..02df1f7345b 100644
--- a/src/interfaces/ecpg/ecpglib/descriptor.c
+++ b/src/interfaces/ecpg/ecpglib/descriptor.c
@@ -507,6 +507,14 @@ ECPGget_desc(int lineno, const char *desc_name, int index,...)
 
 		/* desperate try to guess something sensible */
 		stmt.connection = ecpg_get_connection(NULL);
+		if (!stmt.connection)
+		{
+			ecpg_raise(lineno, ECPG_NO_CONN, ECPG_SQLSTATE_CONNECTION_DOES_NOT_EXIST,
+						ecpg_gettext("NULL"));
+			va_end(args);
+			return false;
+		}
+
 		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..96be4396415 100644
--- a/src/interfaces/ecpg/ecpglib/prepare.c
+++ b/src/interfaces/ecpg/ecpglib/prepare.c
@@ -381,8 +381,16 @@ 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 (!con)
+	{
+		ecpg_raise(lineno, ECPG_NO_CONN, ECPG_SQLSTATE_CONNECTION_DOES_NOT_EXIST,
+				   connection_name ? connection_name : ecpg_gettext("NULL"));
+		return false;
+	}
+	return ecpg_deallocate_all_conn(lineno, compat, con);
 }
 
 char *
@@ -399,9 +407,17 @@ 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 (!con)
+	{
+		ecpg_raise(lineno, ECPG_NO_CONN, ECPG_SQLSTATE_CONNECTION_DOES_NOT_EXIST,
+				   connection_name ? connection_name : ecpg_gettext("NULL"));
+		return NULL;
+	}
 
-	return ecpg_prepared(name, ecpg_get_connection(connection_name));
+	return ecpg_prepared(name, con);
 }
 
 /*
-- 
2.43.0

