Reputation: 1439
I need to perform an update in the database and return a value. This is possible using the RETURNING
keyword in PostgreSQL
Since this is not supported by ecto I guess I have to use a fragment but I'm not sure how to do that. This is what I have:
query = from(v in MyModel,
where: v.id == ^instance_id,
update: [
inc: [counter: 1],
]
)
I'd like to return some fields after updating, for example the counter and the id, so I'd need to add to the query: RETURNING id, counter
;
Upvotes: 0
Views: 2460
Reputation: 597
In Ecto 3 the opportunity to use returning: true is deprecated for update_all in favor of a select in the query. So you would solve it like:
result = from(v in MyModel, where: v.id == ^instance_id, select: {v.id, v.counter})
|> MyRepo.update_all([inc: [counter: 1]])
Upvotes: 4
Reputation: 1951
If you use Ecto.Repo.update_all
https://hexdocs.pm/ecto/Ecto.Repo.html#c:update_all/3 there's an option :returning to pass with the returning list of fields
:returning - selects which fields to return. When true, returns all fields in the given struct. May be a list of fields, where a struct is still returned but only with the given fields. Or false, where nothing is returned (the default). This option is not supported by all databases.
And after execution you can access a tuple with this:
It returns a tuple containing the number of entries and any returned result as second element. If the database does not support RETURNING in UPDATE statements or no return result was selected, the second element will be nil.
Something like this:
result = from(v in MyModel, where: v.id == ^instance_id)
|> MyRepo.update_all([inc: [counter: 1]], returning: [id, counter])
Upvotes: 1