From 50e49c51901000f622a95afac6c09474749f5040 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonatan=20K=C5=82osko?= Date: Mon, 4 Dec 2023 14:15:27 +0700 Subject: [PATCH] Handle duplicate column names in Table.Reader implementation --- lib/postgrex/result.ex | 12 +++++++++++- test/query_test.exs | 9 +++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/postgrex/result.ex b/lib/postgrex/result.ex index 3cca08ac..a9fb0df5 100644 --- a/lib/postgrex/result.ex +++ b/lib/postgrex/result.ex @@ -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 diff --git a/test/query_test.exs b/test/query_test.exs index f188eac2..98ad9dcd 100644 --- a/test/query_test.exs +++ b/test/query_test.exs @@ -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