0001-Recheck-foreign-key-of-a-partition-is-inherited-from.patch

text/plain

Filename: 0001-Recheck-foreign-key-of-a-partition-is-inherited-from.patch
Type: text/plain
Part: 0
Message: Re: [BUG] Fix DETACH with FK pointing to a partitioned table fails

Patch

Format: format-patch
Series: patch 0001
Subject: Recheck foreign key of a partition is inherited from parent.
File+
src/backend/commands/tablecmds.c 19 0
From d84395c7321c201a78661de0b41b76e71ab10678 Mon Sep 17 00:00:00 2001
From: "tender.wang" <tender.wang@openpie.com>
Date: Thu, 3 Aug 2023 17:23:06 +0800
Subject: [PATCH] Recheck foreign key of a partition is inherited from parent.

Previously, fk is inherited if conparentid(pg_constraint) is valid.
It is not enough and we should compare confrelid field to determine
fk is inherited.
---
 src/backend/commands/tablecmds.c | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)

diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 727f151750..1447433109 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -18556,6 +18556,8 @@ DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
 		ForeignKeyCacheInfo *fk = lfirst(cell);
 		HeapTuple	contup;
 		Form_pg_constraint conform;
+		HeapTuple parentTup;
+		Form_pg_constraint parentForm;
 		Constraint *fkconstraint;
 		Oid			insertTriggerOid,
 					updateTriggerOid;
@@ -18573,6 +18575,23 @@ DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
 			continue;
 		}
 
+		/* recheck confrelid field */
+		if (OidIsValid(conform->conparentid))
+		{
+			parentTup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(conform->conparentid));
+			if (!HeapTupleIsValid(parentTup))
+				elog(ERROR, "cache lookup failed for constraint %u", conform->conparentid);
+			parentForm = (Form_pg_constraint) GETSTRUCT(parentTup);
+			/* It is not inherited foreign keys */
+			if (parentForm->confrelid != conform->confrelid)
+			{
+				ReleaseSysCache(contup);
+				ReleaseSysCache(parentTup);
+				continue;
+			}
+			ReleaseSysCache(parentTup);
+		}
+
 		/* unset conparentid and adjust conislocal, coninhcount, etc. */
 		ConstraintSetParentConstraint(fk->conoid, InvalidOid, InvalidOid);
 
-- 
2.25.1