File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed
services/app/apps/codebattle Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments