halostatue

halostatue

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

Showing Posts 1 to 3

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).

halostatue

halostatue OP

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

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{}, …].

— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
Alvinkariuki
How Can I Optimise Compile Time Dependencies I have been building an elixir application for about 2 years now. Many modules and files ha...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews