kkart

kkart

Implementing Ecto Adapter for Dgraph db - autogenerated IDs

I’m implementing an Ecto adapter for the Dgraph graph db. I’m able to successfully insert a new record from a Schema or a Changeset. I’ve implemented the callback Ecto.Adapter.Schema.insert/6 and this callback is expected to return {:ok, fields()}.

If I return {:ok, []} from the callback, Ecto loads the associated Schema struct with the changeset that was given by the user. Dgraph autogenerates UIDs as the primary key for each Dgraph Node created (equivalent to a record), but this doesn’t get included in the Schema struct returned by Ecto to the user.

I assumed incorrectly that if I return {:ok, [uid: autogenerated_id, ...additional_fields]} from my callback, it would use those values to load the Schema struct. (This is a minimal implementation for the example.)

  @impl Ecto.Adapter.Schema
  def insert(
        %{pid: conn} = _repo_meta,
        schema_meta,
        fields,
        _on_conflict,
        _returning,
        _opts
      ) do
    mutation = Query.new_mutation(:set, schema_meta, fields)

    case DBConnection.prepare_execute(conn, mutation, fields, []) do
      {:ok, _, %{uids: uids}} ->
        {:ok, Keyword.put(fields, :uid, find_uid(fields, uids))}

      {:error, reason} ->
        {:invalid, [{:unique, "primary_key"}]}
    end
  end

Instead, I’m getting the following error in Ecto after my callback was called and it is attempting to load the Schema:

     ** (FunctionClauseError) no function clause matching in Ecto.Repo.Schema.load_each/4

     The following arguments were given to Ecto.Repo.Schema.load_each/4:

         # 1
         %DgraphEx.Test.User{__meta__: #Ecto.Schema.Metadata<:loaded, "User">, uid: "_:m0vRzOFL9c", email: "kartch@dgrex.com", handle: "kartch"}

         # 2
         [uid: "0x33"]

         # 3
         []

         # 4
         DgraphEx.Ecto.Adapter

     Attempted function clauses (showing 2 out of 2):

         defp load_each(struct, [{_, value} | kv], [{key, type} | types], adapter)
         defp load_each(struct, [], _types, _adapter)

     code: TestRepo.insert(user_changeset)
     stacktrace:
       (ecto 3.12.5) lib/ecto/repo/schema.ex:1090: Ecto.Repo.Schema.load_each/4
       (ecto 3.12.5) lib/ecto/repo/schema.ex:1068: Ecto.Repo.Schema.load_changes/8
       (ecto 3.12.5) lib/ecto/repo/schema.ex:509: anonymous fn/15 in Ecto.Repo.Schema.do_insert/4
       test/insert_test.exs:18: (test)

The problem with the unmatched function clause is due to an empty 3rd argument being passed to Ecto.Repo.Schema.load_each/4. It appears to need a Keyword list of field keys to types as the 3rd argument but it’s empty. The return clause from my callback doesn’t allow for anything other than {:ok, fields()} so I’m unsure how to apply the new uid to the loaded struct.

Does the fields keyword list being returned by my callback need to be in a different format than the fields supplied in the form of [uid: uid_value, field_key1: field_value1, field_key2: field_value2, ...]?

Thank you for any help.

Edit for clarification:

I’m using a custom type for the UID field that autogenerates a temporary ID. I need to generate a temporary UID to associate the Node predicates on insert, and Dgraph assigns a new UID. In short, my custom type autogenerates a temp UID and I need the DB generated UID to be loaded into the struct.

Marked As Solved Switch mode

kkart

kkart

Thank you for the help, @Schultzer. I found a solution by looking at the mongodb_ecto project. For anyone else trying to accomplish the same thing:

Use a :binary_id as the primary key type in your schema and in the adapter, specify a custom loader and dumper for :binary_id with the Ecto.Adapter.loaders/1 callback. I’m able to autogenerate the temporary ID and return the new ID from my Ecto.Adapter.Schema.insert/6 callback.

Also Liked

Schultzer

Schultzer

There might be something valuable in here: GitHub - Schultzer/ecto_qlc: QLC-based adapters and database migrations for Ecto · GitHub

If my memory serve me well I hit something similar, although I don’t believe you need to generate temp. id, you just need to include it in returning.

Anyway, my adapter supperts autogenerated ids for mnesia, dets, ets in similar fashion to how it’s implemented for postgres, myxql or tds.

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
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
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
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

We're in Beta

About us Mission Statement