Inserting Function Result in the local database

Guys, I have a function that returns the following result.

[
  %{
    table_one: "Exemplo1",
    company: "Exemplo1",
    created: "12/02/2021 07:00:05",
    id: "P0093H",
    priority: "EX",
    service: "Exemplo1",
    status: "Exemplo1",
    teams: "PC9HR",
    title: "Exemplo1",
    urgency: "Exemplo1"
  },
  %{
    table_one: "Exemplo2",
    company: "Exemplo2",
    created: "12/02/2021 08:00:05",
    id: "P0094H",
    priority: "EX",
    service: "Exemplo2",
    status: "Exemplo2",
    teams: "PC9HR",
    title: "Exemplo2",
    urgency: "Exemplo2"
  },
  %{
    table_one: "Exemplo3",
    company: "Exemplo3",
    created: "12/02/2021 09:00:05",
    id: "P0095H",
    priority: "EX",
    service: "Exemplo3",
    status: "Exemplo3",
    teams: "PC9HR",
    title: "Exemplo3",
    urgency: "Exemplo3"
  }
]

How do I import into my local database?

Changeset created:

  schema "incidents" do
    field :company, :string
    field :table_one, :string
    field :created, :string
    field :priority, :string
    field :service, :string
    field :status, :string
    field :title, :string
    field :urgency, :string

    timestamps()
  end

I tried running the following command, but it returns an error.

iex(139)> Project.Example.Test.changeset(%Project.Example.Test{}, result_function) |> Repo.insert

** (Ecto.CastError) expected params to be a :map, got: `[%{table_one: “Exemplo1”, …

(ecto 3.5.6) lib/ecto/changeset.ex:514: Ecto.Changeset.cast/6
(ccmanager 0.1.0) lib/project/example/test.ex:21: Project.Example.Test.changeset/2

What is the easiest and recommended way to map this list?

The quickest way is to use Ecto.insert_all.

You have an error because You provided a collection (list) where You should have provided an element.

You should Enum module to perform insert on a collection… Enum.each or Enum.map.

Or insert_all, but it will skip validation check.

Repo.insert expects a single struct, and you are giving it the entire list.

Use Enum.map or Enum.each as @kokolegorille said and you’ll achieve your goal.

1 Like

Thank you, that really was it.