Skip to content

Commit f0a1759

Browse files
authored
Merge pull request #244 from matt-beanland/fix/combination-order-not-sql-precedence
fix: apply each combination part to the whole of what precedes it
2 parents 81e8acf + 5ae3a4d commit f0a1759

1 file changed

Lines changed: 12 additions & 0 deletions

File tree

lib/query.ex

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,18 @@ defmodule AshSql.Query do
2222
_domain \\ nil
2323
) do
2424
Enum.reduce(combination_of, subquery(first), fn {type, combination_of}, query ->
25+
# Each part applies to the result of everything before it. Appending
26+
# straight onto the accumulated query would build one flat chain of set
27+
# operations, and SQL's own precedence would then decide the grouping —
28+
# `INTERSECT` binds tighter than `UNION`/`EXCEPT`, so a part could end up
29+
# applied to its predecessor rather than to the whole. Nesting what has
30+
# accumulated keeps the order the parts were given in.
31+
query =
32+
case query do
33+
%Ecto.SubQuery{} -> query
34+
query -> subquery(query)
35+
end
36+
2537
case type do
2638
:union ->
2739
Ecto.Query.union(query, ^combination_of)

0 commit comments

Comments
 (0)