[Proposal] For `Repo.reload` functions, add support for items with multiple primary keys

32 views
Skip to first unread message

Nicholas Moen

unread,
Apr 29, 2025, 9:32:02 PMApr 29
to elixir-ecto
Problem: The functions `Repo.reload/2` (and its associated bang function) do not support reloading items with multiple primary keys.

Current solution: Here are the helper functions I have created to accomplish this in some of my tests:

```elixir
defmodule MyProject.TestHelpers.Ecto.Repo do
  @moduledoc "`Ecto.Repo` test helpers."

  alias MyProject.Repo

  @doc "Similar to `Repo.reload/2`, but supports structs with multiple primary keys."
  def reload(%_{} = struct, opts \\ []) do
    case struct.__struct__.__schema__(:primary_key) do
      [_pk] ->
        Repo.reload(struct, opts)

      _pks ->
        get_by_clauses =
          struct.__struct__.__schema__(:primary_key)
          |> Keyword.new(fn primary_key_field ->
            {primary_key_field, Map.fetch!(struct, primary_key_field)}
          end)

        Repo.get_by(struct.__struct__, get_by_clauses, opts)
    end
  end

  @doc "Similar to `Repo.reload!/2`, but supports structs with multiple primary keys."
  def reload!(%_{} = struct, opts \\ []) do
    case struct.__struct__.__schema__(:primary_key) do
      [_pk] ->
        Repo.reload!(struct, opts)

      _pks ->
        get_by_clauses =
          struct.__struct__.__schema__(:primary_key)
          |> Keyword.new(fn primary_key_field ->
            {primary_key_field, Map.fetch!(struct, primary_key_field)}
          end)

        Repo.get_by!(struct.__struct__, get_by_clauses, opts)
    end
  end
end
```

Proposal: Is there any interest in integrating this functionality into Ecto?

I realize that I would have to modify the functions to use the abstractions used by the existing Repo.reload functions. I just wanted to reach out before doing any work in case the omission of this functionality is intentional.

Thanks

José Valim

unread,
Apr 30, 2025, 3:11:09 AMApr 30
to elixi...@googlegroups.com
I think the issue is reloading multiple records, because then you need to align the pairs (or write very verbose queries). Or perhaps there is a way we can work around that?


--
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/093d319c-fcd6-46fd-9165-40f7a7c08eb3n%40googlegroups.com.

Greg Rychlewski

unread,
May 1, 2025, 5:42:46 AMMay 1
to elixir-ecto

The best solution i can think of is to join on values lis. 
Reply all
Reply to author
Forward
0 new messages