Skip to content

Commit 2565f1f

Browse files
authored
Merge pull request #2110 from hexlet-codebattle/populate-clans-helper
add helper for loading clans from csv
2 parents 6a9cbe8 + 5128691 commit 2565f1f

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
defmodule Codebattle.Utils.PopulateClans do
2+
@moduledoc false
3+
4+
@doc """
5+
Populates clans table from csv file. The file is expected to
6+
have two fields in following order: long name, short name.
7+
"""
8+
def from_csv!(file) do
9+
utc_now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
10+
11+
file
12+
|> File.stream!()
13+
|> NimbleCSV.RFC4180.parse_stream()
14+
|> Stream.chunk_every(500)
15+
|> Enum.each(&process_batch(&1, utc_now))
16+
end
17+
18+
defp process_batch(clans, now) do
19+
clans = Enum.map(clans, &row_to_clan(&1, now))
20+
21+
Codebattle.Repo.insert_all(Codebattle.Clan, clans,
22+
on_conflict: {:replace, [:long_name]},
23+
conflict_target: [:name]
24+
)
25+
end
26+
27+
defp row_to_clan([long_name, name], now) do
28+
%{
29+
name: name,
30+
long_name: long_name,
31+
inserted_at: now,
32+
updated_at: now
33+
}
34+
end
35+
end
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
defmodule Codebattle.Utils.PopulateClansTest do
2+
use Codebattle.DataCase, async: true
3+
4+
test "from_csv" do
5+
csv = """
6+
long,short
7+
"the first clan",first_clan
8+
secondclan,clan2
9+
"""
10+
11+
{fd, path} = Temp.open!()
12+
IO.write(fd, csv)
13+
File.close(fd)
14+
15+
assert :ok = Codebattle.Utils.PopulateClans.from_csv!(path)
16+
assert %{long_name: "the first clan"} = Codebattle.Clan.get_by_name!("first_clan")
17+
end
18+
end

0 commit comments

Comments
 (0)