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.

https://hexdocs.pm/ecto/Ecto.Query.API.html#field/2

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

LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
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
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
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
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
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
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
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
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
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement