[Proposal] Support for list of structs as entries in Repo.insert_all/3

19 views
Skip to first unread message

Rodolfo Carvalho

unread,
Jul 28, 2025, 4:00:01 AMJul 28
to elixir-ecto
Hi,

In order to have the Elixir compiler ensure I'm passing reasonable data to `Repo.insert_all/3`, I tried to pass a list of structs as entries, but that doesn't work.

Currently, as per the documentation, the entries must be either maps or keyword lists.

Example

```elixir
defmodule MySchema do
  use Ecto.Schema
 
  schema "my_schema" do
    field :user_id, :integer
    field :resource, Ecto.Enum, values: [:gold, :silver, :bronze]
    field :value, :integer
    timestamps()
  end
end
```

What I ended up doing to insert 3 rows with type-checking:

```elixir
    MySchema
    |> Repo.insert_all([
      %MySchema{
        user_id: user.id,
        resource: :gold,
        value: 500,
        inserted_at: now
      }
      |> Map.take(MySchema.__schema__(:fields)),
      %MySchema{
        user_id: user.id,
        resource: :silver,
        value: 700,
        inserted_at: now
      }
      |> Map.take(MySchema.__schema__(:fields)),
      %MySchema{
        user_id: user.id,
        resource: :bronze,
        value: 900,
        inserted_at: now
      }
      |> Map.take(MySchema.__schema__(:fields))
    ])
```

My proposal is to make it work without the `|> Map.take(MySchema.__schema__(:fields))` part.

Best regards,

Rodolfo

José Valim

unread,
Jul 28, 2025, 6:24:24 AMJul 28
to elixi...@googlegroups.com
The issue with passing structs is that we send all fields, so any field that is auto generated by the database, will be set to its default Elixir value and either fail or be wrong. This is the reason why we don't support structs.


--
You received this message because you are subscribed to the Google Groups "elixir-ecto" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-ecto...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/elixir-ecto/6c3e0dde-4ab9-43ef-b42b-f78c8e104e1dn%40googlegroups.com.
Message has been deleted

Rodolfo Carvalho

unread,
Jul 29, 2025, 5:48:30 PMJul 29
to elixir-ecto
Thanks for the reply, makes total sense. I take back my proposal :)
Reply all
Reply to author
Forward
0 new messages