Ecto inc/dec update one, helpers

Why are there no helpers for Ecto to perform increment and decrement?
For example Repo.inc(query, id, field, value)
Of course to make a helper like this it is not an issue:

    pk = Enum.at(queriable.__schema__(:primary_key), 0)
    result = queriable |> where([q], field(q, ^pk) == ^id) |> update_all(inc: changes)

Actually I am trying to beatify my code a bit, because with Ecto.Multi it makes such a large spaghetti chain.
I made a function:

def update_one(queryable, changes, where \\ []) do
    query = Enum.reduce(where, queryable, fn({key, value}, acc) ->
      where(acc, [q], field(q, ^key) == ^value)
    end)
    result = query |> update_all(set: changes)
end

But I’m not sure is it a good decision.

1 Like

Since Ecto 2.0, we support passing keywords in many places. Your update_one could be rewritten as:

def update_one(queryable, changes, where) do
  query |> Ecto.Query.where(^where) |> Repo.update_all(set: changes)
end

Those are covered in the docs and in the What’s New in Ecto 2.1 book.

3 Likes