1stSolo

1stSolo

Share `lockVersion` between parent and child?

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?

Marked As Solved

1stSolo

1stSolo

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.

Where Next?

Popular in Questions Top

gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New

We're in Beta

About us Mission Statement