|
| 1 | +// Copyright 2023 PingCAP, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package core |
| 16 | + |
| 17 | +import "github.com/pingcap/tidb/planner/funcdep" |
| 18 | + |
| 19 | +// RecheckCTE fills the IsOuterMostCTE field for CTEs. |
| 20 | +// It's a temp solution to before we fully use the Sequence to optimize the CTEs. |
| 21 | +// This func checks whether the CTE is referenced only by the main query or not. |
| 22 | +func RecheckCTE(p LogicalPlan) { |
| 23 | + visited := funcdep.NewFastIntSet() |
| 24 | + findCTEs(p, &visited, true) |
| 25 | +} |
| 26 | + |
| 27 | +func findCTEs( |
| 28 | + p LogicalPlan, |
| 29 | + visited *funcdep.FastIntSet, |
| 30 | + isRootTree bool, |
| 31 | +) { |
| 32 | + if cteReader, ok := p.(*LogicalCTE); ok { |
| 33 | + cte := cteReader.cte |
| 34 | + if !isRootTree { |
| 35 | + // Set it to false since it's referenced by other CTEs. |
| 36 | + cte.isOuterMostCTE = false |
| 37 | + } |
| 38 | + if visited.Has(cte.IDForStorage) { |
| 39 | + return |
| 40 | + } |
| 41 | + visited.Insert(cte.IDForStorage) |
| 42 | + // Set it when we meet it first time. |
| 43 | + cte.isOuterMostCTE = isRootTree |
| 44 | + findCTEs(cte.seedPartLogicalPlan, visited, false) |
| 45 | + if cte.recursivePartLogicalPlan != nil { |
| 46 | + findCTEs(cte.recursivePartLogicalPlan, visited, false) |
| 47 | + } |
| 48 | + return |
| 49 | + } |
| 50 | + for _, child := range p.Children() { |
| 51 | + findCTEs(child, visited, isRootTree) |
| 52 | + } |
| 53 | +} |
0 commit comments