RudManusachi
Elixir Blog Post: SQL CASE with Ecto
Hi there!
Recently I was playing around with extracting and updating data in the DB and for fun challenged myself to try to implement a nice-looking function/macro to do SQL CASE with Ecto.
Wanted to share with you the results and thought it might be a good point to start blogging.
Any feedback is appreciated =)
Spoiler alert, throughout the blog post we are putting up together a sql_case/2 macro that could be used as:
from(m in "movies",
select:
{m.title,
sql_case(m.rating, [
[when: "G", then: "General Audiences"],
[when: "R", then: "Restricted"],
[when: "PG", then: "Parental Guidance Suggested"],
[when: "NC-17", then: "Clearly Adult"],
[else: m.rating]
])}
)
Most Liked
hauleth
I am working on the library that will allow something like:
defmodule Foo do
defq rating(rating) do
case rating do
"G" -> "General Audiences",
"R" -> "Restricted",
"PG" -> "Parental Guidance"
end
end
def query do
from m in Foo,
select: rating(m.rating)
end
end
But it staled a little since I do not have enough time to spare. But the above example should work more or less.
tfwright
Personally I favor terseness in my Ecto queries so I would prefer a syntax more like this:
case(m.rating, %{
"G" => "General Audiences",
"R" => "Restricted",
"PG" => "Parental Guidance"}, m.rating)
Also, FWIW I’ve yet to find a case when I’ve needed case despite maintaining a fairly extensive reporting system. I’d be tempted to say it’s almost a code smell in Ecto. For example, this example looks like it’s formatting the data, logic I prefer to keep in views. The other place I’ve seen it is in totaling with conditions which, at least in PSQL, can be converted to filter.
fuelen
Popular in Blog Posts
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
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









