From 25ee160acd3670104af6b62564d7142e0bbe115f Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Thu, 1 Jul 2004 21:17:13 +0000
Subject: [PATCH] More paranoia in AtEOSubXact_SPI: don't assume we can safely
 use SPI_finish for cleaning up.  It seems possible that the memory contexts
 SPI_finish would try to touch are already gone; and there's no need for SPI
 itself to delete them, since the containing contexts will surely be going
 away anyway at transaction end.

---
 src/backend/executor/spi.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)

diff --git a/src/backend/executor/spi.c b/src/backend/executor/spi.c
index 7534ddd7933..19dbfc13d0f 100644
--- a/src/backend/executor/spi.c
+++ b/src/backend/executor/spi.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $PostgreSQL: pgsql/src/backend/executor/spi.c,v 1.119 2004/07/01 00:50:26 tgl Exp $
+ *	  $PostgreSQL: pgsql/src/backend/executor/spi.c,v 1.120 2004/07/01 21:17:13 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -206,16 +206,27 @@ AtEOSubXact_SPI(bool isCommit, TransactionId childXid)
 	while (_SPI_connected >= 0)
 	{
 		_SPI_connection *connection = &(_SPI_stack[_SPI_connected]);
-		int		res;
 
 		if (connection->connectXid != childXid)
 			break;				/* couldn't be any underneath it either */
 
 		found = true;
 
-		_SPI_curid = _SPI_connected - 1; /* avoid begin_call error */
-		res = SPI_finish();
-		Assert(res == SPI_OK_FINISH);
+		/*
+		 * Pop the stack entry and reset global variables.  Unlike
+		 * SPI_finish(), we don't risk switching to memory contexts that
+		 * might be already gone, or deleting memory contexts that have been
+		 * or will be thrown away anyway.
+		 */
+		_SPI_connected--;
+		_SPI_curid = _SPI_connected;
+		if (_SPI_connected == -1)
+			_SPI_current = NULL;
+		else
+			_SPI_current = &(_SPI_stack[_SPI_connected]);
+		SPI_processed = 0;
+		SPI_lastoid = InvalidOid;
+		SPI_tuptable = NULL;
 	}
 
 	if (found && isCommit)
-- 
GitLab