rmoorman

rmoorman

Building a dynamic query using ecto's `dynamic` macro

Summary

I am currently trying to get a better understanding of elixir macros and in doing so encountered the section about dynamic queries in the ecto documentation. The example, however, leads to an unwanted true and part in the ecto query where and I am trying to have a look at how to solve that.

The trimmed down documentation example

So I tried out the example given and it seems to add a superfluous true and in front of the where clause. I trimmed the example down and put it inside a testcase:

defmodule MyMacroTest do
  use ExUnit.Case, async: true
  import Ecto.Query

  def filter_where(params) do
    Enum.reduce(params, dynamic(true), fn
      {"author", value}, dynamic ->
        dynamic([p], ^dynamic and p.author == ^value)
    end)
  end

  @q from(p in "post")

  test "author" do
    query = %{"author" => "foo"}
    assert inspect(where(@q, ^filter_where(query))) ==
             inspect(where(@q, [p], p.author == ^query["author"]))
  end
end

which fails with

     Assertion with == failed
     code:  assert inspect(where(@q, ^filter_where(query))) == inspect(where(@q, [p], p.author == ^query["author"]))
     left:  "#Ecto.Query<from p0 in \"post\", where: true and p0.author == ^\"foo\">"
     right: "#Ecto.Query<from p0 in \"post\", where: p0.author == ^\"foo\">"

The fancy if statement :see_no_evil:

Switching out the dynamic(true) within the call to Enum.reduce/3 with nil and using if seems to work

defmodule MyMacro2Test do
  use ExUnit.Case, async: true
  import Ecto.Query

  def filter_where(params) do
    Enum.reduce(params, nil, fn
      {"author", value}, dynamic ->
        if dynamic do
          dynamic([p], ^dynamic and p.author == ^value)
        else
          dynamic([p], p.author == ^value)
        end
    end)
  end

  @q from(p in "post")

  test "author" do
    query = %{"author" => "foo"}
    assert inspect(where(@q, ^filter_where(query))) ==
             inspect(where(@q, [p], p.author == ^query["author"]))
  end
end
Finished in 0.04 seconds (0.04s async, 0.00s sync)
1 test, 0 failures

Even though it works, it is not a thing of beauty and given that the dynamic macro basically outputs AST similar to what I would like, writing another macro appears to be the correct thing to do.

But here is the part I seem to struggle with

I now don’t know how to exactly extract that conditional into a macro. I guess I will need a macro because I need to wrap the dynamic macro and pass through the arguments in the same syntax.
Currently stuck with this version

defmodule MyMacroTest3 do
  use ExUnit.Case, async: true
  import Ecto.Query

  defmacro dynamic_and(dynamic, bindings, expr) do
    quote do
      if unquote(dynamic) do
        dynamic(unquote(bindings), unquote(dynamic) and unquote(expr))
      else
        dynamic(unquote(bindings), unquote(expr))
      end
    end
  end

  def filter_where(params) do
    Enum.reduce(params, nil, fn
      {"author", value}, dynamic ->
        dynamic_and(^dynamic, [p], p.author == ^value)
    end)
  end

  @q from(p in "post")

  test "author" do
    query = %{"author" => "foo"}
    assert inspect(where(@q, ^filter_where(query))) ==
             inspect(where(@q, [p], p.author == ^query["author"]))
  end
end

which gives me a compilation error about a misplaced operator ^dynamic

    The pin operator ^ is supported only inside matches or inside custom macros. Make sure you are inside a match or all necessary macros have been required
    │
 18 │         dynamic_and(^dynamic, [p], p.author == ^value)

I tried multiple variations of pinning and unquote/not unquote but I somehow currently fail to see where to look next for the correct way of solving this.
I also thought that a potential solution could involve returning some AST directly, or maybe it would be better to try to construct an %Ecto.Query.DynamicExpr struct myself.
Also got myself a copy of that Metaprogramming book and I am currently reading it hoping that it might help, and even got some bots involved :sweat_smile:

Anyway, I would really apreciate any pointers that could be thrown at me and thank you very much in advance! :slight_smile:

Marked As Solved

LostKobrakai

LostKobrakai

The solution here is Enum.map, Enum.reduce/2 over Enum.reduce/3:

params
|> Enum.map(fn 
  {"author", value} -> dynamic([p], p.author == ^value)
end)
|> Enum.reduce(fn a, b -> dynamic(^a and ^b) end)

Also Liked

gregvaughn

gregvaughn

I love the Enum.reduce/2 approach, but from past experience, I recommend you protect against an empty list, because it’ll raise.

Where Next?

Popular in Questions Top

pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement