Seeding a database from a csv file in Phoenix Elixir

Just wanted to share with you a simple way to the database in an Elixir Pheonix project. The sample code was taken from the Animal Crossing New Horizons project. You can pick the csv from the github repo.

alias Newhorizonsapi.Animals.Fish
alias Newhorizonsapi.Repo

File.stream!("fish_export.csv")
|> Stream.drop(1)
|> CSV.decode(headers: [:name, :sell_value, :location])
|> Enum.each(fn {:ok, map} ->
  Fish.changeset(
    %Fish{},
    %{name: map[:name], price: String.to_integer(map[:sell_value]), location: map[:location]}
  )
  |> Repo.insert!()
end)
Published 1 Jun 2020

Biomedical engineer, with a keen interest in machine learning currently working as a fullstack developer at Marley Spoon. Ruby, Kotlin, Typescript and Elixir
Ricardo Trindade on Twitter