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:
https://github.com/mathieuprog/polymorphic_embed/issues/74
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

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
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
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement