Skip to content

Commit

Permalink
refactor: prepare code to so it's easy to add avg
Browse files Browse the repository at this point in the history
Signed-off-by: Andres Taylor <[email protected]>
  • Loading branch information
systay committed Nov 1, 2023
1 parent fcad7d0 commit 5c578d0
Showing 1 changed file with 29 additions and 20 deletions.
49 changes: 29 additions & 20 deletions go/vt/vtgate/planbuilder/operators/phases.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func (p Phase) act(ctx *plancontext.PlanningContext, op ops.Operator) (ops.Opera
case delegateAggregation:
return enableDelegateAggregation(ctx, op)
case addAggrOrdering:
return addOrderBysForAggregations(ctx, op)
return addOrderingForAllAggregations(ctx, op)
case cleanOutPerfDistinct:
return removePerformanceDistinctAboveRoute(ctx, op)
case subquerySettling:
Expand Down Expand Up @@ -120,41 +120,50 @@ func enableDelegateAggregation(ctx *plancontext.PlanningContext, op ops.Operator
return addColumnsToInput(ctx, op)
}

func addOrderBysForAggregations(ctx *plancontext.PlanningContext, root ops.Operator) (ops.Operator, error) {
// addOrderingForAllAggregations is run we have pushed down Aggregators as far down as possible.
func addOrderingForAllAggregations(ctx *plancontext.PlanningContext, root ops.Operator) (ops.Operator, error) {
visitor := func(in ops.Operator, _ semantics.TableSet, isRoot bool) (ops.Operator, *rewrite.ApplyResult, error) {
aggrOp, ok := in.(*Aggregator)
if !ok {
return in, rewrite.SameTree, nil
}

var res *rewrite.ApplyResult

requireOrdering, err := needsOrdering(ctx, aggrOp)
if err != nil {
return nil, nil, err
}
if !requireOrdering {
return in, rewrite.SameTree, nil
}
orderBys := slice.Map(aggrOp.Grouping, func(from GroupBy) ops.OrderBy {
return from.AsOrderBy()
})
if aggrOp.DistinctExpr != nil {
orderBys = append(orderBys, ops.OrderBy{
Inner: &sqlparser.Order{
Expr: aggrOp.DistinctExpr,
},
SimplifiedExpr: aggrOp.DistinctExpr,
})
}
aggrOp.Source = &Ordering{
Source: aggrOp.Source,
Order: orderBys,

if requireOrdering {
addOrderingFor(aggrOp)
res = rewrite.NewTree("added ordering before aggregation", in)
}
return in, rewrite.NewTree("added ordering before aggregation", in), nil

return in, res, nil
}

return rewrite.BottomUp(root, TableID, visitor, stopAtRoute)
}

func addOrderingFor(aggrOp *Aggregator) {
orderBys := slice.Map(aggrOp.Grouping, func(from GroupBy) ops.OrderBy {
return from.AsOrderBy()
})
if aggrOp.DistinctExpr != nil {
orderBys = append(orderBys, ops.OrderBy{
Inner: &sqlparser.Order{
Expr: aggrOp.DistinctExpr,
},
SimplifiedExpr: aggrOp.DistinctExpr,
})
}
aggrOp.Source = &Ordering{
Source: aggrOp.Source,
Order: orderBys,
}
}

func needsOrdering(ctx *plancontext.PlanningContext, in *Aggregator) (bool, error) {
requiredOrder := slice.Map(in.Grouping, func(from GroupBy) sqlparser.Expr {
return from.SimplifiedExpr
Expand Down

0 comments on commit 5c578d0

Please sign in to comment.