-
Notifications
You must be signed in to change notification settings - Fork 2.1k
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
Add support for AVG on sharded queries #14419
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f636c6f
refactor: clean up code to make it more readable
systay 0c849ca
refactor: prepare code to so it's easy to add avg
systay a0506a1
planbuilder: split avg aggregations into sum/count
systay dcc1866
planbuilder tests: add more avg examples
systay 4ae9bd7
test: add end2end tests with AVG
systay bae0ece
planbuilder: add defensive checks
systay File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
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 |
---|---|---|
|
@@ -34,22 +34,33 @@ func tryPushAggregator(ctx *plancontext.PlanningContext, aggregator *Aggregator) | |
if aggregator.Pushed { | ||
return aggregator, rewrite.SameTree, nil | ||
} | ||
|
||
// this rewrite is always valid, and we should do it whenever possible | ||
if route, ok := aggregator.Source.(*Route); ok && (route.IsSingleShard() || overlappingUniqueVindex(ctx, aggregator.Grouping)) { | ||
return rewrite.Swap(aggregator, route, "push down aggregation under route - remove original") | ||
} | ||
|
||
// other rewrites require us to have reached this phase before we can consider them | ||
if !reachedPhase(ctx, delegateAggregation) { | ||
return aggregator, rewrite.SameTree, nil | ||
} | ||
|
||
// if we have not yet been able to push this aggregation down, | ||
// we need to turn AVG into SUM/COUNT to support this over a sharded keyspace | ||
if needAvgBreaking(aggregator.Aggregations) { | ||
return splitAvgAggregations(ctx, aggregator) | ||
} | ||
|
||
switch src := aggregator.Source.(type) { | ||
case *Route: | ||
// if we have a single sharded route, we can push it down | ||
output, applyResult, err = pushAggregationThroughRoute(ctx, aggregator, src) | ||
case *ApplyJoin: | ||
if reachedPhase(ctx, delegateAggregation) { | ||
output, applyResult, err = pushAggregationThroughJoin(ctx, aggregator, src) | ||
} | ||
output, applyResult, err = pushAggregationThroughJoin(ctx, aggregator, src) | ||
case *Filter: | ||
if reachedPhase(ctx, delegateAggregation) { | ||
output, applyResult, err = pushAggregationThroughFilter(ctx, aggregator, src) | ||
} | ||
output, applyResult, err = pushAggregationThroughFilter(ctx, aggregator, src) | ||
case *SubQueryContainer: | ||
if reachedPhase(ctx, delegateAggregation) { | ||
output, applyResult, err = pushAggregationThroughSubquery(ctx, aggregator, src) | ||
} | ||
output, applyResult, err = pushAggregationThroughSubquery(ctx, aggregator, src) | ||
default: | ||
return aggregator, rewrite.SameTree, nil | ||
} | ||
|
@@ -135,15 +146,6 @@ func pushAggregationThroughRoute( | |
aggregator *Aggregator, | ||
route *Route, | ||
) (ops.Operator, *rewrite.ApplyResult, error) { | ||
// If the route is single-shard, or we are grouping by sharding keys, we can just push down the aggregation | ||
if route.IsSingleShard() || overlappingUniqueVindex(ctx, aggregator.Grouping) { | ||
return rewrite.Swap(aggregator, route, "push down aggregation under route - remove original") | ||
} | ||
|
||
if !reachedPhase(ctx, delegateAggregation) { | ||
return nil, nil, nil | ||
} | ||
|
||
// Create a new aggregator to be placed below the route. | ||
aggrBelowRoute := aggregator.SplitAggregatorBelowRoute(route.Inputs()) | ||
aggrBelowRoute.Aggregations = nil | ||
|
@@ -806,3 +808,74 @@ func initColReUse(size int) []int { | |
} | ||
|
||
func extractExpr(expr *sqlparser.AliasedExpr) sqlparser.Expr { return expr.Expr } | ||
|
||
func needAvgBreaking(aggrs []Aggr) bool { | ||
for _, aggr := range aggrs { | ||
if aggr.OpCode == opcode.AggregateAvg { | ||
return true | ||
} | ||
} | ||
return false | ||
} | ||
|
||
// splitAvgAggregations takes an aggregator that has AVG aggregations in it and splits | ||
// these into sum/count expressions that can be spread out to shards | ||
func splitAvgAggregations(ctx *plancontext.PlanningContext, aggr *Aggregator) (ops.Operator, *rewrite.ApplyResult, error) { | ||
proj := newAliasedProjection(aggr) | ||
|
||
var columns []*sqlparser.AliasedExpr | ||
var aggregations []Aggr | ||
|
||
for offset, col := range aggr.Columns { | ||
avg, ok := col.Expr.(*sqlparser.Avg) | ||
if !ok { | ||
proj.addColumnWithoutPushing(ctx, col, false /* addToGroupBy */) | ||
continue | ||
} | ||
|
||
if avg.Distinct { | ||
panic(vterrors.VT12001("AVG(distinct <>)")) | ||
} | ||
|
||
// We have an AVG that we need to split | ||
sumExpr := &sqlparser.Sum{Arg: avg.Arg} | ||
countExpr := &sqlparser.Count{Args: []sqlparser.Expr{avg.Arg}} | ||
calcExpr := &sqlparser.BinaryExpr{ | ||
Operator: sqlparser.DivOp, | ||
Left: sumExpr, | ||
Right: countExpr, | ||
} | ||
Comment on lines
+843
to
+847
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. ❤️ |
||
|
||
outputColumn := aeWrap(col.Expr) | ||
outputColumn.As = sqlparser.NewIdentifierCI(col.ColumnName()) | ||
_, err := proj.addUnexploredExpr(sqlparser.CloneRefOfAliasedExpr(col), calcExpr) | ||
if err != nil { | ||
return nil, nil, err | ||
} | ||
col.Expr = sumExpr | ||
found := false | ||
for aggrOffset, aggregation := range aggr.Aggregations { | ||
if offset == aggregation.ColOffset { | ||
// We have found the AVG column. We'll change it to SUM, and then we add a COUNT as well | ||
aggr.Aggregations[aggrOffset].OpCode = opcode.AggregateSum | ||
|
||
countExprAlias := aeWrap(countExpr) | ||
countAggr := NewAggr(opcode.AggregateCount, countExpr, countExprAlias, sqlparser.String(countExpr)) | ||
countAggr.ColOffset = len(aggr.Columns) + len(columns) | ||
aggregations = append(aggregations, countAggr) | ||
columns = append(columns, countExprAlias) | ||
found = true | ||
break // no need to search the remaining aggregations | ||
systay marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
if !found { | ||
// if we get here, it's because we didn't find the aggregation. Something is wrong | ||
panic(vterrors.VT13001("no aggregation pointing to this column was found")) | ||
} | ||
} | ||
|
||
aggr.Columns = append(aggr.Columns, columns...) | ||
aggr.Aggregations = append(aggr.Aggregations, aggregations...) | ||
|
||
return proj, rewrite.NewTree("split avg aggregation", proj), nil | ||
} |
Oops, something went wrong.
Oops, something went wrong.
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.
Just for my understanding, supporting this would require loading all the distinct values from the shard, and then perform the avg calculation on the vtgate layer.
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.
I'm not sure. Have not spent enough time thinking about it to come up with a solution, which is why I just fail here.