AndrewDryga

AndrewDryga

Dynamic Embeds in Ecto

Hey guys. I know this is an old topic, but as I write more and more complex application with Elixir and Ecto I feel like we really need a way to let developers use dynamic embeds.

Few words about our use case, we have a Transport schema which stores various common fields and settings of a transport. But depending on transport type (eg. Twillio and Facebook Messenger) settings can be very different and also there are DB constraints that should be in place for those settings.

We do work around this issue with an application logic which takes params for the embedded schema (which defined as :map type on parent changeset) and validates/casts them if embedded changeset is valid or properly adds errors to the parent otherwise. Here are some code:

A function that shows how dynamic changeset works in our case:

  defp cast_provider_settings(changeset, provider_field, provider_settings_field) do
    with {:ok, provider} <- fetch_change(changeset, provider_field),
         {:ok, settings} <- fetch_change(changeset, provider_settings_field),
         provider_settings_changeset = Provider.settings_changeset(provider, settings),
         {:ok, valid_settings} <- Validator.fetch_valid_attrs(provider_settings_changeset) do
      put_change(changeset, provider_settings_field, valid_settings)
    else
      :error ->
        changeset

      {:error, :not_found} ->
        changeset

      {:error, %{valid?: false} = settings_changeset} ->
        put_embedded_error(changeset, provider_settings_field, settings_changeset)
    end
  end

Here is how you can add an error to an embedded changeset defined as map:

  defp put_embedded_error(changeset, embed_field, embedded_changeset) do
    embedded_type =
      {:embed,
       %Ecto.Embedded{
         cardinality: :one,
         field: embed_field,
         on_cast: nil,
         on_replace: :raise,
         owner: %{},
         related: Transport,
         unique: true
       }}

    %{
      changeset
      | changes: Map.put(changeset.changes, embed_field, embedded_changeset),
        types: Map.put(changeset.types, embed_field, embedded_type),
        valid?: false
    }
  end

(Notice that you can’t override types and leave embedded changeset in Ecto Schema where :map type was defined because you would get a cast error. Ecto.Changeset does use pre-compiled type information when insert happens so overriding only helps when you use functions like traverse_errors/2.)

And even if you do that, there is a lot of issues that persist here. The main one right now for us is constraints - they are lost when embedded schema turned into a map and moving them manually to parent doesn’t make sense (error field would point to a wrong direction).

Other ways to hack around:

  1. Define multiple schemas per database entity (or even combine that with PostgreSQL table inheritance). This one looks weird for me because when I fetch data back from DB I do want to see only one kind of schema. Data that I want to put there should be exactly what I get back.
  2. Do not use dynamic embeds. This option looks poor because there is sooo many use cases where dynamic embed makes perfect sense.

As a very raw suggestion how we can deal with that:

  1. We might add a :changeset type for Ecto.Schema.
  2. It’s application responsibility to actually implement logic how embedded changeset gets there, on which fields it’s resolved, etc. (I don’t think that Ecto needs to add any kind of magic here.)
  3. Repo operations should take care of changesets in :changeset fields in a same way as they would do with usual embedded schema.

OR

  1. Make Ecto use type information from changeset (removing the calls to Schema.__*__ functions) which is not straightforward and would make changesets structs much bigger. (See this issue.)

Most Liked

mathieuprog

mathieuprog

@AndrewDryga could you check out the library I published for support for polymorphic embeds?
Would it answer your use case? If not, what would be lacking?

https://github.com/mathieuprog/polymorphic_embed

AndrewDryga

AndrewDryga

@wojtekmach I guess migration would answer both questions. In short - yes, it’s 2 columns. Constraints can be very different, I can’t tell which we will use in future. Currently it’s unique index and CHECK’s.

create table(:transports, primary_key: false) do
  add(:id, :binary_id, primary_key: true)
  add(:title, :string, null: false)
  add(:provider, :string, null: false)
  add(:provider_settings, :map)
end

execute("""
CREATE INDEX transports_provider_settings_user_id_index ON transports
USING GIN ((provider_settings->'user_id'))
""")

execute("""
CREATE UNIQUE INDEX transports_facebook_provider_settings_page_id_index ON transports
USING btree (provider, (provider_settings->'page_id'))
WHERE provider = 'facebook_messenger'
""")
mathieuprog

mathieuprog

I suggested to copy the type field, so you end up with the exact same structure in the DB, no difference for querying, i.e. a type and payload fields in the schema, in addition to a type in the payload to enable polymorphism. That small logic for copying the type would be done in the changeset.

Resorting to non documented, private internals such as Ecto.Embedded struct and its fields (thus that might change and break your app) seems worse as a solution. Would you go for a minor weirdness, or a fragile hack?

Indeed I don’t know about the limitations you faced back in 2018, as I wasn’t doing Elixir at that time.
I see however that ecto_poly was released end 2017, so there were some possibilities.

Where Next?

Popular in Discussions Top

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
thojanssens1
It would be nice to be able to define a redirect from one route to another from the router.ex file. E.g.: redirect "/", UserController, ...
New
mmport80
I have put far too much effort into Dialyzer over the last year or so - and basically - I doubt it’s worth the effort. It’s not as easy ...
New
chuck
Let me start by stating an assumption: Phoenix is a great approach to building REST APIs. There are many reasons for this, but I will ass...
New
praveenperera
How We Replaced React with Phoenix By: Thought Bot
New
tmbb
This is a post to discuss the new Phoenix LiveView functionality. From Chris’s talk, it appears that they generate all HTML on the serve...
342 18146 126
New
fireproofsocks
I’ve been working on an Elixir project that has required a lot of scripting. I usually reach for Elixir because I like it more (and in th...
New
jesse
Hi everyone, I hesitated to post this here because I don’t want you to think I’m spamming, but I’ve been working on a Platform-as-a-Serv...
New
griffinbyatt
Sobelow Sobelow is a security-focused static analysis tool for the Phoenix framework. For security researchers, it is a useful tool for g...
New
paulanthonywilson
I like Umbrella projects and pretty much always use them for personal Elixir stuff, especially Nerves things. But I don’t think this is ...
New

Other popular topics Top

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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
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
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
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
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New

We're in Beta

About us Mission Statement