leonardorame

leonardorame

Hi, I’m new to Elixir and Phoenix.

I’m doing some experiments with Ecto.Adapters.SQL.query and now I would like to render a query result into an HTML table.

So far I did this:

page_controller.ex:

  def hello(conn, _params) do                                                                                                                                                                   
    {:ok, result} = Ecto.Adapters.SQL.query(:"Elixir.Hello.repo", "select idstudy, modality from study order by idstudy", [])                                                                   
    render(conn, "hello.html", studies: result)                                                                                                                                                 
  end 

hello.html.heex

<section class="phx-hero">                                                                                                                                                                      
  <h1>Hello!</h1>                                                                                                                                                                               
  <table>                                                                                                                                                                                       
  <%= for study <- @studies do %>                                                                                                                                                               
    <tr>                                                                                                                                                                                        
      <td><%= study.idstudy %></td>                                                                                                                                                             
      <td><%= study.modality %></td>                                                                                                                                                            
    </tr>                                                                                                                                                                                       
  <% end %>                                                                                                                                                                                     
  </table>                                                                                                                                                                                      
</section>

When I run that code I get this:

##### Protocol.UndefinedError <small>at GET</small> <small>/hello</small>

# protocol Enumerable not implemented for %Postgrex.Result{columns: ["idstudy", "modality"], command: :select, connection_id: 4334, messages: [], num_rows: 8, rows: [[12070, "CR"], [12071, "MR"], [12072, "CR"], [12073, "MR"], [12074, "CR"], [12075, "CR"], [12076, "CR"], [12077, "MR"]]} of type Postgrex.Result (a struct)

Showing Posts 1 to 9

hauleth

hauleth

Postgrex.Result is a struct that contains returned rows in :rows field. Additionally it will not map returned columns to their values, so for study <- @studies, do: {study.idstudy, study.modality} will not work. You need to do mapping on your own.

Any particular reason to write your queries by hand instead of using schemas or schemaless Ecto.Query? Also why low case repo in :"Elixir.Hello.repo"? That would make your life much easier if the repo would be Repo.

leonardorame

leonardorame OP

Could you point me to an example?.

Well, I don’t see the value of ORMs in general, I prefer to write my queries by hand instead of adding an abstraction layer to do the same in a slightly different language.

I created this test by following an example I found by googling for Ecto.Adapters.SQL.query (cannot find it right now). To fix it should I just replace “Elixir.Hello.repo” to “Elixir.Hello.Repo”?.

kokolegorille

kokolegorille

You might try something like this…

Enum.map(result.rows, &Map.new(Enum.zip result.columns, &1))

You also need to convert the resulting list of maps, to a list of your structs.

hauleth

hauleth

Ecto is not ORM, it is more of the query API with changesets.

Your query can be written as:

Repo.all(
  from "study",
    order_by: [idstudy: :asc],
    select: [:idstudy, :modality]
)

It is not much different from your hand-crafted SQL (and I would say that the QUEL-like order that Ecto.Query provides is much clearer than SQL “read from the middle, then end, and then beginning” order).

That will return you just list of maps, what is what you expected from the beginning. But why stop there? Instead of always remembering to define :select in query and remember what is the table name, you can “predefine” it:

defmodule Study do
  def table_name, do: "study"

  def fields, do: [:idstudy, :modality]
end

And then you can do:

Repo.all(
  from Study.table_name(),
    order_by: [idstudy: :asc],
    select: ^Study.fields()
)

Ok, but now we need to define Study twice, also if we have a lot of such tables, then the code will became repetitive, so Ecto has handy “schemas” which allow you to simplify all of that:

defmodule Study do
  use Ecto.Schema

  schema "study" do
    field :idstudy, :string
    field :modality, :integer
  end
end

Repo.all(
  from Study,
    order_by: [idstudy: :asc],
)

So as you see, there is nothing magical that does stuff behind your back. It is just small set of helpers to write queries faster and easier instead of manipulating strings. It also makes it much harder to accidentally have SQLi, as if you do something like:

input = "'; TRUNCATE TABLE study; --"
Repo.all(
  from Study,
    where: [idstudy: ^input]
)

It will send it as a prepared statement to the DB, which mean that passed argument will always be treated as properly escaped.

EDIT:

If I haven’t stated it strong enough QUEL >>>>>>>>>>>> SQL and do not even bother @-ing me, as there is nothing to discuss.

leonardorame

leonardorame OP

Great explanation, thank you! @hauleth .

leonardorame

leonardorame OP

@kokolegorille, by using Enum.map I end up with this:

defmodule HelloWeb.PageController do                                                                                                                                                            
  use HelloWeb, :controller                                                                                                                                                                     
                                                                                                                                                                                                
  def index(conn, _params) do                                                                                                                                                                   
    render(conn, "index.html")                                                                                                                                                                  
  end                                                                                                                                                                                           
                                                                                                                                                                                                
  def hello(conn, _params) do                                                                                                                                                                   
    {:ok, result} = Ecto.Adapters.SQL.query(:"Elixir.Hello.repo", "select idstudy, modality from study order by idstudy", [])                                                                                                                                                                                                                           
    data = Enum.map(result.rows, &Map.new(Enum.zip result.columns, &1))                                                                                                                         
    render(conn, "hello.html", studies: data)                                                                                                                                                   
  end                                                                                                                                                                                           
end     
<section class="phx-hero">                                                                                                                                                                      
  <h1>Hello!</h1>                                                                                                                                                                               
  <%= for study <- @studies do %>                                                                                                                                                               
    <%= for {key, value} <- study do %>                                                                                                                                                         
      <%= key %>                                                                                                                                                                                
      <%= value %>                                                                                                                                                                              
    <% end %>                                                                                                                                                                                   
  <% end %>                                                                                                                                                                                     
</section>  
kokolegorille

kokolegorille

It’s ok for simple scenario, but if You need associations, it would be preferable to use @hauleth solution.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

And if you have structs, you can use Ecto.Repo — Ecto v3.14.0 to load the queried results into a struct.

kokolegorille

kokolegorille

Even easier… thanks for the Repo.load tip :slight_smile:

— All posts loaded —

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
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
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews