Skip to content

Commit

Permalink
Handle duplicate column names in Table.Reader implementation (#666)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonatanklosko authored Dec 4, 2023
1 parent ab4265e commit c6138a3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
12 changes: 11 additions & 1 deletion lib/postgrex/result.ex
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,17 @@ if Code.ensure_loaded?(Table.Reader) do
end

def init(result) do
{:rows, %{columns: result.columns, count: result.num_rows}, result.rows}
{columns, _} =
Enum.map_reduce(result.columns, %{}, fn column, counts ->
counts = Map.update(counts, column, 1, &(&1 + 1))

case counts[column] do
1 -> {column, counts}
n -> {"#{column}_#{n}", counts}
end
end)

{:rows, %{columns: columns, count: result.num_rows}, result.rows}
end
end
end
9 changes: 5 additions & 4 deletions test/query_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1715,19 +1715,20 @@ defmodule QueryTest do
assert {:ok, res} =
P.query(
context[:pid],
"SELECT * FROM (VALUES (1, 'a'), (2, 'b'), (3, 'c')) AS tab (x, y)",
"SELECT *, 1 AS x FROM (VALUES (1, 'a'), (2, 'b'), (3, 'c')) AS tab (x, y)",
[]
)

assert res |> Table.to_rows() |> Enum.to_list() == [
%{"x" => 1, "y" => "a"},
%{"x" => 2, "y" => "b"},
%{"x" => 3, "y" => "c"}
%{"x" => 1, "y" => "a", "x_2" => 1},
%{"x" => 2, "y" => "b", "x_2" => 1},
%{"x" => 3, "y" => "c", "x_2" => 1}
]

columns = Table.to_columns(res)
assert Enum.to_list(columns["x"]) == [1, 2, 3]
assert Enum.to_list(columns["y"]) == ["a", "b", "c"]
assert Enum.to_list(columns["x_2"]) == [1, 1, 1]

assert {_, %{count: 3}, _} = Table.Reader.init(res)
end
Expand Down

0 comments on commit c6138a3

Please sign in to comment.