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]
     ])}
)
3 Likes