halostatue

halostatue

Ecto.Type: how to `cast` into a changeset like `embeds_{one,many}`?

This is a follow-on to Clearing an `embeds_many` entry (`cast_embed/3`), where I have a JSONB column with a constraint of NULL or non-empty list; embeds_many is inappropriate because it treats [] as the nil value for the field, and we explicitly do not want that behaviour. I consider it to be fundamentally incorrect, even though I understand it was done because it “normalizes” embeds as if they were associations.

I have created an Ecto.ParameterizedType for an OptionalList, derived at least partially from @mathieuprog’s polymorphic_embed library and some other digging around that I did.

When used with an embedded schema, the biggest problem (which is also true of polymorphic_embed) is that, unlike cast_embed, the casting of the resulting object is not an %Ecto.Changeset{} for the objects in the list, but is a realized version of the struct and it is doing no changeset validation.

I cannot figure out how to make this work, because when the field is loaded from the database, if it is not NULL, I want it to to cast into [%Value{}, %Value{}, …], but when taking data in for a changeset, I want it to cast into [%Ecto.Changeset{}, %Ecto.Changeset{}, …].

It appears that Ecto.Embedded has a prepare function — but I can’t quite figure out how it gets called in the process, whether it is something that can be done for automatically with a regular Ecto.Type, or whether I have to implement functions similar to cast_embed.

As I mentioned, I am seeing similar behaviour with polymorphic_embed, and I want to fix it in my fork so that it might be able to be upstreamed once I’m sure it works.

defmodule EctoOptionalList do
  @moduledoc """
  A nullable list of the provided type.

  This type wraps `{:array, :map}` in the same way that `embed_many/3` does,
  except that `nil` is a way of clearing the list completely, whereas
  `embed_many/3` always stores a list.

  ### Example

      field :optional, EctoOptionalList, type: Test.Option
  """

  use Ecto.ParameterizedType

  alias Ecto.Schema.Loader

  defstruct [:type, :field, :schema, :load_type]

  @impl true
  def type(_params), do: {:array, :map}

  @impl true
  def init(opts) do
    type = validate_type(opts[:type])

    load_type =
      if function_exported?(type, :__schema__, 1) do
        :schema
      else
        :struct
      end

    struct(__MODULE__, Keyword.merge(opts, type: type, load_type: load_type))
  end

  @impl true
  def cast(nil, _params), do: {:ok, nil}
  def cast(value, _params) when not is_list(value), do: :error

  def cast(list, %{type: type}) do
    result =
      Enum.reduce_while(list, [], fn
        %^type{} = entry, acc -> {:cont, [entry | acc]}
        %_badtype{}, _acc -> {:halt, :error}
        %{} = entry, acc -> {:cont, [build!(type, entry) | acc]}
      end)

    case result do
      :error -> :error
      value -> {:ok, value}
    end
  end

  @impl true
  def load(nil, _, _), do: {:ok, nil}
  def load(data, _, _) when not is_list(data), do: :error

  def load(data, fun, %{type: type, load_type: load_type, field: field}) do
    {:ok, Enum.map(data, &load_field(load_type, type, field, &1, fun))}
  end

  @impl true
  def dump(nil, _, _), do: {:ok, nil}
  def dump(data, _, _) when not is_list(data), do: :error

  def dump(data, fun, %{type: type, load_type: load_type, field: field}) do
    types = if load_type == :schema, do: type.__schema__(:dump)

    {:ok, Enum.map(data, &dump_field(load_type, type, field, &1, types, fun))}
  end

  defp validate_type(nil), do: invalid_type!()
  defp validate_type(%mod{}), do: validate_type(mod)
  defp validate_type(value) when not is_atom(value), do: invalid_type!()

  defp validate_type(mod) do
    with {:module, _} <- Code.ensure_compiled(mod),
         true <- function_exported?(mod, :__struct__, 0) do
      mod
    else
      _ -> invalid_type!()
    end
  end

  defp invalid_type! do
    raise ArgumentError, """
    EctoOptionalList must have a `type` option referencing a struct module.
    This option was either omitted or the value provided is neither a struct
    nor a module defining a struct.

    For example:

        field :my_field, EctoOptionalList, type: MyFieldStruct
        field :my_field, EctoOptionalList, type: %MyFieldStruct{}
    """
  end

  defp build!(type, value) when is_map(value) do
    data =
      Enum.map(
        value,
        fn
          {k, v} when is_binary(k) -> {String.to_existing_atom(k), v}
          kv -> kv
        end
      )

    struct!(type, data)
  end

  defp load_field(:struct, type, _field, value, _loader) when is_map(value) do
    build!(type, value)
  end

  defp load_field(:schema, type, _field, value, loader) when is_map(value) do
    Loader.unsafe_load(type, value, loader)
  end

  defp load_field(_loader_type, type, field, value, _loader) do
    raise ArgumentError,
          "cannot load `#{field}`, expected a map for #{type} but got: #{inspect(value)}"
  end

  defp dump_field(:struct, type, _field, %{__struct: type} = value, _types, _dumper) do
    Map.from_struct(value)
  end

  defp dump_field(:schema, type, _field, %{__struct__: type} = value, types, dumper) do
    Loader.safe_dump(value, types, dumper)
  end

  defp dump_field(_loader_type, type, field, value, _types, _dumper) do
    raise ArgumentError,
          "cannot dump `#{field}`, expected a list of #{type} struct values but got: #{inspect(value)}"
  end
end

Most Liked

halostatue

halostatue

I’m fairly certain that this can be done, but the flow in Ecto is complex enough that I’m not sure what hooks exist or would be required if they don’t exist.

This could be simplified (at least for the specific OptionalList example) if embeds_many allowed default: nil instead of assuming default: []. This would still be needed to make polymorphic_embed work better. I am assuming that I will need something like cast_embed to make the Ecto.Type work differently.


I see I need to look at my fork kineticcafe/polymorphic_embed@kinetic against your recently released 4.0 to see if there is anything that I have modified which you have not caught (aside from my removal of Form support, which we do not need and would prefer to see as a separate package). With the exception of this limitation we have both run against, polymorphic_embed is fantastic, so thank you.

mathieuprog

mathieuprog

I believe I had hit a limitation with Ecto Type regarding this, also see:

I wish I had added failing tests in the codebase in order to document this differences with the embed_one/many Ecto functions.
We would need to confirm again that this can’t be fixed, and from there, either see if the Ecto team can do something, and at the minimum, make sure to document all the limitations in the readme caused by that to inform the users (e.g. comment Polymorphic embeds are not kept as changesets but are turned into structs - as opposed to what happens with ordinary embeds · Issue #74 · mathieuprog/polymorphic_embed · GitHub and comment Polymorphic embeds are not kept as changesets but are turned into structs - as opposed to what happens with ordinary embeds · Issue #74 · mathieuprog/polymorphic_embed · GitHub).

mathieuprog

mathieuprog

Just to clarify, one of the library’s core principle is to follow embed_one/many as close as possible. So it doesn’t have the ambition to solve the initial problem mentioned of distinguishing a nil value from an empty list (as embed_many doesn’t allow us).
However I was reacting on the issue of losing changesets:

When used with an embedded schema, the biggest problem (which is also true of polymorphic_embed) is that, unlike cast_embed, the casting of the resulting object is not an %Ecto.Changeset{} for the objects in the list, but is a realized version of the struct and it is doing no changeset validation.
I cannot figure out how to make this work, because when the field is loaded from the database, if it is not NULL, I want it to to cast into [%Value{}, %Value{}, …], but when taking data in for a changeset, I want it to cast into [%Ecto.Changeset{}, %Ecto.Changeset{}, …].

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement