kylelw23
I have a Phoenix app that already set up a schema, a controller and a router…
I would like to populate data into my created schema through seeds.exs
I have a csv file and I created a file CSVUtil.ex which is like this:
defmodule CampaignsApi.Store.Campaign do
@moduledoc """
Utility module to ingest `campaigns.csv`
"""
alias NimbleCSV.RFC4180, as: CSV
alias CampaignsApi.{Store.Campaign, Repo}
def column_data(file) do
column_names = get_column_names(file)
file
|> File.stream!()
|> CSV.parse_stream(skip_headers: true)
|> Enum.map(fn row ->
row
|> Enum.with_index()
|> Map.new(fn {val, num} -> {column_names[num], val} end)
|> create_or_skip()
end)
end
def get_column_names(file) do
file
|> File.stream!()
|> CSV.parse_stream(skip_headers: false)
|> Enum.fetch!(0)
|> Enum.with_index()
|> Map.new(fn {val, num} -> {num, val} end)
end
def create_or_skip(row) do
case Repo.get_by(Campaign,
id: row["id"]
) do
nil ->
Repo.insert(
%Campaign{}
|> Campaign.changeset(%{
id: Integer.new(row["id"]),
name: row["name"],
start_date: row["start_date"],
end_date: row["end_date"],
budget: Integer.new(row["budget"]),
hashtags: row["hashtags"],
team_id: Integer.new(row["team_id"]),
description: row["description"]
})
)
campaign ->
{:ok, campaign}
end
end
end
I ran mix test and my schema is working fine, and after I ran a seed file that run functions from CSVUtil.
I got this error:
** (Module.Types.Error) found error while checking types for CampaignsApi.Store.update_campaign/2
def update_campaign(%CampaignsApi.Store.Campaign{} = campaign, attrs) do
CampaignsApi.Repo.update(
CampaignsApi.Store.Campaign.changeset(
campaign,
attrs
)
)
end
Please report this bug: https://github.com/elixir-lang/elixir/issues
** (UndefinedFunctionError) function CampaignsApi.Store.Campaign.__struct__/0 is undefined or private
CampaignsApi.Store.Campaign.__struct__()
(elixir 1.13.1) lib/module/types/of.ex:131: Module.Types.Of.struct/3
(elixir 1.13.1) lib/module/types/pattern.ex:750: Module.Types.Pattern.of_shared/4
(elixir 1.13.1) lib/module/types/pattern.ex:47: Module.Types.Pattern.of_pattern/3
(elixir 1.13.1) lib/module/types/helpers.ex:93: Module.Types.Helpers.do_map_reduce_ok/3
(elixir 1.13.1) lib/module/types/pattern.ex:12: Module.Types.Pattern.of_head/4
(elixir 1.13.1) lib/module/types.ex:62: Module.Types.warnings_from_clause/6
(elixir 1.13.1) lib/module/types.ex:22: anonymous fn/8 in Module.Types.warnings/5
I am also new to this technology and I dont know what to do to get that CSVUtil works probably…
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
I’m aware of 2 such projects, are there others?
git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
Hi all,
I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
Hi everyone.
My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
Hi,
we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New
Hi all, I’m new here and would like to hear peoples views on my Elixir/Phoenix based game-engine! :smiley:
Mutonex gamedesign was finish...
New
Hello
I’ve been coding in Elixir for almost two years now because of my current job where we implemented Elixir in our application. But ...
New
Other Trending Topics
Hey there,
I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first.
...
New
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly)
AI dream has many faces, but general...
New
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself.
My main conc...
New
In 2021 I started a new library called Tempo with the objective of modelling time as a set of intervals - not as instants. In 2022 I gave...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #ai
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #blog-post
- #ecto-query
- #elixirconf-us
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #security
- #hex











Showing Posts 1 to 9- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
soup
Im not sure, but you’re defining your import module as
CampaignsApi.Store.Campaign, then aliasingCampaignsApi.Store.Campaign(I assume this is supposed to be your struct).As shown,
CampaignsApi.Store.Campaignisn’t a struct, nor a schema? So ecto is probably giving up when it can’t find the “type” because it’s given a Module, not a Struct.CampaignsApi.Store.Campaign.__struct__/0 is undefined or privateCan you make your importer
CampaignsApi.Importor something?kylelw23
Thank you, turn out that I should define the module as CampaignsApi.Store.CSVUtil not .Campaign
trisolaran
Hi @kylelw23 and welcome!
Apart from getting your code to run, as you already did with @soup’s help, I think there are a couple of things you could improve:
is somebody consuming the return value of
column_data? If yes, then I suggest you keep it a stream in order to avoid storing all the inserted structs in memory when callingEnum.map(). Thus, consider replacingEnum.map()withStream.map(). Using the latter will allow the result of the mapping step to be lazily evaluated by the consumer, which is more efficient if you’re dealing with a large number of rows. If, on the other hand, no one is consuming the return value ofcolumn_dataand you are only interested in the side effect of inserting the rows into the DB, then do replaceEnum.map()withEnum.each()to make this clear.In
create_or_skipyou are hitting the DB twice: once to check if a row with the given ID already exists, and then to insert the row if it doesn’t. Assuming you have a primary key constraint on theidcolumn in your DB schema you could get rid of the first call by callingRepo.insert()with theon_conflict: :nothingoption. The only downside is that thecampaignstruct returned by the insert, in case of a conflict, won’t be the one in the DB but the one you were trying to insert. This may or may not be a problem depending on who (if ever) is consuming this result (the answer to my question at point 1.)I hope this helps!
kylelw23
Hi @trisolaran
and it works normally, but I just wanted to update the database next time if I use column_data again, so It wont duplicate inputs that’s already added to the database.
dimitarvp
When using
Streamyou always have to use a function that collects the results at the end of the pipe becauseStreamfunctions only return other functions. Only when you put e.g.Enum.to_listorStream.runin the end will theStreamfunctions in the pipe get executed.Example:
Without the last function the code above only returns a function. Appending
Enum.to_listforces that function to get executed. It’s howStreamworks in Elixir and many other languages.But be advised: using
Streamincurs some performance penalty. Only use it if you have big collections of elements and you don’t want to have intermediate collections that get processed and then thrown away. Also it’s a good idea to only reach forStreamwhen you have several steps of processing. Your code above definitely does NOT needStreamas it is.trisolaran
His code above is already using a stream
. The output of:
is a stream. What his code doesn’t need is
Enum.map. It could just beEnum.each, provided nobody is using the result ofcolumn_data.That’s why I’d like to see how
column_datais called. @kylelw23 can you show us?dimitarvp
Sure, I’ve seen it above. I was seeking to remove confusion as to why only using
Streamwill seem to not work.kylelw23
Hi @trisolaran ,
seeds.exs:
Then I run mix run seeds.exs
trisolaran
Ok then you should ditch
Enum.mapand useEnum.eachinstead, because you are only runningcolumn_datafor the side effects, you don’t care about what it returns.It makes the code clearer and I think also more efficient:
Enum.mapwill store the result of the mapping in memory, and this could be a lot if you have a lot of rows.