New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
plan: covert max/min to Limit + Sort operators #5105
Merged
Merged
Changes from 11 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
80843d1
WIP
shenli 18a2740
plan: Eliminate aggregate
shenli 2865f96
WIP
shenli a8ff7c5
Fix CI
shenli 7f74424
plan: Fix build
shenli ebdcc45
plan: Add test case
shenli f872e8c
plan: Clean up
shenli f4dfda1
Merge branch 'master' into maxmin2
shenli 32a32e6
Merge branch 'master' into maxmin2
shenli 0396709
Address commentst
shenli 1304e52
plan: Address comments
shenli 7b0c123
Address comments
shenli 177df3a
Address comment
shenli c4546b5
Fix build
shenli 2714824
plan: Add a test case
shenli 374c04e
Merge branch 'master' into maxmin2
hanfei1991 0ef910e
plan: Fix plan package test build
shenli a201c49
Merge branch 'master' into maxmin2
coocood File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
// Copyright 2017 PingCAP, Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// // Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package plan | ||
|
||
import ( | ||
"github.com/pingcap/tidb/ast" | ||
"github.com/pingcap/tidb/context" | ||
) | ||
|
||
// aggEliminater tries to elimiate max/min aggregate function. | ||
// For SQL like `select max(c) from t;`, we could optimize it to `select c from t order by c desc limit 1;`. | ||
// For SQL like `select min(c) from t;`, we could optimize it to `select c from t order by c limit 1;`. | ||
type aggEliminater struct { | ||
ctx context.Context | ||
} | ||
|
||
func (a *aggEliminater) optimize(p LogicalPlan, ctx context.Context) (LogicalPlan, error) { | ||
a.ctx = ctx | ||
return a.eliminateAgg(p), nil | ||
} | ||
|
||
// Try to convert max/min to Limit+Sort operators. | ||
func (a *aggEliminater) eliminateAgg(p LogicalPlan) LogicalPlan { | ||
if agg, ok := p.(*LogicalAggregation); ok { | ||
// We only consider case with single max/min function. | ||
if len(agg.AggFuncs) != 1 { | ||
return p | ||
} | ||
f := agg.AggFuncs[0] | ||
if f.GetName() != ast.AggFuncMax && f.GetName() != ast.AggFuncMin { | ||
return p | ||
} | ||
|
||
// Add Sort and Limit operators. | ||
// For max function, the sort order should be desc. | ||
desc := f.GetName() == ast.AggFuncMax | ||
// Compose Sort operator. | ||
sort := Sort{}.init(a.ctx) | ||
sort.ByItems = append(sort.ByItems, &ByItems{f.GetArgs()[0], desc}) | ||
sort.SetSchema(p.Children()[0].Schema().Clone()) | ||
setParentAndChildren(sort, p.Children()...) | ||
// Compose Limit operator. | ||
li := Limit{Count: 1}.init(a.ctx) | ||
li.SetSchema(sort.Schema().Clone()) | ||
setParentAndChildren(li, sort) | ||
|
||
// Add a projection operator here. | ||
// During topn_push_down, the sort/limit operator will be converted to a topn operator and the schema of sort/limit will be ignored. | ||
// So the schema of the LogicalAggregation will be lost. We add this projection operator to keep the schema unlost. | ||
// For SQL like `select * from t where v=(select min(t1.v) from t t1, t t2, t t3 where t1.id=t2.id and t2.id=t3.id and t1.id=t.id);`, | ||
// the min(t1.v) will be refered in the outer selection. So we should keep the schema from LogicalAggragation. | ||
proj := Projection{}.init(a.ctx) | ||
proj.Exprs = append(proj.Exprs, f.GetArgs()[0]) | ||
proj.SetSchema(p.Schema().Clone()) | ||
setParentAndChildren(proj, li) | ||
return proj | ||
} | ||
|
||
newChildren := make([]Plan, 0, len(p.Children())) | ||
for _, child := range p.Children() { | ||
newChild := a.eliminateAgg(child.(LogicalPlan)) | ||
newChildren = append(newChildren, newChild) | ||
} | ||
setParentAndChildren(p, newChildren...) | ||
return p | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -63,14 +63,24 @@ func (p *LogicalAggregation) collectGroupByColumns() { | |
func (b *planBuilder) buildAggregation(p LogicalPlan, aggFuncList []*ast.AggregateFuncExpr, gbyItems []expression.Expression) (LogicalPlan, map[int]int) { | ||
b.optFlag = b.optFlag | flagBuildKeyInfo | ||
b.optFlag = b.optFlag | flagAggregationOptimize | ||
eliminateAgg := len(gbyItems) == 0 | ||
|
||
agg := LogicalAggregation{AggFuncs: make([]aggregation.Aggregation, 0, len(aggFuncList))}.init(b.ctx) | ||
schema := expression.NewSchema(make([]*expression.Column, 0, len(aggFuncList)+p.Schema().Len())...) | ||
// aggIdxMap maps the old index to new index after applying common aggregation functions elimination. | ||
aggIndexMap := make(map[int]int) | ||
for i, aggFunc := range aggFuncList { | ||
if eliminateAgg && (aggFunc.F != ast.AggFuncMax) && (aggFunc.F != ast.AggFuncMin) { | ||
eliminateAgg = false | ||
} | ||
var newArgList []expression.Expression | ||
for _, arg := range aggFunc.Args { | ||
if eliminateAgg { | ||
_, ok := arg.(*ast.ColumnNameExpr) | ||
if !ok { | ||
eliminateAgg = false | ||
} | ||
} | ||
newArg, np, err := b.rewrite(arg, p, nil, true) | ||
if err != nil { | ||
b.err = errors.Trace(err) | ||
|
@@ -109,6 +119,10 @@ func (b *planBuilder) buildAggregation(p LogicalPlan, aggFuncList []*ast.Aggrega | |
agg.GroupByItems = gbyItems | ||
agg.SetSchema(schema) | ||
agg.collectGroupByColumns() | ||
if eliminateAgg { | ||
b.optFlag = b.optFlag | flagAggEliminate | ||
b.optFlag = b.optFlag | flagPushDownTopN | ||
} | ||
return agg, aggIndexMap | ||
} | ||
|
||
|
@@ -1491,6 +1505,9 @@ func (b *planBuilder) buildSelect(sel *ast.SelectStmt) LogicalPlan { | |
if b.err != nil { | ||
return nil | ||
} | ||
if b.optFlag&flagAggEliminate == flagAggEliminate { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. convert to topn will be no worse than original. it's ok not to do this |
||
b.optFlag = b.optFlag &^ flagAggregationOptimize | ||
} | ||
} | ||
var oldLen int | ||
p, oldLen = b.buildProjection(p, sel.Fields.Fields, totalMap) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This optimize is too complex. If we have an aggregate, we set flag eliminateAgg. That's enough.