From d36a4803e1a3c79f208906c8826aa679a5c6f0cf Mon Sep 17 00:00:00 2001
From: amit <amitlangote09@gmail.com>
Date: Mon, 26 Dec 2016 16:49:06 +0900
Subject: [PATCH 7/7] Fix RETURNING to work correctly after tuple-routing

Restore the original tuple slot to be used by ExecProcessReturning().
Also, set the original slot's tuple's t_tableOid so that requesting it
in the RETURNING list works (instead of retuning 0 for the same as
happens now).

Reported by: n/a
Patch by: Amit Langote
Reports: n/a
---
 src/backend/executor/nodeModifyTable.c | 7 +++++++
 src/test/regress/expected/insert.out   | 7 +++++++
 src/test/regress/sql/insert.sql        | 3 +++
 3 files changed, 17 insertions(+)

diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c
index 825a15f42d..97f03737f5 100644
--- a/src/backend/executor/nodeModifyTable.c
+++ b/src/backend/executor/nodeModifyTable.c
@@ -274,6 +274,7 @@ ExecInsert(ModifyTableState *mtstate,
 	 * get information on the (current) result relation
 	 */
 	resultRelInfo = estate->es_result_relation_info;
+	tuple->t_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
 
 	/* Determine the partition to heap_insert the tuple into */
 	if (mtstate->mt_partition_dispatch_info)
@@ -578,6 +579,12 @@ ExecInsert(ModifyTableState *mtstate,
 	{
 		resultRelInfo = saved_resultRelInfo;
 		estate->es_result_relation_info = resultRelInfo;
+
+		/*
+		 * Switch back to the original slot for the following steps to work
+		 * sanely.
+		 */
+		slot = oldslot;
 	}
 
 	/*
diff --git a/src/test/regress/expected/insert.out b/src/test/regress/expected/insert.out
index ed0513d2ff..3fa9315826 100644
--- a/src/test/regress/expected/insert.out
+++ b/src/test/regress/expected/insert.out
@@ -381,6 +381,13 @@ DETAIL:  Failing row contains (1, 2).
 insert into p1 (a, b) values (2, 3);
 ERROR:  new row for relation "p11" violates partition constraint
 DETAIL:  Failing row contains (3, 2).
+-- check that RETURNING works correctly
+insert into p values (1, 3) returning tableoid::regclass, *;
+ tableoid | a | b 
+----------+---+---
+ p        | 1 | 3
+(1 row)
+
 -- cleanup
 drop table p cascade;
 NOTICE:  drop cascades to 2 other objects
diff --git a/src/test/regress/sql/insert.sql b/src/test/regress/sql/insert.sql
index dca89b9286..6831bfe0d5 100644
--- a/src/test/regress/sql/insert.sql
+++ b/src/test/regress/sql/insert.sql
@@ -223,5 +223,8 @@ insert into p values (1, 2);
 -- selected by tuple-routing
 insert into p1 (a, b) values (2, 3);
 
+-- check that RETURNING works correctly
+insert into p values (1, 3) returning tableoid::regclass, *;
+
 -- cleanup
 drop table p cascade;
-- 
2.11.0

