From 30b3ed29e600ef6258211ff239b6dafe64629399 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Wed, 25 Nov 2026 13:47:05 +0100
Subject: [PATCH v7 19/30] FK: Check operator semantics before relaxing
 starjoin collations

The relaxed collation check assumed that equality under a deterministic
collation implies equality under any other collation.  That holds for
the built-in string equalities, which compare deterministic strings
byte-wise, but the equality operator of a foreign key need not compare
the original strings.  For example, an operator class that lower-cases
its inputs distinguishes I from dotless i in English, and matches them
in Turkish.  Such joins were treated as single-row lookups even when
they matched no row or two rows per fact row.

With different collations, keep the implications only when both the
operator family of the unique index and the equality function of the
foreign key are built-in string comparisons, and otherwise require the
same collation.  Check both, as extensions can add cross-type operators
to a built-in family.  This changes only the starjoin eligibility, not
the foreign key selectivity or enforcement.

Update STARJOINS.md.  Add starjoin_fk_opclass, using a case-folding
operator class through a loose qual and an equivalence class, a mismatch
with just the backing index, and a nondeterministic index collation that
separately breaks the existence and the uniqueness proof.  Only the
native comparison qualifies.
---
 STARJOINS.md                                  |  25 ++-
 src/backend/optimizer/plan/initsplan.c        |  58 ++++++-
 .../regress/expected/starjoin_fk_opclass.out  | 161 ++++++++++++++++++
 .../expected/starjoin_fk_opclass_1.out        |   7 +
 src/test/regress/parallel_schedule            |   2 +-
 src/test/regress/sql/starjoin_fk_opclass.sql  | 131 ++++++++++++++
 6 files changed, 370 insertions(+), 14 deletions(-)
 create mode 100644 src/test/regress/expected/starjoin_fk_opclass.out
 create mode 100644 src/test/regress/expected/starjoin_fk_opclass_1.out
 create mode 100644 src/test/regress/sql/starjoin_fk_opclass.sql

diff --git a/STARJOINS.md b/STARJOINS.md
index 1d194d405aa..dbce403494f 100644
--- a/STARJOINS.md
+++ b/STARJOINS.md
@@ -387,7 +387,19 @@ still single-row lookups, such as a join under "C" to a "C" key with a
 case-insensitive unique index.  `starjoin_equality_implies` accepts
 collations that agree on equality, and a deterministic first collation,
 as equality under a deterministic collation is byte-wise equality, which
-implies equality under any collation.
+implies equality under any collation.  That holds for the built-in
+string equalities, which compare strings under a deterministic collation
+byte-wise, but the equality operator of a foreign key need not compare
+the original strings.  An operator class that lower-cases its inputs,
+for example, distinguishes I from dotless i in English and matches them
+in Turkish, while English and a nondeterministic Turkish collation
+disagree on how to fold I.  So with different collations,
+`starjoin_equality_implies` accepts the implication only if both the
+operator family of the unique index and the equality function of the
+foreign key are built-in string comparisons, and otherwise the
+collations have to be the same.  Both are checked, as extensions can add
+cross-type operators to a built-in family.  Identical collations need no
+such proof.
 
 These checks change only which relations are treated as dimensions, not
 foreign key enforcement or selectivity estimation.
@@ -529,9 +541,9 @@ the plans, the planning cost, or the regression tests.
   point, so the search takes noticeably more memory.  So the suites
   compare the planning memory of the search and of the forced order,
   accepting up to 10% more, with four other dimensions that always
-  qualify to widen the difference.  The starjoin_fk_collation suite
-  needs a UTF8 database with ICU collations, and has an alternative
-  output for when it's skipped.
+  qualify to widen the difference.  The starjoin_fk_collation and
+  starjoin_fk_opclass suites need a UTF8 database with ICU, and have
+  alternative outputs for when they're skipped.
   - starjoin_fk_overlap: a composite foreign key qualifies alone and
     together with a short one, whichever is examined first (varying both
     the creation and the name order), while a lone short key and two
@@ -549,3 +561,8 @@ the plans, the planning cost, or the regression tests.
     key with a case-insensitive unique index, where joins under either
     collation qualify, while an accent-insensitive join can match two
     rows and does not.
+  - starjoin_fk_opclass: a case-folding operator class through a loose
+    qual and an equivalence class, a mismatch with just the backing
+    index, and a nondeterministic index collation that separately breaks
+    the existence and the uniqueness proof, where only the native
+    comparison qualifies.
diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c
index fb2d8749338..ad1ea341e32 100644
--- a/src/backend/optimizer/plan/initsplan.c
+++ b/src/backend/optimizer/plan/initsplan.c
@@ -17,6 +17,7 @@
 #include "access/nbtree.h"
 #include "access/sysattr.h"
 #include "catalog/pg_constraint.h"
+#include "catalog/pg_opfamily.h"
 #include "catalog/pg_type.h"
 #include "nodes/makefuncs.h"
 #include "nodes/nodeFuncs.h"
@@ -32,6 +33,7 @@
 #include "optimizer/restrictinfo.h"
 #include "parser/analyze.h"
 #include "rewrite/rewriteManip.h"
+#include "utils/fmgroids.h"
 #include "utils/lsyscache.h"
 #include "utils/rel.h"
 #include "utils/typcache.h"
@@ -151,7 +153,8 @@ static void check_hashjoinable(RestrictInfo *restrictinfo);
 static void check_memoizable(RestrictInfo *restrictinfo);
 static bool has_extra_starjoin_quals(PlannerInfo *root, RelOptInfo *dim_rel,
 									 ForeignKeyOptInfo *fkinfo);
-static bool starjoin_equality_implies(Oid coll1, Oid coll2);
+static bool starjoin_equality_implies(Oid coll1, Oid coll2, Oid opfamily,
+									  Oid eqop);
 static bool starjoin_fk_collations_match(PlannerInfo *root,
 										 RelOptInfo *dim_rel,
 										 ForeignKeyOptInfo *fkinfo);
@@ -4202,13 +4205,43 @@ has_extra_starjoin_quals(PlannerInfo *root, RelOptInfo *dim_rel,
 }
 
 /*
- * Does equality under coll1 imply equality under coll2?  A deterministic
- * collation treats only byte-wise equal strings as equal, and those are
- * equal under any collation.
+ * Does equality under coll1 imply equality under coll2, for the FK's
+ * equality operator eqop and the unique index's operator family?
+ *
+ * A deterministic collation treats only byte-wise equal strings as equal,
+ * and the built-in string equalities treat those as equal under any
+ * collation.  But an operator could first transform its inputs using the
+ * collation (e.g. lower-case them), so with different collations trust only
+ * the built-in string families and equality functions.  Check both, because
+ * extensions can add cross-type operators to a built-in family.
  */
 static bool
-starjoin_equality_implies(Oid coll1, Oid coll2)
+starjoin_equality_implies(Oid coll1, Oid coll2, Oid opfamily, Oid eqop)
 {
+	if (coll1 == coll2)
+		return true;
+
+	if (!OidIsValid(coll1) || !OidIsValid(coll2))
+		return false;
+
+	if (opfamily != TEXT_BTREE_FAM_OID &&
+		opfamily != TEXT_PATTERN_BTREE_FAM_OID &&
+		opfamily != BPCHAR_BTREE_FAM_OID &&
+		opfamily != BPCHAR_PATTERN_BTREE_FAM_OID)
+		return false;
+
+	switch (get_opcode(eqop))
+	{
+		case F_TEXTEQ:
+		case F_BPCHAREQ:
+		case F_NAMEEQ:
+		case F_NAMEEQTEXT:
+		case F_TEXTEQNAME:
+			break;
+		default:
+			return false;
+	}
+
 	if (collations_agree_on_equality(coll1, coll2))
 		return true;
 
@@ -4236,6 +4269,8 @@ starjoin_fk_collations_match(PlannerInfo *root, RelOptInfo *dim_rel,
 		{
 			AttrNumber	attno = index->indexkeys[j];
 			Oid			indcoll = index->indexcollations[j];
+			Oid			opfamily = index->opfamily[j];
+			Oid			eqop;
 			Oid			attcoll;
 			Oid			typid;
 			int32		typmod;
@@ -4254,14 +4289,17 @@ starjoin_fk_collations_match(PlannerInfo *root, RelOptInfo *dim_rel,
 			if (i == fkinfo->nkeys)
 				return false;
 
+			eqop = fkinfo->conpfeqop[i];
 			get_atttypetypmodcoll(dim_rte->relid, attno,
 								  &typid, &typmod, &attcoll);
 			if (fkinfo->eclass[i] != NULL)
 			{
 				Oid			joincoll = fkinfo->eclass[i]->ec_collation;
 
-				if (!starjoin_equality_implies(attcoll, joincoll) ||
-					!starjoin_equality_implies(joincoll, indcoll))
+				if (!starjoin_equality_implies(attcoll, joincoll,
+											   opfamily, eqop) ||
+					!starjoin_equality_implies(joincoll, indcoll,
+											   opfamily, eqop))
 					return false;
 			}
 			else
@@ -4271,8 +4309,10 @@ starjoin_fk_collations_match(PlannerInfo *root, RelOptInfo *dim_rel,
 					Oid			joincoll;
 
 					joincoll = exprInputCollation((Node *) rinfo->clause);
-					if (!starjoin_equality_implies(attcoll, joincoll) ||
-						!starjoin_equality_implies(joincoll, indcoll))
+					if (!starjoin_equality_implies(attcoll, joincoll,
+												   opfamily, eqop) ||
+						!starjoin_equality_implies(joincoll, indcoll,
+												   opfamily, eqop))
 						return false;
 				}
 			}
diff --git a/src/test/regress/expected/starjoin_fk_opclass.out b/src/test/regress/expected/starjoin_fk_opclass.out
new file mode 100644
index 00000000000..07d84723551
--- /dev/null
+++ b/src/test/regress/expected/starjoin_fk_opclass.out
@@ -0,0 +1,161 @@
+-- Starjoin lookup semantics with a collation-sensitive FK operator class
+\set ON_ERROR_STOP on
+SELECT getdatabaseencoding() <> 'UTF8' OR icu_unicode_version() IS NULL AS skip_test \gset
+\if :skip_test
+\echo 'SKIP: requires ICU and a UTF8 database'
+\quit
+\endif
+BEGIN;
+SET LOCAL geqo = off;
+SET LOCAL enable_starjoin_ordering = on;
+CREATE TEMP TABLE d1 (id int PRIMARY KEY);
+CREATE TEMP TABLE d2 (id int PRIMARY KEY);
+CREATE TEMP TABLE d3 (id int PRIMARY KEY);
+CREATE TEMP TABLE d4 (id int PRIMARY KEY);
+INSERT INTO d1 VALUES (1);
+INSERT INTO d2 VALUES (1);
+INSERT INTO d3 VALUES (1);
+INSERT INTO d4 VALUES (1);
+CREATE COLLATION pg_temp.en_det (provider = icu, locale = 'en', deterministic = true);
+CREATE COLLATION pg_temp.tr_det (provider = icu, locale = 'tr', deterministic = true);
+CREATE FUNCTION pg_temp.fold_cmp(a text, b text) RETURNS int
+LANGUAGE plpgsql IMMUTABLE STRICT AS $$
+BEGIN
+  RETURN bttextcmp(lower(a), lower(b));
+END;
+$$;
+-- Derive all five strategies from the same comparator. Keep the equality
+-- function non-inlinable so the join clause contains the actual FK operator.
+DO $$
+DECLARE
+  s record;
+BEGIN
+  FOR s IN SELECT * FROM (VALUES
+    ('fold_lt', '~<~', '<'), ('fold_le', '~<=~', '<='), ('fold_eq', '===', '='),
+    ('fold_ge', '~>=~', '>='), ('fold_gt', '~>~', '>')) v(fn, op, cmp)
+  LOOP
+    EXECUTE format('CREATE FUNCTION pg_temp.%I(text, text) RETURNS bool
+                    LANGUAGE plpgsql IMMUTABLE STRICT AS %L', s.fn,
+                   format('BEGIN RETURN pg_temp.fold_cmp($1, $2) %s 0; END;', s.cmp));
+    EXECUTE format('CREATE OPERATOR pg_temp.%s
+                    (LEFTARG = text, RIGHTARG = text, FUNCTION = pg_temp.%I)', s.op, s.fn);
+  END LOOP;
+END;
+$$;
+CREATE OPERATOR CLASS pg_temp.fold_ops FOR TYPE text USING btree AS
+  OPERATOR 1 pg_temp.~<~, OPERATOR 2 pg_temp.~<=~, OPERATOR 3 pg_temp.===,
+  OPERATOR 4 pg_temp.~>=~, OPERATOR 5 pg_temp.~>~, FUNCTION 1 pg_temp.fold_cmp(text, text);
+CREATE TEMP TABLE words (k text COLLATE pg_temp.en_det NOT NULL);
+CREATE UNIQUE INDEX words_key ON words (k pg_temp.fold_ops);
+INSERT INTO words VALUES ('I'), (U&'\0131'); -- dotless i
+CREATE TEMP TABLE fact (
+  k text COLLATE pg_temp.en_det NOT NULL CONSTRAINT words_fk REFERENCES words(k),
+  a int NOT NULL REFERENCES d1, b int NOT NULL REFERENCES d2,
+  c int NOT NULL REFERENCES d3, d int NOT NULL REFERENCES d4
+);
+INSERT INTO fact SELECT 'I', 1, 1, 1, 1 FROM generate_series(1, 100);
+ANALYZE fact, words;
+SELECT $$SELECT count(*) FROM fact f JOIN words w ON w.k OPERATOR(pg_temp.===) f.k
+  JOIN d1 ON f.a = d1.id JOIN d2 ON f.b = d2.id
+  JOIN d3 ON f.c = d3.id JOIN d4 ON f.d = d4.id$$ AS q_en \gset
+SELECT replace(:'q_en', 'w.k OPERATOR', 'w.k COLLATE pg_temp.tr_det OPERATOR') AS q_tr \gset
+-- 100 facts; 100 matches in English, 200 in Turkish.
+SELECT (SELECT count(*) FROM fact) AS facts, (:q_en) AS en_matches, (:q_tr) AS tr_matches;
+ facts | en_matches | tr_matches 
+-------+------------+------------
+   100 |        100 |        200
+(1 row)
+
+-- As in starjoin_fk_collation, the query lists the dimensions in canonical
+-- order. If all qualify, the search needs about as much planner memory as
+-- forcing that order; otherwise it builds additional joinrels.
+CREATE FUNCTION pg_temp.dimensions_qualify(query text) RETURNS bool
+LANGUAGE plpgsql SET join_collapse_limit = 8 AS $$
+DECLARE
+  plan json;
+  search_memory bigint;
+BEGIN
+  EXECUTE 'EXPLAIN ' || query;
+  EXECUTE 'EXPLAIN (MEMORY, FORMAT JSON) ' || query INTO plan;
+  search_memory := plan->0->'Planning'->>'Memory Used';
+  SET LOCAL join_collapse_limit = 1;
+  EXECUTE 'EXPLAIN (MEMORY, FORMAT JSON) ' || query INTO plan;
+  RETURN search_memory <= (plan->0->'Planning'->>'Memory Used')::bigint * 1.1;
+END;
+$$;
+-- The Turkish equality is not a single-row lookup.
+SELECT pg_temp.dimensions_qualify(:'q_en') AS en_qualifies,
+       pg_temp.dimensions_qualify(:'q_tr') AS tr_qualifies;
+ en_qualifies | tr_qualifies 
+--------------+--------------
+ t            | f
+(1 row)
+
+SET LOCAL enable_starjoin_ordering = off;
+SELECT pg_temp.dimensions_qualify(:'q_en') AS qualifies_with_feature_off;
+ qualifies_with_feature_off 
+----------------------------
+ f
+(1 row)
+
+SET LOCAL enable_starjoin_ordering = on;
+SAVEPOINT change_index;
+ALTER TABLE fact DROP CONSTRAINT words_fk;
+SELECT pg_temp.dimensions_qualify(:'q_en') AS qualifies_without_words_fk;
+ qualifies_without_words_fk 
+----------------------------
+ f
+(1 row)
+
+-- A mismatch with just the backing index can also invalidate uniqueness.
+DROP INDEX words_key;
+TRUNCATE words;
+CREATE UNIQUE INDEX words_key ON words (k COLLATE pg_temp.tr_det pg_temp.fold_ops);
+INSERT INTO words VALUES ('I'), ('i');
+ALTER TABLE fact ADD FOREIGN KEY (k) REFERENCES words(k);
+SELECT (:q_en) AS en_matches_with_tr_index,
+       pg_temp.dimensions_qualify(:'q_en') AS qualifies;
+ en_matches_with_tr_index | qualifies 
+--------------------------+-----------
+                      200 | f
+(1 row)
+
+ROLLBACK TO change_index;
+-- A deterministic source collation need not imply equality under a
+-- nondeterministic target, either. English folds 'I' to 'i'; Turkish
+-- folds it to dotless i. Test existence and uniqueness separately.
+ALTER TABLE fact DROP CONSTRAINT words_fk;
+DROP INDEX words_key;
+TRUNCATE words;
+CREATE COLLATION pg_temp.tr_nd (provider = icu, locale = 'tr', deterministic = false);
+CREATE UNIQUE INDEX words_key ON words (k COLLATE pg_temp.tr_nd pg_temp.fold_ops);
+INSERT INTO words VALUES ('I');
+UPDATE fact SET k = 'i';
+ALTER TABLE fact ADD FOREIGN KEY (k) REFERENCES words(k);
+SELECT replace(:'q_en', 'w.k OPERATOR', 'w.k COLLATE pg_temp.tr_nd OPERATOR') AS q_nd \gset
+SELECT (:q_nd) AS matches_under_index_collation,
+       pg_temp.dimensions_qualify(:'q_nd') AS qualifies;
+ matches_under_index_collation | qualifies 
+-------------------------------+-----------
+                             0 | f
+(1 row)
+
+INSERT INTO words VALUES ('i');
+SELECT (:q_en) AS matches_under_column_collation,
+       pg_temp.dimensions_qualify(:'q_en') AS qualifies;
+ matches_under_column_collation | qualifies 
+--------------------------------+-----------
+                            200 | f
+(1 row)
+
+ROLLBACK TO change_index;
+-- Match the same key through an equivalence class instead of a loose qual.
+ALTER OPERATOR pg_temp.=== (text, text) SET (COMMUTATOR = OPERATOR(pg_temp.===), MERGES);
+SELECT pg_temp.dimensions_qualify(:'q_en') AS ec_en_qualifies,
+       pg_temp.dimensions_qualify(:'q_tr') AS ec_tr_qualifies;
+ ec_en_qualifies | ec_tr_qualifies 
+-----------------+-----------------
+ t               | f
+(1 row)
+
+ROLLBACK;
diff --git a/src/test/regress/expected/starjoin_fk_opclass_1.out b/src/test/regress/expected/starjoin_fk_opclass_1.out
new file mode 100644
index 00000000000..68d01c253c0
--- /dev/null
+++ b/src/test/regress/expected/starjoin_fk_opclass_1.out
@@ -0,0 +1,7 @@
+-- Starjoin lookup semantics with a collation-sensitive FK operator class
+\set ON_ERROR_STOP on
+SELECT getdatabaseencoding() <> 'UTF8' OR icu_unicode_version() IS NULL AS skip_test \gset
+\if :skip_test
+\echo 'SKIP: requires ICU and a UTF8 database'
+SKIP: requires ICU and a UTF8 database
+\quit
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index d3f7384e811..012d42a5415 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -149,7 +149,7 @@ test: event_trigger_login
 test: fast_default
 
 # some tests for starjoin planning
-test: starjoin_planning starjoin_eager starjoin_plan starjoin_width starjoin_reproducers starjoin_other starjoin_sample starjoin_fk_overlap starjoin_fk_period starjoin_fk_collation starjoin_geqo
+test: starjoin_planning starjoin_eager starjoin_plan starjoin_width starjoin_reproducers starjoin_other starjoin_sample starjoin_fk_overlap starjoin_fk_period starjoin_fk_collation starjoin_fk_opclass starjoin_geqo
 
 # more expensive tests for starjoin planning (larger variants of earlier tests)
 # test: starjoin_eager_large starjoin_plan_large starjoin_width_large
diff --git a/src/test/regress/sql/starjoin_fk_opclass.sql b/src/test/regress/sql/starjoin_fk_opclass.sql
new file mode 100644
index 00000000000..27f703f1a57
--- /dev/null
+++ b/src/test/regress/sql/starjoin_fk_opclass.sql
@@ -0,0 +1,131 @@
+-- Starjoin lookup semantics with a collation-sensitive FK operator class
+\set ON_ERROR_STOP on
+SELECT getdatabaseencoding() <> 'UTF8' OR icu_unicode_version() IS NULL AS skip_test \gset
+\if :skip_test
+\echo 'SKIP: requires ICU and a UTF8 database'
+\quit
+\endif
+
+BEGIN;
+SET LOCAL geqo = off;
+SET LOCAL enable_starjoin_ordering = on;
+
+CREATE TEMP TABLE d1 (id int PRIMARY KEY);
+CREATE TEMP TABLE d2 (id int PRIMARY KEY);
+CREATE TEMP TABLE d3 (id int PRIMARY KEY);
+CREATE TEMP TABLE d4 (id int PRIMARY KEY);
+INSERT INTO d1 VALUES (1);
+INSERT INTO d2 VALUES (1);
+INSERT INTO d3 VALUES (1);
+INSERT INTO d4 VALUES (1);
+CREATE COLLATION pg_temp.en_det (provider = icu, locale = 'en', deterministic = true);
+CREATE COLLATION pg_temp.tr_det (provider = icu, locale = 'tr', deterministic = true);
+
+CREATE FUNCTION pg_temp.fold_cmp(a text, b text) RETURNS int
+LANGUAGE plpgsql IMMUTABLE STRICT AS $$
+BEGIN
+  RETURN bttextcmp(lower(a), lower(b));
+END;
+$$;
+-- Derive all five strategies from the same comparator. Keep the equality
+-- function non-inlinable so the join clause contains the actual FK operator.
+DO $$
+DECLARE
+  s record;
+BEGIN
+  FOR s IN SELECT * FROM (VALUES
+    ('fold_lt', '~<~', '<'), ('fold_le', '~<=~', '<='), ('fold_eq', '===', '='),
+    ('fold_ge', '~>=~', '>='), ('fold_gt', '~>~', '>')) v(fn, op, cmp)
+  LOOP
+    EXECUTE format('CREATE FUNCTION pg_temp.%I(text, text) RETURNS bool
+                    LANGUAGE plpgsql IMMUTABLE STRICT AS %L', s.fn,
+                   format('BEGIN RETURN pg_temp.fold_cmp($1, $2) %s 0; END;', s.cmp));
+    EXECUTE format('CREATE OPERATOR pg_temp.%s
+                    (LEFTARG = text, RIGHTARG = text, FUNCTION = pg_temp.%I)', s.op, s.fn);
+  END LOOP;
+END;
+$$;
+CREATE OPERATOR CLASS pg_temp.fold_ops FOR TYPE text USING btree AS
+  OPERATOR 1 pg_temp.~<~, OPERATOR 2 pg_temp.~<=~, OPERATOR 3 pg_temp.===,
+  OPERATOR 4 pg_temp.~>=~, OPERATOR 5 pg_temp.~>~, FUNCTION 1 pg_temp.fold_cmp(text, text);
+
+CREATE TEMP TABLE words (k text COLLATE pg_temp.en_det NOT NULL);
+CREATE UNIQUE INDEX words_key ON words (k pg_temp.fold_ops);
+INSERT INTO words VALUES ('I'), (U&'\0131'); -- dotless i
+CREATE TEMP TABLE fact (
+  k text COLLATE pg_temp.en_det NOT NULL CONSTRAINT words_fk REFERENCES words(k),
+  a int NOT NULL REFERENCES d1, b int NOT NULL REFERENCES d2,
+  c int NOT NULL REFERENCES d3, d int NOT NULL REFERENCES d4
+);
+INSERT INTO fact SELECT 'I', 1, 1, 1, 1 FROM generate_series(1, 100);
+ANALYZE fact, words;
+
+SELECT $$SELECT count(*) FROM fact f JOIN words w ON w.k OPERATOR(pg_temp.===) f.k
+  JOIN d1 ON f.a = d1.id JOIN d2 ON f.b = d2.id
+  JOIN d3 ON f.c = d3.id JOIN d4 ON f.d = d4.id$$ AS q_en \gset
+SELECT replace(:'q_en', 'w.k OPERATOR', 'w.k COLLATE pg_temp.tr_det OPERATOR') AS q_tr \gset
+-- 100 facts; 100 matches in English, 200 in Turkish.
+SELECT (SELECT count(*) FROM fact) AS facts, (:q_en) AS en_matches, (:q_tr) AS tr_matches;
+
+-- As in starjoin_fk_collation, the query lists the dimensions in canonical
+-- order. If all qualify, the search needs about as much planner memory as
+-- forcing that order; otherwise it builds additional joinrels.
+CREATE FUNCTION pg_temp.dimensions_qualify(query text) RETURNS bool
+LANGUAGE plpgsql SET join_collapse_limit = 8 AS $$
+DECLARE
+  plan json;
+  search_memory bigint;
+BEGIN
+  EXECUTE 'EXPLAIN ' || query;
+  EXECUTE 'EXPLAIN (MEMORY, FORMAT JSON) ' || query INTO plan;
+  search_memory := plan->0->'Planning'->>'Memory Used';
+  SET LOCAL join_collapse_limit = 1;
+  EXECUTE 'EXPLAIN (MEMORY, FORMAT JSON) ' || query INTO plan;
+  RETURN search_memory <= (plan->0->'Planning'->>'Memory Used')::bigint * 1.1;
+END;
+$$;
+-- The Turkish equality is not a single-row lookup.
+SELECT pg_temp.dimensions_qualify(:'q_en') AS en_qualifies,
+       pg_temp.dimensions_qualify(:'q_tr') AS tr_qualifies;
+SET LOCAL enable_starjoin_ordering = off;
+SELECT pg_temp.dimensions_qualify(:'q_en') AS qualifies_with_feature_off;
+SET LOCAL enable_starjoin_ordering = on;
+
+SAVEPOINT change_index;
+ALTER TABLE fact DROP CONSTRAINT words_fk;
+SELECT pg_temp.dimensions_qualify(:'q_en') AS qualifies_without_words_fk;
+
+-- A mismatch with just the backing index can also invalidate uniqueness.
+DROP INDEX words_key;
+TRUNCATE words;
+CREATE UNIQUE INDEX words_key ON words (k COLLATE pg_temp.tr_det pg_temp.fold_ops);
+INSERT INTO words VALUES ('I'), ('i');
+ALTER TABLE fact ADD FOREIGN KEY (k) REFERENCES words(k);
+SELECT (:q_en) AS en_matches_with_tr_index,
+       pg_temp.dimensions_qualify(:'q_en') AS qualifies;
+ROLLBACK TO change_index;
+
+-- A deterministic source collation need not imply equality under a
+-- nondeterministic target, either. English folds 'I' to 'i'; Turkish
+-- folds it to dotless i. Test existence and uniqueness separately.
+ALTER TABLE fact DROP CONSTRAINT words_fk;
+DROP INDEX words_key;
+TRUNCATE words;
+CREATE COLLATION pg_temp.tr_nd (provider = icu, locale = 'tr', deterministic = false);
+CREATE UNIQUE INDEX words_key ON words (k COLLATE pg_temp.tr_nd pg_temp.fold_ops);
+INSERT INTO words VALUES ('I');
+UPDATE fact SET k = 'i';
+ALTER TABLE fact ADD FOREIGN KEY (k) REFERENCES words(k);
+SELECT replace(:'q_en', 'w.k OPERATOR', 'w.k COLLATE pg_temp.tr_nd OPERATOR') AS q_nd \gset
+SELECT (:q_nd) AS matches_under_index_collation,
+       pg_temp.dimensions_qualify(:'q_nd') AS qualifies;
+INSERT INTO words VALUES ('i');
+SELECT (:q_en) AS matches_under_column_collation,
+       pg_temp.dimensions_qualify(:'q_en') AS qualifies;
+ROLLBACK TO change_index;
+
+-- Match the same key through an equivalence class instead of a loose qual.
+ALTER OPERATOR pg_temp.=== (text, text) SET (COMMUTATOR = OPERATOR(pg_temp.===), MERGES);
+SELECT pg_temp.dimensions_qualify(:'q_en') AS ec_en_qualifies,
+       pg_temp.dimensions_qualify(:'q_tr') AS ec_tr_qualifies;
+ROLLBACK;
-- 
2.56.1

