From 6ed6237c1b9c06a6603e7c817da2f6308b24591d Mon Sep 17 00:00:00 2001
From: houzj <houzj.fnst@cn.fujitsu.com>
Date: Tue, 16 Mar 2021 15:28:10 +0800
Subject: [PATCH] extend safery check to support parallel insert into fk relation

Currently, We can not support parallel insert into fk relation in all cases.

For example:
When inserting into a table with foreign key, if the referenced could also be modified in
INSERT command, we will need to do CommandCounterIncrement to let the modification
on referenced table visible for the RI check which is not supported in parallel worker.

So, Extent the parallel-safety check to treat the following cases(could modify referenced table) parallel restricted:
1) foreign key and primary key are on the same table(INSERT's target table).
  (referenced and referencing are the same table)
2) referenced and referencing table are both partition of INSERT's target table.

(Note: modifyingCTE and function with modifying statement could also modifiy the referenced table,
However, the current parallel safery check already treat it as unsafe, we do not need to
anything about it.)

Except for the above cases, we treat other cases as parallel safe.
---
 src/backend/optimizer/util/clauses.c | 84 +++++++++++++++++++++++++++++++++++-
 src/include/catalog/pg_proc.dat      |  8 ++--
 2 files changed, 87 insertions(+), 5 deletions(-)

diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c
index ade66a5..cff18dd 100644
--- a/src/backend/optimizer/util/clauses.c
+++ b/src/backend/optimizer/util/clauses.c
@@ -100,6 +100,7 @@ typedef struct
 	RangeTblEntry *target_rte;	/* query's target relation if any */
 	CmdType		command_type;	/* query's command type */
 	PlannerGlobal *planner_global;	/* global info for planner invocation */
+	List	   *pk_rels;		/* OIDs of relations referenced by target relation */
 } max_parallel_hazard_context;
 
 static bool contain_agg_clause_walker(Node *node, void *context);
@@ -582,6 +583,7 @@ max_parallel_hazard(Query *parse, PlannerGlobal *glob)
 		rt_fetch(parse->resultRelation, parse->rtable) : NULL;
 	context.command_type = parse->commandType;
 	context.planner_global = glob;
+	context.pk_rels = NIL;
 	(void) max_parallel_hazard_walker((Node *) parse, &context);
 
 	return context.max_hazard;
@@ -873,7 +875,7 @@ static bool
 target_rel_max_parallel_hazard(max_parallel_hazard_context *context)
 {
 	bool		max_hazard_found;
-
+	ListCell   *lc;
 	Relation	targetRel;
 
 	/*
@@ -884,6 +886,36 @@ target_rel_max_parallel_hazard(max_parallel_hazard_context *context)
 	max_hazard_found = target_rel_max_parallel_hazard_recurse(targetRel,
 															  context->command_type,
 															  context);
+
+	/*
+	 * Check if target relation is one of PK relations.
+	 */
+	if (!max_hazard_found && context->max_hazard == PROPARALLEL_SAFE)
+	{
+		if (list_member_oid(context->pk_rels, context->target_rte->relid))
+		{
+			max_hazard_found = max_parallel_hazard_test(PROPARALLEL_RESTRICTED,
+														context);
+		}
+	}
+
+	/*
+	 * check if any pk relation is partition of the target table.
+	 */
+	if (context->max_hazard == PROPARALLEL_SAFE)
+	{
+		foreach(lc, context->pk_rels)
+		{
+			if (list_member_oid(context->planner_global->partitionOids,
+							   lfirst_oid(lc)))
+			{
+				max_hazard_found = max_parallel_hazard_test(PROPARALLEL_RESTRICTED,
+															context);
+				break;
+			}
+		}
+	}
+
 	table_close(targetRel, NoLock);
 
 	return max_hazard_found;
@@ -972,9 +1004,59 @@ target_rel_trigger_max_parallel_hazard(Relation rel,
 	for (i = 0; i < rel->trigdesc->numtriggers; i++)
 	{
 		Oid			tgfoid = rel->trigdesc->triggers[i].tgfoid;
+		int			trigtype;
 
 		if (max_parallel_hazard_test(func_parallel(tgfoid), context))
 			return true;
+
+		/*
+		 * If the trigger type is RI_TRIGGER_FK, this indicates a FK exists in
+		 * the relation, this should result in creation of new CommandIds if
+		 * PK relation is modified.
+		 *
+		 * However, creation of new CommandIds is not supported in a
+		 * parallel worker(but is safe in the parallel leader). So, treat all
+		 * scenarios that may modify PK relation as parallel-restricted.
+		 */
+		trigtype = RI_FKey_trigger_type(tgfoid);
+		if (trigtype == RI_TRIGGER_FK)
+		{
+			HeapTuple	tup;
+			Form_pg_constraint conForm;
+			Oid constraintOid;
+
+			constraintOid = rel->trigdesc->triggers[i].tgconstraint;
+
+			/*
+			 * Fetch the pg_constraint row so we can fill in the entry.
+			 */
+			tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
+			if (!HeapTupleIsValid(tup)) /* should not happen */
+				elog(ERROR, "cache lookup failed for constraint %u",
+					constraintOid);
+
+			conForm = (Form_pg_constraint) GETSTRUCT(tup);
+			if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
+				elog(ERROR, "constraint %u is not a foreign key constraint",
+					constraintOid);
+
+			/*
+			 * If FK relation and PK relation are not the same,
+			 * they could be partitions of the same table.
+			 * Remember Oids of PK relation for the later check.
+			 */
+			if (conForm->confrelid != conForm->conrelid)
+				context->pk_rels = lappend_oid(context->pk_rels, conForm->confrelid);
+
+			/*
+			 * If FK relation and PK relation are the same, the PK relation
+			 * could be modfied.
+			 */
+			else if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
+				return true;
+
+			ReleaseSysCache(tup);
+		}
 	}
 
 	return false;
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 93393fc..61361a6 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -3745,11 +3745,11 @@
 
 # Generic referential integrity constraint triggers
 { oid => '1644', descr => 'referential integrity FOREIGN KEY ... REFERENCES',
-  proname => 'RI_FKey_check_ins', provolatile => 'v', proparallel => 'r',
-  prorettype => 'trigger', proargtypes => '', prosrc => 'RI_FKey_check_ins' },
+  proname => 'RI_FKey_check_ins', provolatile => 'v', prorettype => 'trigger',
+  proargtypes => '', prosrc => 'RI_FKey_check_ins' },
 { oid => '1645', descr => 'referential integrity FOREIGN KEY ... REFERENCES',
-  proname => 'RI_FKey_check_upd', provolatile => 'v', proparallel => 'r',
-  prorettype => 'trigger', proargtypes => '', prosrc => 'RI_FKey_check_upd' },
+  proname => 'RI_FKey_check_upd', provolatile => 'v', prorettype => 'trigger',
+  proargtypes => '', prosrc => 'RI_FKey_check_upd' },
 { oid => '1646', descr => 'referential integrity ON DELETE CASCADE',
   proname => 'RI_FKey_cascade_del', provolatile => 'v', prorettype => 'trigger',
   proargtypes => '', prosrc => 'RI_FKey_cascade_del' },
-- 
2.7.2.windows.1

