Skip to content

Commit

Permalink
Wrap arguments of Append in a subquery if it contains ORDER or LIMIT
Browse files Browse the repository at this point in the history
  • Loading branch information
xitology committed Apr 18, 2024
1 parent 0dc8c40 commit 0a9950c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
35 changes: 35 additions & 0 deletions docs/src/test/nodes.md
Original file line number Diff line number Diff line change
Expand Up @@ -1426,6 +1426,41 @@ nested subqueries.
) AS "observation_2"
=#

Arguments of `Append` may contain `ORDER BY` or `LIMIT` clauses, which
must be wrapped in a nested subquery.

q = From(measurement) |>
Order(Get.measurement_date) |>
Select(Get.person_id, :date => Get.measurement_date) |>
Append(From(observation) |>
Define(:date => Get.observation_date) |>
Limit(1))

print(render(q))
#=>
SELECT
"measurement_2"."person_id",
"measurement_2"."date"
FROM (
SELECT
"measurement_1"."person_id",
"measurement_1"."measurement_date" AS "date"
FROM "measurement" AS "measurement_1"
ORDER BY "measurement_1"."measurement_date"
) AS "measurement_2"
UNION ALL
SELECT
"observation_2"."person_id",
"observation_2"."date"
FROM (
SELECT
"observation_1"."person_id",
"observation_1"."observation_date" AS "date"
FROM "observation" AS "observation_1"
FETCH FIRST 1 ROW ONLY
) AS "observation_2"
=#

An `Append` without any queries can be created explicitly.

q = Append(args = [])
Expand Down
8 changes: 4 additions & 4 deletions src/translate.jl
Original file line number Diff line number Diff line change
Expand Up @@ -365,10 +365,10 @@ function assemble(n::AppendNode, ctx)
if a.name !== a_name
a_name = :union
end
if @dissect(a.clause, SELECT(args = args)) && aligned_columns(urefs, repl, args)
if @dissect(a.clause, over |> SELECT(args = args)) && aligned_columns(urefs, repl, args) && !@dissect(over, ORDER() || LIMIT())
push!(cs, a.clause)
continue
elseif !@dissect(a.clause, SELECT() || UNION())
elseif !@dissect(a.clause, SELECT() || UNION() || ORDER() || LIMIT())
alias = nothing
tail = a.clause
else
Expand Down Expand Up @@ -666,10 +666,10 @@ function assemble(n::IterateNode, ctx)
end
cs = SQLClause[]
for (arg, a) in (n.over => left, n.iterator => right)
if @dissect(a.clause, SELECT(args = args)) && aligned_columns(urefs, left.repl, args)
if @dissect(a.clause, over |> SELECT(args = args)) && aligned_columns(urefs, repl, args) && !@dissect(over, ORDER() || LIMIT())
push!(cs, a.clause)
continue
elseif !@dissect(a.clause, SELECT() || UNION())
elseif !@dissect(a.clause, SELECT() || UNION() || ORDER() || LIMIT())
alias = nothing
tail = a.clause
else
Expand Down

0 comments on commit 0a9950c

Please sign in to comment.