Danilo Cândido
Danilo Cândido

Reputation: 408

How to get a row from result of Ecto.Adapters.SQL.Query in Elixir

I am using Ecto.Adapters.SQL
I have this query below

query = "select c.name, c.email from clients c where c.id in (1,2,3)"

Then I put the query in my Repo

result = SQL.query(Automessages.Repo, query , []) 

After that I got this result(Map) with 3 rows

{:ok,
 %Mariaex.Result{columns: ["name", "email"], connection_id: nil,
  last_insert_id: nil, num_rows: 3,
  rows: [["Ana Silva", "[email protected]"],
   ["Farias de melo", "[email protected]"],
   ["João da costa", "[email protected]"]]}}

My question is how to get only the rows?

[["Ana Silva", "[email protected]"],
   ["Farias de melo", "[email protected]"],
   ["João da costa", "[email protected]"]]

Upvotes: 0

Views: 485

Answers (1)

Dogbert
Dogbert

Reputation: 222358

You can use pattern matching to extract the rows:

{:ok, %{rows: rows}} = SQL.query(Automessages.Repo, qry , [])
# rows is now [["Ana Silva", ...], ...]

Note that this will throw a MatchError if the pattern matching fails. If you don't want that, you can use case to handle it:

case SQL.query(Automessages.Repo, qry , []) do
  {:ok, %{rows: rows}} ->
    # rows is available here
  {:error, error} ->
    # some error occurred
end

Upvotes: 2

Related Questions