diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c index 52ebdd90fcb..5a0ecd80a07 100644 --- a/src/backend/optimizer/path/costsize.c +++ b/src/backend/optimizer/path/costsize.c @@ -4436,10 +4436,24 @@ cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan) { QualCost sp_cost; - /* Figure any cost for evaluating the testexpr */ + /* + * Figure any cost for evaluating the testexpr. + * + * Usually, SubPlan nodes are built very early, before we have constructed + * any RelOptInfos for the parent query level, which means the parent root + * does not yet contain enough information to safely consult statistics. + * Therefore, we pass root as NULL here. cost_qual_eval() is already + * well-equipped to handle a NULL root. + * + * One exception is SubPlan nodes built for the initplans of MIN/MAX + * aggregates from indexes (cf. SS_make_initplan_from_plan). In this + * case, having a NULL root is safe because testexpr will be NULL. + * Besides, an initplan will by definition not consult anything from the + * parent plan. + */ cost_qual_eval(&sp_cost, make_ands_implicit((Expr *) subplan->testexpr), - root); + NULL); if (subplan->useHashTable) { diff --git a/src/test/regress/expected/subselect.out b/src/test/regress/expected/subselect.out index 6c1fb2bfdbb..e41d31b3084 100644 --- a/src/test/regress/expected/subselect.out +++ b/src/test/regress/expected/subselect.out @@ -773,6 +773,25 @@ select (select (a.*)::text) from view_a a; (42) (1 row) +-- +-- Test case for bug #19037: no relation entry for relid N +-- +explain (costs off) +select (1 = any(array_agg(f1))) = any (select false) from int4_tbl; + QUERY PLAN +---------------------------- + Aggregate + -> Seq Scan on int4_tbl + SubPlan 1 + -> Result +(4 rows) + +select (1 = any(array_agg(f1))) = any (select false) from int4_tbl; + ?column? +---------- + t +(1 row) + -- -- Check that whole-row Vars reading the result of a subselect don't include -- any junk columns therein diff --git a/src/test/regress/sql/subselect.sql b/src/test/regress/sql/subselect.sql index e5a562c3f5d..fb0a901a516 100644 --- a/src/test/regress/sql/subselect.sql +++ b/src/test/regress/sql/subselect.sql @@ -412,6 +412,15 @@ select (select view_a) from view_a; select (select (select view_a)) from view_a; select (select (a.*)::text) from view_a a; +-- +-- Test case for bug #19037: no relation entry for relid N +-- + +explain (costs off) +select (1 = any(array_agg(f1))) = any (select false) from int4_tbl; + +select (1 = any(array_agg(f1))) = any (select false) from int4_tbl; + -- -- Check that whole-row Vars reading the result of a subselect don't include -- any junk columns therein