valyukov

valyukov

Dynamic fields in Ecto queries

Hi there,

How I can build queries with dynamic fields assignment in Ecto?
I try to do next thing:

import Ecto.Query
field = :id
value = 1

from(o in Order, where: o[field] != ^value)

** (Ecto.Query.CompileError) `o[field]` is not a valid query expression
    (ecto) expanding macro: Ecto.Query.where/3
           iex:6: (file)
    (ecto) expanding macro: Ecto.Query.from/2
           iex:6: (file)

how you can see it doesn’t work, but who cares? keyword syntax allow to do next things:

from(o in Order, where: ^[{field, value}])

and this works fine, but only for simple cases, it doesn’t allow neglect syntax (!=), like, is not, etc.

I don’t give up, and try to apply some metaprogramming magic:

(quote do: unquote(Order) |> where([q], q.unquote(field) == ^unquote(var!(value)))) |> Code.eval_quoted |> elem(0)

And it works perfect, however I need to make join with dynamic association, the next example throw exception and I have no idea how to solve it:

assoc = :transaction

(quote do: unquote(Order |> Ecto.Queryable.to_query) |> join(:inner, [r], l in assoc(r, unquote(var!(assoc)))) |> where([r, l], l.unquote(field) == ^unquote(var!(value)))) 
|> Code.eval_quoted 
|> elem(0)
** (CompileError) nofile: invalid quoted expression: #Ecto.Query<from o in Store.Order>
      (ecto) expanding macro: Ecto.Query.where/3
             nofile:1: (file)
    (elixir) expanding macro: Kernel.|>/2
             nofile:1: (file)

but if I quote module all works fine

how we see there is only one problem that join macros throw error when I try to pass Ecto.Query struct to it. Next snippet works well, but in my app I would like to pass exactly Ecto.Query to join.

assoc = :transaction

(quote do: unquote(Order) |> join(:inner, [r], l in assoc(r, unquote(var!(assoc)))) |> where([r, l], l.unquote(field) == ^unquote(var!(value)))) 
|> Code.eval_quoted 
|> elem(0)

Schemes:

defmodule Order do
  use Ecto.Schema
  schema "orders" do
    has_one :transaction, Transaction
  end
end

defmodule Transaction do
  use Ecto.Schema

  schema "transactions" do
    belongs_to :order, Order
  end
end

Data:
orders: [{id: 1}, {id: 2}]
transactions: [{id: 1, order_id: 1}, {id: 2, order_id: 2}]

Marked As Solved

Linuus

Linuus

To use dynamic fields you can use the field macro.

thing = :points
from a in Foo, where: field(a, ^thing) > 8
19
Post #2

Also Liked

valyukov

valyukov

It works perfect! Thank you!

mosiac05

mosiac05

Thanks, works fine.

Where Next?

Popular in Questions Top

lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New

We're in Beta

About us Mission Statement