From 512fde187fa67174573dd78a9f758f3c8e125098 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 20/30] FK: Exclude ONLY scans of partitioned parents from
 starjoin dimensions

A foreign key referencing a partitioned table is recorded against the
parent, so a query joining ONLY the parent still matches the foreign
key.  But a partitioned table stores no rows itself, so ONLY scans an
empty relation, and the join removes every fact row instead of
preserving it.

Skip a dimension whose range table entry is a partitioned table without
inheritance.  Joins to the whole partitioned table never qualified, as
the planner ignores foreign keys referencing inheritance parents, and
direct joins to leaf partitions are not affected.

Update STARJOINS.md.  Add starjoin_fk_only, checking the row counts,
that the ONLY parent no longer qualifies, and that a leaf partition
still does.
---
 STARJOINS.md                                  | 15 +++-
 src/backend/optimizer/plan/initsplan.c        | 10 ++-
 .../regress/expected/starjoin_fk_only.out     | 82 +++++++++++++++++++
 src/test/regress/parallel_schedule            |  2 +-
 src/test/regress/sql/starjoin_fk_only.sql     | 61 ++++++++++++++
 5 files changed, 166 insertions(+), 4 deletions(-)
 create mode 100644 src/test/regress/expected/starjoin_fk_only.out
 create mode 100644 src/test/regress/sql/starjoin_fk_only.sql

diff --git a/STARJOINS.md b/STARJOINS.md
index dbce403494f..d070ebee587 100644
--- a/STARJOINS.md
+++ b/STARJOINS.md
@@ -270,7 +270,17 @@ fact row matches exactly one row of the dimension, and that the
 dimension can be joined to the fact at any point of the join search.
 The fact has to be a base relation too.
 
-1. The dimension is a plain base relation (`RELOPT_BASEREL`).
+1. The dimension is a plain base relation (`RELOPT_BASEREL`), not an
+   ONLY scan of a partitioned table.
+
+   A foreign key referencing a partitioned table is recorded against the
+   parent, so a query joining ONLY the parent still matches the foreign
+   key.  But a partitioned table stores no rows itself, so the join
+   would remove every fact row instead of preserving it.  Joins to the
+   whole partitioned table never qualify, as the referenced relation has
+   to be scanned without inheritance (see the conditions inherited from
+   foreign key matching).  Direct joins to leaf partitions are not
+   affected.
 
 2. All join columns on the fact are NOT NULL.
 
@@ -566,3 +576,6 @@ the plans, the planning cost, or the regression tests.
     index, and a nondeterministic index collation that separately breaks
     the existence and the uniqueness proof, where only the native
     comparison qualifies.
+  - starjoin_fk_only: an ONLY scan of the referenced partitioned parent
+    matches no rows and does not qualify, while an ONLY scan of a
+    directly referenced leaf partition does.
diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c
index ad1ea341e32..a9e0f7e4899 100644
--- a/src/backend/optimizer/plan/initsplan.c
+++ b/src/backend/optimizer/plan/initsplan.c
@@ -4368,7 +4368,8 @@ has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel, RelOptInfo *dim_rel)
  * via an equality condition matching a non-temporal foreign key, satisfying
  * these conditions:
  *
- *	1. The dimension is a plain base relation (RELOPT_BASEREL).
+ *	1. The dimension is a plain base relation (RELOPT_BASEREL), not an ONLY
+ *	   scan of a partitioned table.
  *
  *	2. All join columns on the fact are NOT NULL.
  *
@@ -4491,6 +4492,7 @@ generate_starjoin_clusters(PlannerInfo *root)
 		{
 			Index		d = (Index) lfirst_int(lc2);
 			RelOptInfo *dim_rel = root->simple_rel_array[d];
+			RangeTblEntry *dim_rte = root->simple_rte_array[d];
 			ListCell   *lc3;
 			bool		ok = true;
 			int			r;
@@ -4499,8 +4501,12 @@ generate_starjoin_clusters(PlannerInfo *root)
 			if (dim_rel == NULL || dim_rel->reloptkind != RELOPT_BASEREL)
 				continue;
 
+			/* ONLY on a partitioned table cannot see any referenced rows. */
+			if (dim_rte->relkind == RELKIND_PARTITIONED_TABLE && !dim_rte->inh)
+				continue;
+
 			/* Sampling may remove the row referenced by the foreign key. */
-			if (root->simple_rte_array[d]->tablesample != NULL)
+			if (dim_rte->tablesample != NULL)
 				continue;
 
 			/* No local restriction quals on the dimension. */
diff --git a/src/test/regress/expected/starjoin_fk_only.out b/src/test/regress/expected/starjoin_fk_only.out
new file mode 100644
index 00000000000..750275b7b81
--- /dev/null
+++ b/src/test/regress/expected/starjoin_fk_only.out
@@ -0,0 +1,82 @@
+-- A satisfied FK references rows in the partitions, but JOIN ONLY
+-- scans the empty parent. It must not count as a single-row lookup.
+\set ON_ERROR_STOP on
+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 TEMP TABLE partdim (k int PRIMARY KEY) PARTITION BY RANGE (k);
+CREATE TEMP TABLE partdim_default PARTITION OF partdim DEFAULT;
+INSERT INTO partdim VALUES (1);
+CREATE TEMP TABLE fact (
+  k int NOT NULL CONSTRAINT partdim_fk REFERENCES partdim,
+  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 1, 1, 1, 1, 1 FROM generate_series(1, 100);
+SELECT $$SELECT count(*) FROM fact f JOIN ONLY partdim p ON f.k = p.k
+  JOIN ONLY d1 ON f.a = d1.id JOIN ONLY d2 ON f.b = d2.id
+  JOIN ONLY d3 ON f.c = d3.id JOIN ONLY d4 ON f.d = d4.id$$ AS q_only \gset
+SELECT replace(:'q_only', 'ONLY partdim', 'partdim') AS q_all \gset
+-- 100 facts; 100 matches with the partition, none with ONLY.
+SELECT (SELECT count(*) FROM fact) AS facts, (:q_all) AS all_matches, (:q_only) AS only_matches;
+ facts | all_matches | only_matches 
+-------+-------------+--------------
+   100 |         100 |            0
+(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;
+$$;
+SELECT pg_temp.dimensions_qualify(:'q_only') AS only_parent_qualifies;
+ only_parent_qualifies 
+-----------------------
+ f
+(1 row)
+
+SET LOCAL enable_starjoin_ordering = off;
+SELECT pg_temp.dimensions_qualify(:'q_only') AS qualifies_with_feature_off;
+ qualifies_with_feature_off 
+----------------------------
+ f
+(1 row)
+
+SET LOCAL enable_starjoin_ordering = on;
+ALTER TABLE fact DROP CONSTRAINT partdim_fk;
+SELECT pg_temp.dimensions_qualify(:'q_only') AS qualifies_without_partdim_fk;
+ qualifies_without_partdim_fk 
+------------------------------
+ f
+(1 row)
+
+-- ONLY is fine for a directly referenced leaf partition or ordinary table.
+ALTER TABLE fact ADD FOREIGN KEY (k) REFERENCES partdim_default;
+SELECT replace(:'q_only', 'ONLY partdim p', 'ONLY partdim_default p') AS q_leaf \gset
+SELECT (:q_leaf) AS leaf_matches, pg_temp.dimensions_qualify(:'q_leaf') AS leaf_qualifies;
+ leaf_matches | leaf_qualifies 
+--------------+----------------
+          100 | t
+(1 row)
+
+ROLLBACK;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index 012d42a5415..c76847b6406 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_fk_opclass 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_fk_only 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_only.sql b/src/test/regress/sql/starjoin_fk_only.sql
new file mode 100644
index 00000000000..abefd5fa455
--- /dev/null
+++ b/src/test/regress/sql/starjoin_fk_only.sql
@@ -0,0 +1,61 @@
+-- A satisfied FK references rows in the partitions, but JOIN ONLY
+-- scans the empty parent. It must not count as a single-row lookup.
+\set ON_ERROR_STOP on
+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 TEMP TABLE partdim (k int PRIMARY KEY) PARTITION BY RANGE (k);
+CREATE TEMP TABLE partdim_default PARTITION OF partdim DEFAULT;
+INSERT INTO partdim VALUES (1);
+CREATE TEMP TABLE fact (
+  k int NOT NULL CONSTRAINT partdim_fk REFERENCES partdim,
+  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 1, 1, 1, 1, 1 FROM generate_series(1, 100);
+
+SELECT $$SELECT count(*) FROM fact f JOIN ONLY partdim p ON f.k = p.k
+  JOIN ONLY d1 ON f.a = d1.id JOIN ONLY d2 ON f.b = d2.id
+  JOIN ONLY d3 ON f.c = d3.id JOIN ONLY d4 ON f.d = d4.id$$ AS q_only \gset
+SELECT replace(:'q_only', 'ONLY partdim', 'partdim') AS q_all \gset
+-- 100 facts; 100 matches with the partition, none with ONLY.
+SELECT (SELECT count(*) FROM fact) AS facts, (:q_all) AS all_matches, (:q_only) AS only_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;
+$$;
+SELECT pg_temp.dimensions_qualify(:'q_only') AS only_parent_qualifies;
+SET LOCAL enable_starjoin_ordering = off;
+SELECT pg_temp.dimensions_qualify(:'q_only') AS qualifies_with_feature_off;
+SET LOCAL enable_starjoin_ordering = on;
+ALTER TABLE fact DROP CONSTRAINT partdim_fk;
+SELECT pg_temp.dimensions_qualify(:'q_only') AS qualifies_without_partdim_fk;
+
+-- ONLY is fine for a directly referenced leaf partition or ordinary table.
+ALTER TABLE fact ADD FOREIGN KEY (k) REFERENCES partdim_default;
+SELECT replace(:'q_only', 'ONLY partdim p', 'ONLY partdim_default p') AS q_leaf \gset
+SELECT (:q_leaf) AS leaf_matches, pg_temp.dimensions_qualify(:'q_leaf') AS leaf_qualifies;
+ROLLBACK;
-- 
2.56.1

