From 60e27a669969b9fd7d5d8bccb83350492f92c224 Mon Sep 17 00:00:00 2001
From: Mark Rofail <mark.rofail@shahry.app>
Date: Sat, 20 Mar 2021 20:32:29 +0200
Subject: [PATCH v11 4/4] fk_arrays_elems_edits

---
 doc/src/sgml/ddl.sgml               |  82 +++++-----
 doc/src/sgml/ref/create_table.sgml  |  32 +++-
 src/backend/commands/matview.c      |   3 +-
 src/backend/commands/tablecmds.c    |  56 ++-----
 src/backend/utils/adt/ri_triggers.c | 246 +++++++++++++---------------
 src/backend/utils/adt/ruleutils.c   |  14 +-
 src/include/utils/builtins.h        |   3 +-
 7 files changed, 194 insertions(+), 242 deletions(-)

diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml
index 365e31c258..1f23e59904 100644
--- a/doc/src/sgml/ddl.sgml
+++ b/doc/src/sgml/ddl.sgml
@@ -1111,23 +1111,21 @@ CREATE TABLE order_items (
     <firstterm>Array Element Foreign Keys</firstterm> and is implemented in PostgreSQL
     with <firstterm>EACH ELEMENT OF foreign key constraints</firstterm>, as
     described in the following example:
+<programlisting>
+CREATE TABLE drivers (
+    driver_id integer PRIMARY KEY,
+    first_name text,
+    last_name text
+);
 
-    <programlisting>
-     CREATE TABLE drivers (
-         driver_id integer PRIMARY KEY,
-         first_name text,
-         last_name text
-     );
-
-     CREATE TABLE racing (
-         race_id integer PRIMARY KEY,
-         title text,
-         race_day date,
-         final_positions integer[],
-         FOREIGN KEY <emphasis> (EACH ELEMENT OF final_positions) REFERENCES drivers </emphasis>
-     );
-    </programlisting>
-
+CREATE TABLE racing (
+    race_id integer PRIMARY KEY,
+    title text,
+    race_day date,
+    final_positions integer[],
+    FOREIGN KEY <emphasis>(EACH ELEMENT OF final_positions) REFERENCES drivers</emphasis>
+);
+</programlisting>
     The above example uses an array (<literal>final_positions</literal>) to
     store the results of a race: for each of its elements a referential
     integrity check is enforced on the <literal>drivers</literal> table. Note
@@ -1143,35 +1141,33 @@ CREATE TABLE order_items (
     Even though the most common use case for Array Element Foreign Keys constraint is on
     a single column key, you can define an Array Element Foreign Keys constraint on a
     group of columns.
+<programlisting>
+CREATE TABLE available_moves (
+    kind text,
+    move text,
+    description text,
+    PRIMARY KEY (kind, move)
+);
 
-    <programlisting>
-     CREATE TABLE available_moves (
-         kind text,
-         move text,
-         description text,
-         PRIMARY KEY (kind, move)
-     );
-
-     CREATE TABLE paths (
-         description text,
-         kind text,
-         moves text[],
-         <emphasis>FOREIGN KEY (kind, EACH ELEMENT OF moves) REFERENCES available_moves (kind, move)</emphasis>
-     );
-
-     INSERT INTO available_moves VALUES ('relative', 'LN', 'look north');
-     INSERT INTO available_moves VALUES ('relative', 'RL', 'rotate left');
-     INSERT INTO available_moves VALUES ('relative', 'RR', 'rotate right');
-     INSERT INTO available_moves VALUES ('relative', 'MF', 'move forward');
-     INSERT INTO available_moves VALUES ('absolute', 'N', 'move north');
-     INSERT INTO available_moves VALUES ('absolute', 'S', 'move south');
-     INSERT INTO available_moves VALUES ('absolute', 'E', 'move east');
-     INSERT INTO available_moves VALUES ('absolute', 'W', 'move west');
-
-     INSERT INTO paths VALUES ('L-shaped path', 'relative', '{LN, RL, MF, RR, MF, MF}');
-     INSERT INTO paths VALUES ('L-shaped path', 'absolute', '{W, N, N}');
-    </programlisting>
+CREATE TABLE paths (
+    description text,
+    kind text,
+    moves text[],
+    <emphasis>FOREIGN KEY (kind, EACH ELEMENT OF moves) REFERENCES available_moves (kind, move)</emphasis>
+);
 
+INSERT INTO available_moves VALUES ('relative', 'LN', 'look north');
+INSERT INTO available_moves VALUES ('relative', 'RL', 'rotate left');
+INSERT INTO available_moves VALUES ('relative', 'RR', 'rotate right');
+INSERT INTO available_moves VALUES ('relative', 'MF', 'move forward');
+INSERT INTO available_moves VALUES ('absolute', 'N', 'move north');
+INSERT INTO available_moves VALUES ('absolute', 'S', 'move south');
+INSERT INTO available_moves VALUES ('absolute', 'E', 'move east');
+INSERT INTO available_moves VALUES ('absolute', 'W', 'move west');
+
+INSERT INTO paths VALUES ('L-shaped path', 'relative', '{LN, RL, MF, RR, MF, MF}');
+INSERT INTO paths VALUES ('L-shaped path', 'absolute', '{W, N, N}');
+</programlisting>
     In addition to standard foreign key requirements, array
     <literal>ELEMENT</literal> foreign key constraints require that the
     referencing column is an array of a compatible type to the corresponding
diff --git a/doc/src/sgml/ref/create_table.sgml b/doc/src/sgml/ref/create_table.sgml
index 319a419f78..80b0421a78 100644
--- a/doc/src/sgml/ref/create_table.sgml
+++ b/doc/src/sgml/ref/create_table.sgml
@@ -1256,16 +1256,32 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
       considerably enhances the performance. Also concerning coercion while using the 
       GIN index:
         
-      <programlisting>
-       CREATE TABLE pktableforarray ( ptest1 int2 PRIMARY KEY, ptest2 text );
-       CREATE TABLE fktableforarray ( ftest1 int4[], FOREIGN KEY (EACH ELEMENT OF ftest1) REFERENCES PKTABLEFORARRAY, ftest2 int );
-      </programlisting>
+<programlisting>
+CREATE TABLE pktableforarray (
+    ptest1 int2 PRIMARY KEY,
+    ptest2 text
+);
+
+CREATE TABLE fktableforarray (
+    ftest1 int4[],
+    FOREIGN KEY (EACH ELEMENT OF ftest1) REFERENCES pktableforarray,
+    ftest2 int
+);
+</programlisting>
       This syntax is fine since it will cast ptest1 to int4 upon RI checks,        
 
-      <programlisting>
-       CREATE TABLE pktableforarray ( ptest1 int4 PRIMARY KEY, ptest2 text );
-       CREATE TABLE fktableforarray ( ftest1 int2[], FOREIGN KEY (EACH ELEMENT OF ftest1) REFERENCES PKTABLEFORARRAY, ftest2 int );        
-      </programlisting>
+<programlisting>
+CREATE TABLE pktableforarray (
+    ptest1 int4 PRIMARY KEY,
+    ptest2 text
+);
+
+CREATE TABLE fktableforarray (
+    ftest1 int2[],
+    FOREIGN KEY (EACH ELEMENT OF ftest1) REFERENCES pktableforarray,
+    ftest2 int
+);        
+</programlisting>
        however, this syntax will cast ftest1 to int4 upon RI checks, thus defeating the
        purpose of the index.
      </para>
diff --git a/src/backend/commands/matview.c b/src/backend/commands/matview.c
index 648649ef44..172ec6e982 100644
--- a/src/backend/commands/matview.c
+++ b/src/backend/commands/matview.c
@@ -764,8 +764,7 @@ refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner,
 				generate_operator_clause(&querybuf,
 										 leftop, attrtype,
 										 op,
-										 rightop, attrtype,
-										 FKCONSTR_REF_PLAIN);
+										 rightop, attrtype);
 
 				foundUniqueIndex = true;
 			}
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index ed65a43145..1798e0b8c9 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -40,6 +40,7 @@
 #include "catalog/pg_inherits.h"
 #include "catalog/pg_namespace.h"
 #include "catalog/pg_opclass.h"
+#include "catalog/pg_operator.h"
 #include "catalog/pg_tablespace.h"
 #include "catalog/pg_trigger.h"
 #include "catalog/pg_type.h"
@@ -8593,7 +8594,7 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 	int			numfks,
 				numpks;
 	Oid			indexOid;
-	bool		has_array;
+	bool		has_each_element;
 	bool		old_check_ok;
 	ObjectAddress address;
 	ListCell   *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
@@ -8699,7 +8700,7 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 	 * format to pass to CreateConstraintEntry.
 	 */
 	Assert(list_length(fkconstraint->fk_reftypes) == numfks);
-	has_array = false;
+	has_each_element = false;
 	i = 0;
 	foreach(lc, fkconstraint->fk_reftypes)
 	{
@@ -8712,12 +8713,12 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 				break;
 			case FKCONSTR_REF_EACH_ELEMENT:
 				/* At most one FK column can be an array reference */
-				if (has_array)
+				if (has_each_element)
 					ereport(ERROR,
 							(errcode(ERRCODE_INVALID_FOREIGN_KEY),
 							 errmsg("foreign keys support only one array column")));
 
-				has_array = true;
+				has_each_element = true;
 				break;
 			default:
 				elog(ERROR, "invalid fk_reftype: %d", (int) reftype);
@@ -8731,7 +8732,7 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 	* Array foreign keys support only UPDATE/DELETE NO ACTION, UPDATE/DELETE
 	* RESTRICT
 	*/
-	if (has_array)
+	if (has_each_element)
 	{
 		if ((fkconstraint->fk_upd_action != FKCONSTR_ACTION_NOACTION &&
 			 fkconstraint->fk_upd_action != FKCONSTR_ACTION_RESTRICT) ||
@@ -8861,8 +8862,6 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 		 */
 		if (fkreftypes[i] == FKCONSTR_REF_EACH_ELEMENT)
 		{
-			Oid			elemopclass;
-
 			/* We check if the array element type exists and is of valid Oid */
 			fktype = get_base_element_type(fktype);
 			if (!OidIsValid(fktype))
@@ -8886,45 +8885,6 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 					errdetail("Unssupported relation between %s and %s.",
 							format_type_be(fktypoid[i]),
 							format_type_be(pktype))));
-
-			/*
-			 * For the moment, we must also insist that the array's element
-			 * type have a default btree opclass that is in the index's
-			 * opfamily.  This is necessary because ri_triggers.c relies on
-			 * COUNT(DISTINCT x) on the element type, as well as on array_eq()
-			 * on the array type, and we need those operations to have the
-			 * same notion of equality that we're using otherwise.
-			 *
-			 * XXX this restriction is pretty annoying, considering the effort
-			 * that's been put into the rest of the RI mechanisms to make them
-			 * work with nondefault equality operators.  In particular, it
-			 * means that the cast-to-PK-datatype code path isn't useful for
-			 * array-to-scalar references.
-			 */
-			elemopclass = GetDefaultOpClass(fktype, BTREE_AM_OID);
-			if (!OidIsValid(elemopclass) ||
-				get_opclass_family(elemopclass) != opfamily)
-			{
-				/* Get the index opclass's name for the error message. */
-				char	   *opcname;
-
-				cla_ht = SearchSysCache1(CLAOID,
-										 ObjectIdGetDatum(opclasses[i]));
-				if (!HeapTupleIsValid(cla_ht))
-					elog(ERROR, "cache lookup failed for opclass %u",
-						 opclasses[i]);
-				cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
-				opcname = pstrdup(NameStr(cla_tup->opcname));
-				ReleaseSysCache(cla_ht);
-				ereport(ERROR,
-						(errcode(ERRCODE_DATATYPE_MISMATCH),
-						 errmsg("foreign key constraint \"%s\" cannot be implemented",
-								fkconstraint->conname),
-						 errdetail("Key column \"%s\" has element type %s which does not have a default btree operator class that's compatible with class \"%s\".",
-								   strVal(list_nth(fkconstraint->fk_attrs, i)),
-								   format_type_be(fktype),
-								   opcname)));
-			}
 		}
 
 		/*
@@ -8959,6 +8919,10 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 			ffeqop = InvalidOid;
 		}
 
+		// XXX: Fix logic for selecting operators
+		if (fkreftypes[i] == FKCONSTR_REF_EACH_ELEMENT)
+			ffeqop = ARRAY_EQ_OP;
+
 		if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
 		{
 			/*
diff --git a/src/backend/utils/adt/ri_triggers.c b/src/backend/utils/adt/ri_triggers.c
index e7d6cd744f..5c61a07866 100644
--- a/src/backend/utils/adt/ri_triggers.c
+++ b/src/backend/utils/adt/ri_triggers.c
@@ -111,7 +111,6 @@ typedef struct RI_ConstraintInfo
 	char		confupdtype;	/* foreign key's ON UPDATE action */
 	char		confdeltype;	/* foreign key's ON DELETE action */
 	char		confmatchtype;	/* foreign key's match type */
-	bool		has_array;		/* true if any reftype is EACH_ELEMENT */
 	int			nkeys;			/* number of key columns */
 	int16		pk_attnums[RI_MAX_NUMKEYS]; /* attnums of referenced cols */
 	int16		fk_attnums[RI_MAX_NUMKEYS]; /* attnums of referencing cols */
@@ -189,8 +188,7 @@ static void ri_GenerateQual(StringInfo buf,
 							const char *sep,
 							const char *leftop, Oid leftoptype,
 							Oid opoid,
-							const char *rightop, Oid rightoptype,
-							char fkreftype);
+							const char *rightop, Oid rightoptype);
 static void ri_GenerateQualCollation(StringInfo buf, Oid collation);
 static int	ri_NullCheck(TupleDesc tupdesc, TupleTableSlot *slot,
 						 const RI_ConstraintInfo *riinfo, bool rel_is_pk);
@@ -349,89 +347,107 @@ RI_FKey_check(TriggerData *trigdata)
 	if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
 	{
 		StringInfoData querybuf;
-		StringInfoData countbuf;
 		char		pkrelname[MAX_QUOTED_REL_NAME_LEN];
 		char		attname[MAX_QUOTED_NAME_LEN];
 		char		paramname[16];
 		const char *querysep;
 		Oid			queryoids[RI_MAX_NUMKEYS];
 		const char *pk_only;
+		int			each_elem;
 
-		/* ----------
-		 * The query string built is
-		 *	SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
-		 *		   FOR KEY SHARE OF x
-		 * The type id's for the $ parameters are those of the
-		 * corresponding FK attributes.
-		 *
-		 * In case of an array ELEMENT foreign key, the previous query is used
-		 * to count the number of matching rows and see if every combination
-		 * is actually referenced.
-		 * The wrapping query is
-		 *	SELECT 1 WHERE
-		 *	  (SELECT count(DISTINCT y) FROM unnest($1) y)
-		 *	  = (SELECT count(*) FROM (<QUERY>) z)
-		 * ----------
-		 */
-		initStringInfo(&querybuf);
-		pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
-			"" : "ONLY ";
-		quoteRelationName(pkrelname, pk_rel);
-		appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
-						 pk_only, pkrelname);
-		querysep = "WHERE";
+		for (each_elem = 0; each_elem < riinfo->nkeys; each_elem++)
+			if (riinfo->fk_reftypes[each_elem] == FKCONSTR_REF_EACH_ELEMENT)
+				break;
 
-		if (riinfo->has_array)
+		if (each_elem < riinfo->nkeys)
 		{
-			initStringInfo(&countbuf);
-			appendStringInfo(&countbuf, "SELECT 1 WHERE ");
-		}
-
-		for (int i = 0; i < riinfo->nkeys; i++)
-		{
-			Oid			pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
-			Oid			fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
-
-			quoteOneName(attname,
-						 RIAttName(pk_rel, riinfo->pk_attnums[i]));
-			sprintf(paramname, "$%d", i + 1);
-
 			/*
-			 * In case of an array ELEMENT foreign key, we check that each
-			 * distinct non-null value in the array is present in the PK
-			 * table.
+			 * The query string built is:
+			 *
+			 * SELECT 1 WHERE NOT EXISTS
+			 * (
+			 *   SELECT 1 FROM pg_catalog.unnest($1)
+			 *   WHERE unnest IS NOT NULL AND NOT EXISTS
+			 *   (
+			 *     SELECT 1 FROM [ONLY] pktable x WHERE pkatt1 = [$2 | unnest] [AND ...]
+			 *     FOR KEY SHARE OF x
+			 *   )
+			 * )
+			 *
+			 * The type ids for the $ parameters are those of the
+			 * corresponding FK attributes.
 			 */
-			if (riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT)
-				appendStringInfo(&countbuf,
-								 "(SELECT pg_catalog.count(DISTINCT y) FROM pg_catalog.unnest(%s) y)",
-								 paramname);
-
-			ri_GenerateQual(&querybuf, querysep,
-							attname, pk_type,
-							riinfo->pf_eq_oprs[i],
-							paramname, fk_type,
-							riinfo->fk_reftypes[i]);
-			querysep = "AND";
-			queryoids[i] = fk_type;
-		}
-		appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
-
-		if (riinfo->has_array)
-		{
-			appendStringInfo(&countbuf,
-							 " OPERATOR(pg_catalog.=) (SELECT pg_catalog.count(*) FROM (%s) z)",
-							 querybuf.data);
+			initStringInfo(&querybuf);
+			pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
+				"" : "ONLY ";
+			quoteRelationName(pkrelname, pk_rel);
+			appendStringInfo(&querybuf, "SELECT 1 WHERE NOT EXISTS ("
+							 "SELECT 1 FROM pg_catalog.unnest($%d) WHERE unnest IS NOT NULL"
+							 " AND NOT EXISTS (SELECT 1 FROM %s%s x",
+							 each_elem + 1, pk_only, pkrelname);
+			querysep = "WHERE";
+			for (int i = 0; i < riinfo->nkeys; i++)
+			{
+				Oid			pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
+				Oid			fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
+
+				quoteOneName(attname,
+							 RIAttName(pk_rel, riinfo->pk_attnums[i]));
+				if (riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT)
+					sprintf(paramname, "unnest");
+				else
+					sprintf(paramname, "$%d", i + 1);
+				ri_GenerateQual(&querybuf, querysep,
+					attname, pk_type,
+					riinfo->pf_eq_oprs[i],
+					paramname, fk_type);
+				querysep = "AND";
+				queryoids[i] = fk_type;
+			}
+			appendStringInfoString(&querybuf, " FOR KEY SHARE OF x))");
 
-			/* Prepare and save the plan for Array Element Foreign Keys */
-			qplan = ri_PlanCheck(countbuf.data, riinfo->nkeys, queryoids,
+			/* Prepare and save the plan */
+			qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
 								 &qkey, fk_rel, pk_rel);
 		}
 		else
 		{
+			/*
+			 * The query string built is:
+			 *
+			 *	SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
+			 *		   FOR KEY SHARE OF x
+			 *
+			 * The type ids for the $ parameters are those of the
+			 * corresponding FK attributes.
+			 */
+			initStringInfo(&querybuf);
+			pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
+				"" : "ONLY ";
+			quoteRelationName(pkrelname, pk_rel);
+			appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
+							 pk_only, pkrelname);
+			querysep = "WHERE";
+			for (int i = 0; i < riinfo->nkeys; i++)
+			{
+				Oid			pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
+				Oid			fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
+
+				quoteOneName(attname,
+							 RIAttName(pk_rel, riinfo->pk_attnums[i]));
+				sprintf(paramname, "$%d", i + 1);
+				ri_GenerateQual(&querybuf, querysep,
+								attname, pk_type,
+								riinfo->pf_eq_oprs[i],
+								paramname, fk_type);
+				querysep = "AND";
+				queryoids[i] = fk_type;
+			}
+			appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
+
 			/* Prepare and save the plan */
 			qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
-								&qkey, fk_rel, pk_rel);
-
+								 &qkey, fk_rel, pk_rel);
 		}
 	}
 
@@ -551,8 +567,7 @@ ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel,
 			ri_GenerateQual(&querybuf, querysep,
 							attname, pk_type,
 							riinfo->pp_eq_oprs[i],
-							paramname, pk_type,
-							FKCONSTR_REF_PLAIN);
+							paramname, pk_type);
 			querysep = "AND";
 			queryoids[i] = pk_type;
 		}
@@ -741,9 +756,8 @@ ri_restrict(TriggerData *trigdata, bool is_no_action)
 			sprintf(paramname, "$%d", i + 1);
 			ri_GenerateQual(&querybuf, querysep,
 							paramname, pk_type,
-							riinfo->pf_eq_oprs[i],
-							attname, fk_type,
-							riinfo->fk_reftypes[i]);
+							riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT ? OID_ARRAY_ELEMCONTAINED_OP : riinfo->pf_eq_oprs[i], // XXX
+							attname, fk_type);
 			if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
 				ri_GenerateQualCollation(&querybuf, pk_coll);
 			querysep = "AND";
@@ -848,9 +862,8 @@ RI_FKey_cascade_del(PG_FUNCTION_ARGS)
 			sprintf(paramname, "$%d", i + 1);
 			ri_GenerateQual(&querybuf, querysep,
 							paramname, pk_type,
-							riinfo->pf_eq_oprs[i],
-							attname, fk_type,
-							riinfo->fk_reftypes[i]);
+							riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT ? OID_ARRAY_ELEMCONTAINED_OP : riinfo->pf_eq_oprs[i], // XXX
+							attname, fk_type);
 			if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
 				ri_GenerateQualCollation(&querybuf, pk_coll);
 			querysep = "AND";
@@ -968,9 +981,8 @@ RI_FKey_cascade_upd(PG_FUNCTION_ARGS)
 			sprintf(paramname, "$%d", j + 1);
 			ri_GenerateQual(&qualbuf, qualsep,
 							paramname, pk_type,
-							riinfo->pf_eq_oprs[i],
-							attname, fk_type,
-							riinfo->fk_reftypes[i]);
+							riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT ? OID_ARRAY_ELEMCONTAINED_OP : riinfo->pf_eq_oprs[i], // XXX
+							attname, fk_type);
 			if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
 				ri_GenerateQualCollation(&querybuf, pk_coll);
 			querysep = ",";
@@ -1149,9 +1161,8 @@ ri_set(TriggerData *trigdata, bool is_set_null)
 			sprintf(paramname, "$%d", i + 1);
 			ri_GenerateQual(&qualbuf, qualsep,
 							paramname, pk_type,
-							riinfo->pf_eq_oprs[i],
-							attname, fk_type,
-							riinfo->fk_reftypes[i]);
+							riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT ? OID_ARRAY_ELEMCONTAINED_OP : riinfo->pf_eq_oprs[i], // XXX
+							attname, fk_type);
 			if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
 				ri_GenerateQualCollation(&querybuf, pk_coll);
 			querysep = ",";
@@ -1363,6 +1374,7 @@ RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
 	char		workmembuf[32];
 	int			spi_result;
 	SPIPlanPtr	qplan;
+	int 		each_elem;
 
 	riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
 
@@ -1450,30 +1462,25 @@ RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
 	quoteRelationName(pkrelname, pk_rel);
 	quoteRelationName(fkrelname, fk_rel);
 
-	if (riinfo->has_array)
-	{
-		appendStringInfo(&querybuf, " FROM ONLY %s fk", fkrelname);
-		for (int i = 0; i < riinfo->nkeys; i++)
-		{
-			if (riinfo->fk_reftypes[i] != FKCONSTR_REF_EACH_ELEMENT)
-				continue;
+	fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
+		"" : "ONLY ";
+	pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
+		"" : "ONLY ";
 
-			quoteOneName(fkattname,
-						 RIAttName(fk_rel, riinfo->fk_attnums[i]));
-			appendStringInfo(&querybuf,
-							 " CROSS JOIN LATERAL pg_catalog.unnest(fk.%s) a (e)",
-							 fkattname);
-		}
-		appendStringInfo(&querybuf,
-						 " LEFT OUTER JOIN ONLY %s pk ON",
-						 pkrelname);
+	for (each_elem = 0; each_elem < riinfo->nkeys; each_elem++)
+		if (riinfo->fk_reftypes[each_elem] == FKCONSTR_REF_EACH_ELEMENT)
+			break;
+
+	if (each_elem < riinfo->nkeys)
+	{
+		quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[each_elem]));
+		appendStringInfo(&querybuf, " FROM %s%s fk"
+						 " CROSS JOIN LATERAL pg_catalog.unnest(fk.%s)"
+						 " LEFT OUTER JOIN %s%s pk ON",
+						 fk_only, fkrelname, fkattname, pk_only, pkrelname);
 	}
 	else
 	{
-		fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
-			"" : "ONLY ";
-		pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
-			"" : "ONLY ";
 		appendStringInfo(&querybuf,
 						" FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
 						fk_only, fkrelname, pk_only, pkrelname);
@@ -1493,7 +1500,7 @@ RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
 		quoteOneName(pkattname + 3,
 					 RIAttName(pk_rel, riinfo->pk_attnums[i]));
 		if (riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT)
-			tmp = "a.e";
+			tmp = "unnest";
 		else
 		{
 			quoteOneName(fkattname + 3,
@@ -1503,8 +1510,7 @@ RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
 		ri_GenerateQual(&querybuf, sep,
 						pkattname, pk_type,
 						riinfo->pf_eq_oprs[i],
-						tmp, fk_type,
-						FKCONSTR_REF_PLAIN);
+						tmp, fk_type);
 		if (pk_coll != fk_coll)
 			ri_GenerateQualCollation(&querybuf, pk_coll);
 		sep = "AND";
@@ -1521,7 +1527,7 @@ RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
 	for (int i = 0; i < riinfo->nkeys; i++)
 	{
 		if (riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT)
-			appendStringInfo(&querybuf, "%sa.e IS NOT NULL", sep);
+			appendStringInfo(&querybuf, "%sunnest IS NOT NULL", sep);
 		else
 		{
 			quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
@@ -1743,9 +1749,8 @@ RI_PartitionRemove_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
 					 RIAttName(fk_rel, riinfo->fk_attnums[i]));
 		ri_GenerateQual(&querybuf, sep,
 						pkattname, pk_type,
-						riinfo->pf_eq_oprs[i],
-						fkattname, fk_type,
-						riinfo->fk_reftypes[i]);
+						riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT ? OID_ARRAY_ELEMCONTAINED_OP : riinfo->pf_eq_oprs[i], // XXX
+						fkattname, fk_type);
 		if (pk_coll != fk_coll)
 			ri_GenerateQualCollation(&querybuf, pk_coll);
 		sep = "AND";
@@ -1930,12 +1935,11 @@ ri_GenerateQual(StringInfo buf,
 				const char *sep,
 				const char *leftop, Oid leftoptype,
 				Oid opoid,
-				const char *rightop, Oid rightoptype,
-				char fkreftype)
+				const char *rightop, Oid rightoptype)
 {
 	appendStringInfo(buf, " %s ", sep);
 	generate_operator_clause(buf, leftop, leftoptype, opoid,
-							 rightop, rightoptype, fkreftype);
+							 rightop, rightoptype);
 }
 
 /*
@@ -2192,24 +2196,6 @@ ri_LoadConstraintInfo(Oid constraintOid)
 							   riinfo->ff_eq_oprs,
 							   riinfo->fk_reftypes);
 
-	/*
-	 * Fix up some stuff for Array Element Foreign Keys.  We need a has_array
-	 * flag indicating whether there's an array foreign key, and we want to
-	 * set ff_eq_oprs[i] to array_eq() for array columns, because that's what
-	 * makes sense for ri_KeysEqual, and we have no other use for ff_eq_oprs
-	 * in this module.  (If we did, substituting the array comparator at the
-	 * call point in ri_KeysEqual might be more appropriate.)
-	 */
-	riinfo->has_array = false;
-	for (int i = 0; i < riinfo->nkeys; i++)
-	{
-		if (riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT)
-		{
-			riinfo->has_array = true;
-			riinfo->ff_eq_oprs[i] = ARRAY_EQ_OP;
-		}
-	}
-
 	ReleaseSysCache(tup);
 
 	/*
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index 5300ce2276..85775d5435 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -11478,24 +11478,16 @@ void
 generate_operator_clause(StringInfo buf,
 						 const char *leftop, Oid leftoptype,
 						 Oid opoid,
-						 const char *rightop, Oid rightoptype,
-						 char fkreftype)
+						 const char *rightop, Oid rightoptype)
 {
 	HeapTuple	opertup;
 	Form_pg_operator operform;
 	char	   *oprname;
 	char	   *nspname;
-	Oid			oproid;
 
-	/* Override operator with <<@ in case of FK array */
-	if(fkreftype == FKCONSTR_REF_EACH_ELEMENT)
-		oproid = OID_ARRAY_ELEMCONTAINED_OP;
-	else
-		oproid = opoid;
-
-	opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oproid));
+	opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
 	if (!HeapTupleIsValid(opertup))
-		elog(ERROR, "cache lookup failed for operator %u", oproid);
+		elog(ERROR, "cache lookup failed for operator %u", opoid);
 	operform = (Form_pg_operator) GETSTRUCT(opertup);
 	Assert(operform->oprkind == 'b');
 	oprname = NameStr(operform->oprname);
diff --git a/src/include/utils/builtins.h b/src/include/utils/builtins.h
index 36d36d57b7..27d2f2ffb3 100644
--- a/src/include/utils/builtins.h
+++ b/src/include/utils/builtins.h
@@ -68,8 +68,7 @@ extern char *quote_qualified_identifier(const char *qualifier,
 extern void generate_operator_clause(fmStringInfo buf,
 									 const char *leftop, Oid leftoptype,
 									 Oid opoid,
-									 const char *rightop, Oid rightoptype,
-									 char fkreftype);
+									 const char *rightop, Oid rightoptype);
 
 /* varchar.c */
 extern int	bpchartruelen(char *s, int len);
-- 
2.27.0

