I’m wondering if anyone can point me to any previous discussion around why ecto doesn’t have a case_where
function? I know I can use fragment
or create a macro (which I do!) but I’m just interested in the reasoning for not including it. Is it due to complexity around supporting multiple dbs or is it to discourage the use of it? Or something else?
Thanks!
hauleth
September 10, 2021, 2:29pm
2
My bet is that no-one spent time implementing that. However I am experimenting with implementing such functionality as a library:
hauleth:master
← hauleth:ft/db-functions-with-body
opened 09:51AM - 15 Jun 21 UTC
For now `cond` statements are supported, but it can uncleanly fail if there is u… nsupported construct in the query function body.
Up to discussion:
- [ ] maybe support some of the `case`s (with the constants as the match patters) as [PostgreSQL supports such construct](https://postgresql.org/docs/13/interactive/functions-conditional.html#FUNCTIONS-CASE)
- [ ] `if` and `unless`, but it will make them work slightly different from the Elixir one, as PostgreSQL is statically typed, so there is no way to simulate it for non-bool condition
- [ ] variables assignment? I am not even sure how that could work at all, but if someone have any idea, then I will be open
Things needed to be done before merging:
- [ ] Tests, extensive test suite
- [ ] Clean handling of invalid function body
---
Goal of this PR is to add support for more complex query functions, for example support conditionals like:
```elixir
defq clamp(val) do
cond do
val < 0.0 -> 0.0
val > 1.0 -> 1.0
true -> true
end
end
```
Which then can be used in the query just as you would expect:
```elixir
from entry in "entries",
select: %{clamped: clamp(entry.value)}
```
2 Likes
Oh nice! Looks like it will be a useful library—I’m keeping an eye on it.
The README for this repo actually answers my question well enough