AndrewDryga

AndrewDryga

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

First 10 of 24 Posts Switch mode

wojtekmach

wojtekmach

Hex Core Team

Can you talk a bit more about your use case; on the DB level is it e.g. transports table with a few columns, including e.g. provider_type (string) and provider_settings (json) columns?

And even if you do that, there is a lot of issues that persist here. The main one right now for us is constraints

What types of constraints, like CHECK constraints?

AndrewDryga

AndrewDryga OP

@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'
""")
wojtekmach

wojtekmach

Hex Core Team

Hey @AndrewDryga, the migration is very helpful, thanks. The DB design looks good.

What do you think about validating provider settings with schemaless changesets and copying the errors to the parent? This would be similar to how constraint validations are handled, they’re used in the parent changeset and end up in parent changeset errors.

AndrewDryga

AndrewDryga OP

@wojtekmach this is definitely possible, we do as you said: validate dynamic embed with changeset (it’s not schemaless but it doesn’t matter) and put errors to the parent if any. But now we also need to copy constraints and in the view layer add a hack that would map constraint error to look like it occurred in the structure from provider_settings embed.

Mapping is required because we want error for a client to appear where it’s logically should be and point to a correct field, in case front-end maps that errors back. Correct me if I’m wrong, but changeset struct after constraint violation would point to a field in the embed, not to field in the parent struct.

The question is should we do something and make Ecto support dynamic embeds without a lot of hacking and mapping everything back and forth? Because resulting code is pretty complex, duplicated and error prone.

blatyo

blatyo

Conduit Core Team

The core team tends to prefer building an extendable core and allowing the community to provide extensions. Is there something here that might prevent a library and require this to be in Ecto? What would Ecto support for dynamic embeds look like?

AndrewDryga

AndrewDryga OP

Unfortunately, I don’t know a way to write a library that would change the fact that you can’t use Ecto.Changeset you built by yourself with Ecto.Repo operations. If you have ideas - I’m all ears. Maybe provide your own Repo implementation, but for a library it would be very hard to keep it up to date.

To support dynamic embeds (as far as I know):

  1. We should allow to use pretty much any Ecto.Changeset on embedded schemas (but I’m not sure how the syntax would look like there; syntax may be not required if we allow the lib to override Changeset type information and it would be actually used).
  2. (maybe) We should support constraints on embedded schemas, or at least on dynamic embeds.
  3. Ecto.Repo should thread dynamic embeds like any other embeds and in case of errors return them in proper structure (errors occurred in embed should be in embedded changeset).
drapermd

drapermd

@AndrewDryga Do you have an open source tree that you can share to solve this problem?

AndrewDryga

AndrewDryga OP

We have code that we use internally but noting ready for open source yet. Without Ecto support it’s just hacks.

Adzz

Adzz

Forgive me if I’m not understanding the problem correctly, but can you solve this problem with a custom ecto type?

Similar to the approach used here: https://medium.com/@ItizAdz/creating-a-has-one-of-association-in-ecto-with-ectomorph-3932adb996d9

Essentially the custom type decides how to build which struct based on the shape of the params it gets.

AndrewDryga

AndrewDryga OP

Currently, this is not possible because a type implementation only has access to data inside one field, but our use case is when type is actually a separate field in a schema. If we can, somehow, make type to know about other field values - it would work.

Where Next? Top

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 91561 914
New
byu
@chrismccord : I just saw the Extract AGENTS.md from Phoenix.new into phx.new generator commit to the phoenix project. My initial shotgu...
New
arcanemachine
I was working on an Ecto migration and I needed a timestamp. So, for the nth time, I looked up the different data types for timestamps, a...
New
AstonJ
Just a general thread to post chat/news/info relating to AI/ML stuff that may be relevant for Nx now or in the future. Got anything to sh...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
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
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
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
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New
mudasobwa
While I am working on the Language Agnostic Code Audit SaaS, which uses MetaAST (spoiler: I am expecting it to be in a good shape for ann...
New

We're in Beta

About us Mission Statement