mfrasca

mfrasca

Writing a query - translation approach

some time ago I had posted this question on a parser which I had already written in Python/ply and I am porting to elixir / ecto / erlang, using yecc.

one point where I got stuck was which format to target from the erlang code associated to the grammar productions, and it took time to understand that the result of quote is not something I can easily reuse, also because I did not manage to understand which alternatives were being offered.

also possibly puzzling for me, was that in the iex console, a query gets printed in a format which is not a format I can use to insert the query by hand in the console.

iex(163)> from(p in "plant")
#Ecto.Query<from p0 in "plant">

the present follow-up question, more than a question, is a RFC, since it contains the help I would give to someone who made the same assertion as myself a few weeks ago. and since I’m a total beginner in Elixir, I guess some might want to comment.


should I be scared of the quoted format. I’m not sure why I should not just produce it from my parser and put it into a macro?

scared, that’s not the word, but it is a dead-end way. you want to build the value representing the query, that’s a Ecto.Query structure, and you should have a look at the sources in the lib/ecto/query.ex and nearby files, to understand which are the fields you need to define, and which values to give them.

in particular, check the four fields from, select, wheres, and joins. they are either individual structures, or homogeneous lists of structures. you can build whatever sample query, and get the field from it, like this:

q = Ecto.Query.from(p in "plant", select: [p.code], where: p.location_id==3)
q.from
q.wheres

then try it yourself. it’s just values, there’s no OO complications here.


after some experimenting, I found out that the following works quite fine with my database botanic database:

w = %Ecto.Query{}
w = %{ w | from: %Ecto.Query.FromExpr{source: {"accession", nil}}}
w = %{ w | select: %Ecto.Query.SelectExpr{expr: [
  {{:., [], [{:&, [], [0]}, :code]}, [], []}]}}
Botany.Repo.all(w)

as do the more complex ones (I’m joining plant with accession and location, and filtering based on values in all tables. tables get numbered according to the position in which they appear in the joins list, 0 being reserved for the from.source. 0: plant, 1: accession, 2: location):

w = %Ecto.Query{}
w = %{ w | from: %Ecto.Query.FromExpr{source: {"plant", nil}}}
w = %{ w | joins: [
  %Ecto.Query.JoinExpr{
    source: {"accession", nil}, 
    qual: :inner,
    on: %Ecto.Query.QueryExpr{
      expr: {:==, [], [
        {{:., [], [{:&, [], [0]}, :accession_id]}, [], []},
        {{:., [], [{:&, [], [1]}, :id]}, [], []}
      ]}}},
  %Ecto.Query.JoinExpr{
    source: {"location", nil}, 
    qual: :inner,
    on: %Ecto.Query.QueryExpr{
      expr: {:==, [], [
        {{:., [], [{:&, [], [0]}, :location_id]}, [], []},
        {{:., [], [{:&, [], [2]}, :id]}, [], []}
      ]}}}
  ]}
w = %{ w | select: %Ecto.Query.SelectExpr{expr: [
  {{:., [], [{:&, [], [2]}, :code]}, [], []}, 
  {{:., [], [{:&, [], [1]}, :code]}, [], []}, 
  {{:., [], [{:&, [], [0]}, :code]}, [], []}]}}
Botany.Repo.all(w)

the above is a base query, defining the joins, selecting one field per each of the three tables involved, and returning everything. below I’m adding a wheres list, length 1, containing a few of the operators I have in my grammar.

%{ w | wheres: [%Ecto.Query.BooleanExpr{op: :and, expr: 
    {:==, [], [
      {{:., [], [{:&, [], [2]}, :code]}, [], []}, 
      "GH1"]}}]} |> 
  Botany.Repo.all()
%{ w | wheres: [%Ecto.Query.BooleanExpr{op: :ane, expr: 
    {:in, [], [
      {{:., [], [{:&, [], [1]}, :code]}, [], []}, 
      ["2018.0044", "2018.0045", "2018.0046", "2018.0047"]]}}]} |> 
  Botany.Repo.all()
%{ w | wheres: [%Ecto.Query.BooleanExpr{op: :and, expr: 
    {:or, [], [
      {:==, [], [
        {{:., [], [{:&, [], [2]}, :code]}, [], []}, 
        "GH2"]}, 
      {:==, [], [
        {{:., [], [{:&, [], [1]}, :code]}, [], []}, 
        "2018.0044"]}]}}]} |> 
  Botany.Repo.all()
%{ w | wheres: [%Ecto.Query.BooleanExpr{op: :and, expr: 
    {:and, [], [
      {:==, [], [
        {{:., [], [{:&, [], [2]}, :code]}, [], []}, 
        "GH2"]}, 
      {:==, [], [
        {{:., [], [{:&, [], [1]}, :code]}, [], []}, 
        "2018.0044"]}]}}]} |> 
  Botany.Repo.all()

I haven’t tried yet, but I guess that producing this from the yecc parser will not be much more difficult than the quote representation.

First Post!

josevalim

josevalim

Creator of Elixir

I made a reply related to this topic here: How do i produce an elixir struct from erlang

Where Next?

Popular in Questions Top

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
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
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
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
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

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
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
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
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

We're in Beta

About us Mission Statement