Skip to content

Commit

Permalink
cr suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
dkuku committed Nov 29, 2023
1 parent c12b7cf commit 59069f4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 23 deletions.
42 changes: 22 additions & 20 deletions lib/ayesql/runner.ex
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,33 @@ defmodule AyeSQL.Runner do

# Handles the result.
@doc false
@spec handle_result(map()) :: [map() | struct()]
@spec handle_result(map(), keyword()) :: [map() | struct()]
@spec handle_result(map()) :: [map() | struct() | keyword()]
@spec handle_result(map(), keyword()) :: [map() | struct() | keyword()]
def handle_result(result, options \\ [])

def handle_result(data, options) when is_list(options) do
handle_result(data, Map.new(options))
end

def handle_result(raw_data, %{into: :raw}) do
raw_data
end

def handle_result(%{columns: nil}, _options) do
[]
end

def handle_result(%{columns: columns, rows: rows} = raw_data, options) do
if options[:into] == :raw do
raw_data
else
atom_columns = Stream.map(columns, &String.to_atom/1)

rows
|> Stream.map(&Stream.zip(atom_columns, &1))
|> Enum.map(fn row ->
case options[:into] do
nil -> Enum.into(row, %{})
Map -> Enum.into(row, %{})
Keyword -> Enum.into(row, [])
enum when enum == [] or enum == %{} -> Enum.into(row, enum)
struct -> struct(struct, row)
end
end)
end
def handle_result(%{columns: columns, rows: rows}, options) do
atom_columns = Stream.map(columns, &String.to_atom/1)

rows
|> Stream.map(&Stream.zip(atom_columns, &1))
|> Enum.map(fn row ->
case options[:into] do
struct when is_struct(struct) -> struct(struct, row)
[] -> Enum.into(row, [])
_ -> Enum.into(row, %{})
end
end)
end
end
4 changes: 1 addition & 3 deletions test/ayesql/runner_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ defmodule AyeSQL.RunnerTest do
%{username: "alice", email: "[email protected]"}
]

assert ^expected = Runner.handle_result(data, into: Map)
assert ^expected = Runner.handle_result(data, into: %{})
end

Expand All @@ -46,7 +45,6 @@ defmodule AyeSQL.RunnerTest do
[username: "alice", email: "[email protected]"]
]

assert expected == Runner.handle_result(data, into: Keyword)
assert expected == Runner.handle_result(data, into: [])
end

Expand All @@ -64,7 +62,7 @@ defmodule AyeSQL.RunnerTest do
%User{username: "alice", email: "[email protected]"}
]

assert expected == Runner.handle_result(data, into: User)
assert expected == Runner.handle_result(data, into: %User{})
end

test "when rows are not empty, returns a raw result with columns and rows" do
Expand Down

0 comments on commit 59069f4

Please sign in to comment.