Skip to content

Commit

Permalink
Fix ORDER BY clauses in ARRAY subqueries
Browse files Browse the repository at this point in the history
  • Loading branch information
exAspArk committed Feb 12, 2025
1 parent 93d9430 commit 1b3a1e1
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
7 changes: 7 additions & 0 deletions src/query_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -839,6 +839,13 @@ func TestHandleQuery(t *testing.T) {
"values": {"10", "bemidb"},
},

// ORDER BY
"SELECT ARRAY(SELECT 1 FROM pg_enum ORDER BY enumsortorder) AS array": {
"description": {"array"},
"types": {Uint32ToString(pgtype.Int4ArrayOID)},
"values": {"{}"},
},

// Table alias
"SELECT pg_shadow.usename FROM pg_shadow": {
"description": {"usename"},
Expand Down
14 changes: 11 additions & 3 deletions src/query_remapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -391,11 +391,9 @@ func (remapper *QueryRemapper) remapJoinExpressions(selectStatement *pgQuery.Sel
node.GetJoinExpr().Quals = remapper.remapTypeCastsInNode(node.GetJoinExpr().Quals) // recursion

// DuckDB doesn't support non-INNER JOINs with ON clauses that reference columns from outer tables:
//
// SELECT (
// SELECT 1 AS test FROM (SELECT 1 AS inner_val) LEFT JOIN (SELECT NULL) ON inner_val = *outer_val*
// ) FROM (SELECT 1 AS outer_val)
//
// > "Non-inner join on correlated columns not supported"
//
// References:
Expand Down Expand Up @@ -457,8 +455,18 @@ func (remapper *QueryRemapper) remapSelect(selectStatement *pgQuery.SelectStmt,
remapper.remapCaseExpressions(selectStatement, indentLevel) // recursive
} else if targetNode.GetResTarget().Val.GetSubLink() != nil {
// Nested SELECT
subSelect := targetNode.GetResTarget().Val.GetSubLink().Subselect.GetSelectStmt()
subLink := targetNode.GetResTarget().Val.GetSubLink()
subSelect := subLink.Subselect.GetSelectStmt()
remapper.remapSelectStatement(subSelect, indentLevel+1) // recursive

// DuckDB doesn't work with ORDER BY in ARRAY subqueries:
// SELECT ARRAY(SELECT 1 FROM pg_enum ORDER BY enumsortorder)
// > Referenced column "enumsortorder" not found in FROM clause!
//
// Remove ORDER BY from ARRAY subqueries
if subLink.SubLinkType == pgQuery.SubLinkType_ARRAY_SUBLINK && subSelect.SortClause != nil {
subSelect.SortClause = nil
}
} else if targetNode.GetResTarget().Val.GetCoalesceExpr() != nil {
// COALESCE(value1, value2, ...)
coalesceExpr := targetNode.GetResTarget().Val.GetCoalesceExpr()
Expand Down

0 comments on commit 1b3a1e1

Please sign in to comment.