From 7add1ad78d0f2dfe0bc67f4abd921a2185a45f9a Mon Sep 17 00:00:00 2001 From: Ti Chi Robot Date: Mon, 24 Apr 2023 20:10:40 +0800 Subject: [PATCH] planbuilder: Keep with clause when build recursive cte (#43362) (#43372) close pingcap/tidb#43318 --- planner/core/casetest/testdata/plan_suite_in.json | 1 + planner/core/casetest/testdata/plan_suite_out.json | 12 ++++++++++++ planner/core/logical_plan_builder.go | 2 +- 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/planner/core/casetest/testdata/plan_suite_in.json b/planner/core/casetest/testdata/plan_suite_in.json index 4bcbb0c64fbee..9621e57e9db88 100644 --- a/planner/core/casetest/testdata/plan_suite_in.json +++ b/planner/core/casetest/testdata/plan_suite_in.json @@ -796,6 +796,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/casetest/testdata/plan_suite_out.json b/planner/core/casetest/testdata/plan_suite_out.json index 5bb3668a85275..8710357fc8f16 100644 --- a/planner/core/casetest/testdata/plan_suite_out.json +++ b/planner/core/casetest/testdata/plan_suite_out.json @@ -3750,6 +3750,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": [ diff --git a/planner/core/logical_plan_builder.go b/planner/core/logical_plan_builder.go index 18f1d602d9ac1..62b35605ed8af 100644 --- a/planner/core/logical_plan_builder.go +++ b/planner/core/logical_plan_builder.go @@ -7145,9 +7145,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)