diff --git a/planner/core/logical_plan_builder.go b/planner/core/logical_plan_builder.go index 9e5d33608ff2d..aa16c1d83bc71 100644 --- a/planner/core/logical_plan_builder.go +++ b/planner/core/logical_plan_builder.go @@ -7021,9 +7021,9 @@ func (b *PlanBuilder) buildRecursiveCTE(ctx context.Context, cte ast.ResultSetNo // 1. Handle the WITH clause if exists. if x.With != nil { l := len(b.outerCTEs) + sw := x.With defer func() { b.outerCTEs = b.outerCTEs[:l] - sw := x.With x.With = sw }() err := b.buildWith(ctx, x.With) diff --git a/planner/core/testdata/plan_suite_in.json b/planner/core/testdata/plan_suite_in.json index e33f3fb93869e..96721b1c2aa81 100644 --- a/planner/core/testdata/plan_suite_in.json +++ b/planner/core/testdata/plan_suite_in.json @@ -629,6 +629,7 @@ { "name": "TestSingleConsumerCTE", "cases": [ + "with base1 as (WITH RECURSIVE cte(a) AS (with tmp as (select 1 as a) SELECT a from tmp UNION SELECT a+1 FROM cte) SELECT * FROM cte) select * from base1; -- issue #43318", "with cte as (select 1) select * from cte; -- inline cte", "with cte1 as (select 1), cte2 as (select 2) select * from cte1 union select * from cte2; -- inline cte1, cte2", "with cte as (select 1) select * from cte union select * from cte; -- cannot be inlined", diff --git a/planner/core/testdata/plan_suite_out.json b/planner/core/testdata/plan_suite_out.json index 5d55764635ffe..fbe75c850bbd1 100644 --- a/planner/core/testdata/plan_suite_out.json +++ b/planner/core/testdata/plan_suite_out.json @@ -2125,6 +2125,18 @@ { "Name": "TestSingleConsumerCTE", "Cases": [ + { + "SQL": "with base1 as (WITH RECURSIVE cte(a) AS (with tmp as (select 1 as a) SELECT a from tmp UNION SELECT a+1 FROM cte) SELECT * FROM cte) select * from base1; -- issue #43318", + "Plan": [ + "CTEFullScan 2.00 root CTE:cte data:CTE_3", + "CTE_3 2.00 root Recursive CTE", + "├─Projection(Seed Part) 1.00 root 1->Column#15", + "│ └─TableDual 1.00 root rows:1", + "└─Projection(Recursive Part) 1.00 root cast(plus(Column#16, 1), bigint(1) BINARY)->Column#18", + " └─CTETable 1.00 root Scan on CTE_3" + ], + "Warning": null + }, { "SQL": "with cte as (select 1) select * from cte; -- inline cte", "Plan": [