almightycouch / rethinkdb_ecto

RethinkDB adapter for Ecto.
https://hexdocs.pm/rethinkdb_ecto
MIT License
114 stars 18 forks source link

Support for optimistic locking? #5

Open Lida opened 8 years ago

Lida commented 8 years ago

I was running the example in Ecto's doc for optimistic locking while using RethinkDB.Ecto as the adapter.

Repo.update!(stale_change) didn't update the row, but it didn't throw a Ecto.StaleModelError either.

What is going on here?

almightycouch commented 8 years ago

Hi @Lida, thank you for pointing that out. Basically, RethinkDB has built-in support for atomic updates. You don't have to rely on Ecto's optimistic lock to allow lock-free updates on a single record.

I will investigate why the update did not work as excepted.

Lida commented 8 years ago

Hi @almightycouch, the optimistic locking is being used to make sure concurrent updates doesn't conflict. For example allowing multiple user to increment a counter. I am currently using ReQL directly to make sure we don't clobber any updates.

table("counters") |> get(model.id) |> update((lambda fn(row) ->
      if row["version"] == model.version do
        Map.merge(params, %{version: model.version + 1})
      else
        error("Can't update")
      end
    end))