Skip to content

Commit 018ba1b

Browse files
committed
Avoid duplicate order_by with distinct, closes #318
1 parent 2d90ef3 commit 018ba1b

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

lib/ecto/adapters/postgres/connection.ex

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -505,10 +505,13 @@ if Code.ensure_loaded?(Postgrex) do
505505
defp order_by(%{order_bys: []}, _distinct, _sources), do: []
506506
defp order_by(%{order_bys: order_bys} = query, distinct, sources) do
507507
order_bys = Enum.flat_map(order_bys, & &1.expr)
508-
[" ORDER BY " |
509-
intersperse_map(distinct ++ order_bys, ", ", &order_by_expr(&1, sources, query))]
508+
order_bys = order_by_concat(distinct, order_bys)
509+
[" ORDER BY " | intersperse_map(order_bys, ", ", &order_by_expr(&1, sources, query))]
510510
end
511511

512+
defp order_by_concat([head | left], [head | right]), do: [head | order_by_concat(left, right)]
513+
defp order_by_concat(left, right), do: left ++ right
514+
512515
defp order_by_expr({dir, expr}, sources, query) do
513516
str = expr(expr, sources, query)
514517

test/ecto/adapters/postgres_test.exs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,9 @@ defmodule Ecto.Adapters.PostgresTest do
309309
query = Schema |> order_by([r], [r.y]) |> distinct([r], desc: r.x) |> select([r], r.x) |> plan()
310310
assert all(query) == ~s{SELECT DISTINCT ON (s0."x") s0."x" FROM "schema" AS s0 ORDER BY s0."x" DESC, s0."y"}
311311

312+
query = Schema |> order_by([r], desc: r.x) |> distinct([r], desc: r.x) |> select([r], r.x) |> plan()
313+
assert all(query) == ~s{SELECT DISTINCT ON (s0."x") s0."x" FROM "schema" AS s0 ORDER BY s0."x" DESC}
314+
312315
query = Schema |> order_by([r], [r.y]) |> distinct([r], desc_nulls_last: r.x) |> select([r], r.x) |> plan()
313316
assert all(query) == ~s{SELECT DISTINCT ON (s0."x") s0."x" FROM "schema" AS s0 ORDER BY s0."x" DESC NULLS LAST, s0."y"}
314317
end

0 commit comments

Comments
 (0)