1stSolo

1stSolo

I have a parent-table and a child-table; they are 1:1 - the “child” could have been a set of fields on the parent but it was better to decompose that into two separate tables to better handle some special cases (e.g. some “parents” have two children in the “child” tables).
I originally had lock_version on both parent and child tables, but can I instead have lock_version only on the parent?
The GraphQL API we have allows to update the child only through parent, e.g.
updateParent(parentId:<id>, data: %{child: %{description: "new value"}}, but in this case when the arguments are passed into Ecto changset it doesn’t actually increment lock_version on the parent because none of the parent’s fields changed. If I could somehow detect a change of the child and trigger 'lock_version increment on the parent then I would not need the child to have its own lock_version. Anyone done this before?
The only downside here is that if “child” is modified by any other means other than the above API endpoint, e.g. by batch or trigger then optimistic lock won’t fail because Ecto is not aware of the changes in the db until it fetches the data.
But the basic idea in the setup here is that parent and child only happen to be decomposed into 1:1 tables, but they are virtually one table and thus not necessarily need a lock_version (or own timestamps, for that matter) on the child.
Alternatively, one could always set child’s lock_version to the parent’s lock_version when creating the changset for the child?

Showing Posts 1 to 1

1stSolo

1stSolo OP

I have a solution. Turns out, Changeset.cast_assoc is extremely useful when parent and child are updated together as a single unit as is my use-case. Even though the data is decomposed into two related tables, semantically the dependent/child is operated on as if it were a property of the parent module.
As the result:

  1. Don’t need to have lock_version on the child since parent’s lock_version is updated if cast_assoc detects a change in the child
  2. Requires to preload the assoc for cast_assoc to be able to detect changes
  3. For cast_assoc to behave properly and perform insert/update/delete based on the existing state of the dependent object, id of the child needs to be provided (it can be copied from Parent..id) or else Changeset will raise because the default for :on_replace of the association is :raise.

Example:

defmodule Project do
  use Ecto.Schema
  import Ecto.Changeset
  import Ecto.Query
  ...
  schema "projects" do
    field(:name, :string)
    field(:description, :string)
    field(:version, :string, default: "2.0")
    field(:owner_id, Ecto.UUID)

    has_one(:design, Design, foreign_key: :project_id)

    field :lock_version, :integer, default: 1
    timestamps(type: :utc_datetime)
  end

  def changeset(project, attrs \\ %{}) do
    supplied_design = attrs[:design]
    attrs =
      if not is_nil(supplied_design) and not is_nil(project.design.id) do
        Map.put(attrs, :design, Map.put(supplied_design, :id, project.design.id))
      else
        attrs
      end

    project
    |> cast(attrs, @cast_attrs)
    |> validate_required(@rqrd_attrs)
    |> check_constraint(:name, name: :name_length, message: "Project name \"#{attrs[:name]}\" is too long.")
    |> unique_constraint(:name, name: :project_name_unique, message: "Project name \"#{attrs[:name]}\" must be unique")
    |> validate_text_length(:description)
    |> cast_assoc(:design)
    |> optimistic_lock(:lock_version)
  end
  ...
  def update(%Project{} = project, attrs) do
    Repo.transaction(fn ->
      project
      |> Repo.preload(:design)
      |> changeset(attrs)
      |> Repo.update()
      |> case do
        {:ok, project} -> project
        {:error, error} -> Repo.rollback(error)
      end
    end)
  end

So Project.get(<uuid>) |> Project.update(%{design: %{diagram: "{\"some_json\": \"here\"}"}}) is then all is needed and the lock_version will get incremented with either Project or Design had changes. This allows to update both parent and child with a single optimistic lock field; timestamps, however, will be updated in both tables if child has changes.

— All posts loaded —

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
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
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews