hauleth
Interest check in query functions
I am working on big update to my ecto_function library. It is inspired by Nx support for defn functions, and my thought was “well, why not, check if it will be possible to do something similar for DB queries”. It seems that it is more or less possible:
defq clamp(val) do
cond do
val < 0 -> 0
val > 1 -> 1
true -> val
end
end
Which when used like:
from e in "entires",
select: clamp(e.value)
Will be translated to:
SELECT
CASE
WHEN e.value < 0 THEN 0
WHEN e.value > 1 THEN 1
ELSE e.value
END
FROM entries e
This may be useful when one would like to move more computation to the DB where sometimes it may make more sense (move your computation to your data instead of moving data to your computation).
Question is whether there will be will for such constructs and whether community will find something like that useful.
There is already working PoC on the GitHub
https://github.com/hauleth/ecto_function/pull/4
But I would live to get some more insights before I dig more into it.
Most Liked
hauleth
Actually it doesn’t change it into Ecto.Query, it changes it into macro that produces fragment/1.
defq clamp(val) do
cond do
val < 0 -> 0
val > 1 -> 1
true -> val
end
end
Will expand to:
defmacro clamp(val) do
quote do
fragment(
"CASE WHEN ? THEN ? WHEN ? THEN ? ELSE ? END",
unquote(val) < 0, 0,
unquote(val) > 1, 1,
unquote(val)
)
end
end
As shown above it is meant to be used within regular Ecto.Query queries, it will just provide a way to define more complex queries without manually writing fragments.
Popular in Announcing
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









