Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic composable Ecto query w/ dynamic field name in query expression

Tags:

elixir

ecto

I'm trying to allow for passing in a field name and running it in an Ecto query expression dynamically, like so:

def count_distinct(query, field_name) when is_binary(field_name) do
  query
  |> select([x], count(Map.fetch!(x, field_name), :distinct))
end

However, I get this compilation error:

(Ecto.Query.CompileError) `Map.fetch!(x, field_name)` is not a valid query expression

Is there any way to accomplish this?

like image 266
Josh Rieken Avatar asked Jan 06 '16 19:01

Josh Rieken


1 Answers

You need to use field/2 to dynamically generate fields in queries:

query
|> select([x], count(field(x, ^field_name), :distinct))

An example using the other query syntax for completion:

from x in query,
  select: count(field(x, ^field_name), :distinct)
like image 57
Gazler Avatar answered Oct 12 '22 14:10

Gazler