Skip to content

Commit 6a19649

Browse files
authored
Merge pull request #3131 from dolthub/angela/cte
Unwrap ParenExpr when evaluating OrderBy expressions
2 parents f45e28b + bf332d9 commit 6a19649

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

enginetest/queries/order_by_group_by_queries.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,4 +346,26 @@ var OrderByGroupByScriptTests = []ScriptTest{
346346
},
347347
},
348348
},
349+
{
350+
// https://github.com/dolthub/dolt/issues/9605
351+
Name: "Order by wrapped by parentheses",
352+
SetUpScript: []string{
353+
"create table t(i int, j int)",
354+
"insert into t values(2,4),(0,7),(9,10),(4,3)",
355+
},
356+
Assertions: []ScriptTestAssertion{
357+
{
358+
Query: "with cte(i) as (select i from t) select * from cte order by (i)",
359+
Expected: []sql.Row{{0}, {2}, {4}, {9}},
360+
},
361+
{
362+
Query: "with cte(i) as (select i from t) select * from cte order by (((i)))",
363+
Expected: []sql.Row{{0}, {2}, {4}, {9}},
364+
},
365+
{
366+
Query: "select * from t order by (i * 10 + j)",
367+
Expected: []sql.Row{{0, 7}, {2, 4}, {4, 3}, {9, 10}},
368+
},
369+
},
370+
},
349371
}

sql/planbuilder/orderby.go

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@ func (b *Builder) analyzeOrderBy(fromScope, projScope *scope, order ast.OrderBy)
4646
case ast.DescScr:
4747
descending = true
4848
}
49-
50-
switch e := o.Expr.(type) {
49+
expr := unwrapExpression(o.Expr)
50+
switch e := expr.(type) {
5151
case *ast.ColName:
5252
// check for projection alias first
5353
dbName := strings.ToLower(e.Qualifier.DbQualifier.String())
@@ -147,7 +147,7 @@ func (b *Builder) analyzeOrderBy(fromScope, projScope *scope, order ast.OrderBy)
147147
// has to have been ref'd already
148148
id, ok := fromScope.getExpr(e.String(), true)
149149
if !ok {
150-
err := fmt.Errorf("faild to ref aggregate expression: %s", e.String())
150+
err := fmt.Errorf("failed to ref aggregate expression: %s", e.String())
151151
b.handleErr(err)
152152
}
153153
return expression.NewGetField(int(id), e.Type(), e.String(), e.IsNullable()), transform.NewTree, nil
@@ -226,3 +226,13 @@ func (b *Builder) buildOrderBy(inScope, orderByScope *scope) {
226226
inScope.node = sort
227227
return
228228
}
229+
230+
// unwrapExpression unwraps expressions wrapped in ParenExpr (parenthesis)
231+
// TODO: consider moving this function to a different file or package since it seems like it could be used in other
232+
// places
233+
func unwrapExpression(expr ast.Expr) ast.Expr {
234+
if parensExpr, ok := expr.(*ast.ParenExpr); ok {
235+
return unwrapExpression(parensExpr.Expr)
236+
}
237+
return expr
238+
}

0 commit comments

Comments
 (0)