Skip to content

Commit

Permalink
Fix potential memleak with singleton CTE subplan
Browse files Browse the repository at this point in the history
  • Loading branch information
Vyacheslav Kompan committed Nov 21, 2023
1 parent d5ff703 commit 55c56c7
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
17 changes: 14 additions & 3 deletions src/backend/optimizer/path/allpaths.c
Original file line number Diff line number Diff line change
Expand Up @@ -2140,9 +2140,20 @@ set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
* shared plan with another SegmentGeneral node. Thus, we should avoid
* sharing SegmentGeneral subplans.
*/
subplan = (cteplaninfo->subplan->flow->locustype != CdbLocusType_SegmentGeneral) ?
share_prepared_plan(cteroot, cteplaninfo->subplan) :
(Plan *) copyObject(cteplaninfo->subplan);
if (cteplaninfo->subplan->flow->locustype != CdbLocusType_SegmentGeneral)
{
subplan = share_prepared_plan(cteroot, cteplaninfo->subplan);
}
else
{
/*
* If we are not sharing and subplan was created just now, use it.
* Otherwise, make a copy of it to avoid construction of DAG
* instead of a tree.
*/
if (subplan == NULL)
subplan = (Plan *) copyObject(cteplaninfo->subplan);
}

subroot = cteplaninfo->subroot;
}
Expand Down
4 changes: 2 additions & 2 deletions src/test/regress/expected/with.out
Original file line number Diff line number Diff line change
Expand Up @@ -2290,9 +2290,9 @@ DROP TABLE IF EXISTS r;
NOTICE: table "r" does not exist, skipping
--end_ignore
CREATE TABLE d (a int, b int) DISTRIBUTED BY (a);
INSERT INTO d VALUES (1,2),(2,3);
INSERT INTO d VALUES ( 1, 2 ),( 2, 3 );
CREATE TABLE r (a int, b int) DISTRIBUTED REPLICATED;
INSERT INTO r VALUES (1,2),(3,4);
INSERT INTO r VALUES ( 1, 2 ),( 3, 4 );
EXPLAIN (COSTS off)
WITH cte AS (
SELECT count(*) a FROM r
Expand Down
4 changes: 2 additions & 2 deletions src/test/regress/sql/with.sql
Original file line number Diff line number Diff line change
Expand Up @@ -1093,9 +1093,9 @@ DROP TABLE IF EXISTS r;
--end_ignore

CREATE TABLE d (a int, b int) DISTRIBUTED BY (a);
INSERT INTO d VALUES (1,2),(2,3);
INSERT INTO d VALUES ( 1, 2 ),( 2, 3 );
CREATE TABLE r (a int, b int) DISTRIBUTED REPLICATED;
INSERT INTO r VALUES (1,2),(3,4);
INSERT INTO r VALUES ( 1, 2 ),( 3, 4 );

EXPLAIN (COSTS off)
WITH cte AS (
Expand Down

0 comments on commit 55c56c7

Please sign in to comment.