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

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
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
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
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
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

We're in Beta

About us Mission Statement