Macro to create a keyword for ecto3 dynamic bindings

How can I use a macro to create a simple keyword to use in a dynamic for Ecto 3?

What I want to achieve:

dynamic([school: e], ilike(field(e, ^param_name), ^"%#{param_value}%"))

I tried two versions:

defmacro want_this(prefix) do
   quote do
      dynamic([unquote(prefix): a], ilike(field(a, ^param_name), ^"%#{param_value}%"))
   end
end

want_this(:school)

but this version does not even compile.

Another try was done under the assumption that the macro would be compile and executed:

defmacro want_this(prefix) do
   quote do
      dynamic(unquote(Keyword.new(%{prefix=> a})), ilike(field(a, ^param_name), ^"%#{param_value}%"))
   end
end

want_this(:school)

but it compiles to Keyword.new(%{school: a})

A little context for the reason:

I have a filter function to receive a filter name, school.name or name for example, with a value. If the filter name has a . in the name, it should be applied to the relation instead to the entity itself. The joins with their aliases are working, but the creation of the conditions to use these aliases is my current problem.

I tried to use positional bindings, but the function itself does not know what the current position the filter, so I cannot use dynamic([_,x], ilike(field(a, ^param_name), ^"%#{param_value}%")). X could be the second or the fifth position. I do know the position at execution, but not at compilation.

Thanks in advance :slight_smile:

2 Likes

Try [{unquote(prefix), a}]

2 Likes