Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions enginetest/queries/order_by_group_by_queries.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,4 +346,50 @@ var OrderByGroupByScriptTests = []ScriptTest{
},
},
},
{
// https://github.com/dolthub/dolt/issues/9605
Name: "Order by CTE column wrapped by parentheses",
SetUpScript: []string{
"create table tree_data (id int not null, parent_id int, primary key (id), constraint foreign key (parent_id) references tree_data (id));",
"insert into tree_data values (1,null),(2,null),(3,null),(4,1),(5,4),(6,3)",
},
Assertions: []ScriptTestAssertion{
{
Query: `WITH RECURSIVE __rank_table(id, parent_id, rank_order) AS (SELECT tree_data.id,
tree_data.parent_id,
row_number() OVER (
ORDER BY tree_data.id) AS rank_order
FROM tree_data),
__tree(tree_depth, tree_path, tree_ordering, tree_pk) AS
(SELECT 0,
cast(concat("", id, "") AS char(1000)),
cast(concat("", lpad(concat(T.rank_order, ""), 20, "0")) AS char(1000)),
T.id
FROM __rank_table T
WHERE T.parent_id IS NULL
UNION ALL SELECT __tree.tree_depth + 1,
concat(__tree.tree_path, T2.id, ""),
concat(__tree.tree_ordering, lpad(concat(T2.rank_order, ""), 20, "0")),
T2.id
FROM __tree,
__rank_table T2
WHERE __tree.tree_pk = T2.parent_id)
SELECT __tree.tree_depth AS tree_depth,
tree_data.id,
tree_data.parent_id
FROM __tree,
tree_data
WHERE __tree.tree_pk = tree_data.id
ORDER BY (__tree.tree_depth) DESC;`,
Expected: []sql.Row{
{2, 5, 4},
{1, 4, 1},
{1, 6, 3},
{0, 1, nil},
{0, 2, nil},
{0, 3, nil},
},
},
},
},
}
10 changes: 7 additions & 3 deletions sql/planbuilder/orderby.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,12 @@ func (b *Builder) analyzeOrderBy(fromScope, projScope *scope, order ast.OrderBy)
case ast.DescScr:
descending = true
}

switch e := o.Expr.(type) {
expr := o.Expr
// unwrap expressions wrapped by parentheses
if parensExpr, ok := expr.(*ast.ParenExpr); ok {
expr = parensExpr.Expr
}
switch e := expr.(type) {
case *ast.ColName:
// check for projection alias first
dbName := strings.ToLower(e.Qualifier.DbQualifier.String())
Expand Down Expand Up @@ -147,7 +151,7 @@ func (b *Builder) analyzeOrderBy(fromScope, projScope *scope, order ast.OrderBy)
// has to have been ref'd already
id, ok := fromScope.getExpr(e.String(), true)
if !ok {
err := fmt.Errorf("faild to ref aggregate expression: %s", e.String())
err := fmt.Errorf("failed to ref aggregate expression: %s", e.String())
b.handleErr(err)
}
return expression.NewGetField(int(id), e.Type(), e.String(), e.IsNullable()), transform.NewTree, nil
Expand Down
Loading