From 0f5a5bd14ce2791f24f855f8176b470a0ba8884d Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" Date: Fri, 27 Jun 2025 11:46:16 +0200 Subject: [PATCH 3/3] Local variables pointing to path node used repeatedly In match_unsorted_outer() we create a materialize path for inner relation and pass it to try_nestloop_path repeatedly. Link and unlink the path to and from the local variable to keep track of it. --- src/backend/optimizer/path/joinpath.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c index 7aa8f5d799c..275fe9cfb58 100644 --- a/src/backend/optimizer/path/joinpath.c +++ b/src/backend/optimizer/path/joinpath.c @@ -1892,12 +1892,14 @@ match_unsorted_outer(PlannerInfo *root, /* * Consider materializing the cheapest inner path, unless * enable_material is off or the path in question materializes its - * output anyway. + * output anyway. Link the path to a local reference so that it won't + * be freed by add_path if the surrounding nest path is freed by + * add_path. It will get freed if not used later. */ if (enable_material && inner_cheapest_total != NULL && !ExecMaterializesOutput(inner_cheapest_total->pathtype)) - matpath = (Path *) - create_material_path(innerrel, inner_cheapest_total); + link_path(&matpath, + (Path *) create_material_path(innerrel, inner_cheapest_total)); } foreach(lc1, outerrel->pathlist) @@ -2013,6 +2015,10 @@ match_unsorted_outer(PlannerInfo *root, false); } + /* Materialized inner path won't be used anymore. Unlink it */ + if (matpath) + unlink_path(&matpath, 0, false, true); + /* * Consider partial nestloop and mergejoin plan if outerrel has any * partial path and the joinrel is parallel-safe. However, we can't -- 2.50.0