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 - #19 by josevalim

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement