Skip to content

Commit f515323

Browse files
committed
replace sort nodes through subquery aliases
1 parent 70b084e commit f515323

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

sql/analyzer/replace_sort.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,36 @@ func replaceIdxSortHelper(ctx *sql.Context, scope *plan.Scope, node sql.Node, so
154154
case *plan.Sort, *plan.IndexedTableAccess, *plan.ResolvedTable,
155155
*plan.Project, *plan.Filter, *plan.Limit, *plan.Offset, *plan.Distinct, *plan.TableAlias:
156156
newChildren[i], same, err = replaceIdxSortHelper(ctx, scope, child, sortNode)
157+
case *plan.SubqueryAlias:
158+
if sortNode == nil {
159+
continue
160+
}
161+
sortFields := sortNode.SortFields
162+
for i, sortField := range sortNode.SortFields {
163+
col, sameExpr, _ := transform.Expr(sortField.Column, func(e sql.Expression) (sql.Expression, transform.TreeIdentity, error) {
164+
if gt, ok := e.(*expression.GetField); ok {
165+
if gf, ok := c.ScopeMapping[gt.Id()]; ok {
166+
return gf, transform.NewTree, nil
167+
}
168+
}
169+
return e, transform.SameTree, nil
170+
})
171+
if !sameExpr {
172+
col2, _ := col.(sql.Expression2)
173+
sortFields[i] = sql.SortField{
174+
Column: col,
175+
Column2: col2,
176+
NullOrdering: sortField.NullOrdering,
177+
Order: sortField.Order,
178+
}
179+
}
180+
}
181+
newSort := sortNode.WithSortFields(sortFields)
182+
newSort.Child = c.Child
183+
if err != nil {
184+
return nil, transform.SameTree, err
185+
}
186+
newChildren[i], same, err = replaceIdxSortHelper(ctx, scope, child, newSort)
157187
case *plan.JoinNode:
158188
// It's (probably) not possible to have Sort as child of Join without Subquery/SubqueryAlias,
159189
// and in the case where there is a Subq/SQA it's taken care of through finalizeSubqueries

sql/plan/sort.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,12 @@ func (s *Sort) WithExpressions(exprs ...sql.Expression) (sql.Node, error) {
115115
return NewSort(fields, s.Child), nil
116116
}
117117

118+
func (s *Sort) WithSortFields(sf sql.SortFields) *Sort {
119+
ret := *s
120+
ret.SortFields = sf
121+
return &ret
122+
}
123+
118124
func (s *Sort) GetSortFields() sql.SortFields {
119125
return s.SortFields
120126
}

0 commit comments

Comments
 (0)