Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw SQL with Ecto

I'm very new in the world of Elixir and Phoenix Framework. I'm trying to follow TheFireHoseProject tutorial, but having problems with querying raw SQL with Ecto. The tutorial says this should work:

defmodule Queries do
def random do
  query = Ecto.Adapters.Postgres.query(
    Repo,
    "SELECT id, saying, author from quotes ORDER BY RANDOM() LIMIT 1",
    [])
  %Postgrex.Result{rows: [row]} = query
  {id, saying, author} = row
  %Splurty.Quote{id: id, saying: saying, author: author}
end
end

I'm getting a runtime error that the Ecto.Adapters.Postgres.query doesn't exist (undefined function).

I tried to search the Ecto documentation and found that there might be a function called run_query, but it doesn't work either.

I think I'm using Ecto 1.1.4 and I didn't find any good (up-to-date) samples of how can I query raw SQL with Ecto.

The link to the firehoseproject is: http://phoenix.thefirehoseproject.com/

like image 294
Antti Simonen Avatar asked Mar 16 '16 17:03

Antti Simonen


1 Answers

If all you need is just to add a raw SQL to otherwise normal Ecto query you can use fragment/1:

from q in Quote, order_by: fragment("RANDOM()"), limit: 1

It's often enough and it's much easier to handle. You can generally use fragment/1 in any part of Ecto query. For even nicer use, you can define a macro that will allow you to fit nicely into Ecto's DLS:

defmodule QueryHelpers do
  defmacro random() do
    quote do
      fragment("RANDOM()")
    end
  end
end

And later use it:

import QueryHelpers
from q in Quote, order_by: random(), limit: 1
like image 68
michalmuskala Avatar answered Sep 18 '22 01:09

michalmuskala