Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I see the raw SQL generated for an Ecto.Query?

Tags:

elixir

ecto

I have an Ecto.Query and a Repo, such that I can call Repo.all(query) and get results. However, the results are not what I expect.

How can I see the raw SQL the Repo will generate from the Ecto.Query?

like image 855
Nathan Long Avatar asked Apr 21 '16 13:04

Nathan Long


People also ask

What databases does ecto support?

Ecto is a domain specific language for writing queries and interacting with databases in the Elixir language. The latest version (2.0) supports PostgreSQL and MySQL. (support for MSSQL, SQLite, and MongoDB will be available in the future).

What is ecto elixir?

Ecto is an official Elixir project providing a database wrapper and integrated query language. With Ecto we're able to create migrations, define schemas, insert and update records, and query them. Changesets. In order to insert, update or delete data from the database, Ecto. Repo.


2 Answers

You can use Ecto.Adapters.SQL.to_sql/3:

iex> Ecto.Adapters.SQL.to_sql(:all, Repo, Post) {"SELECT p.id, p.title, p.inserted_at, p.created_at FROM posts as p", []} 

This function is also available under the repository with name to_sql if you’re using a SQL based adapter:

 iex> Repo.to_sql(:all, Post)   {"SELECT p.id, p.title, p.inserted_at, p.created_at FROM posts as p", []} 

The query can be any struct that implements the Ecto.Queryable protocol like Post above(which is a module that imports Ecto.Schema). An Ecto.Query can also be passed:

iex> query = Ecto.Query.where(Post, [p], p.views > 10) iex> Ecto.Adapters.SQL.to_sql(:all, Repo, query) {"SELECT p.id, p.title, p.inserted_at, p.created_at FROM posts as p WHERE p.views > $1", [10]} 
like image 134
Gazler Avatar answered Sep 29 '22 23:09

Gazler


A convenient helper method for printing raw SQL

def print_sql(queryable) do   IO.inspect(Ecto.Adapters.SQL.to_sql(:all, Repo, queryable))   queryable end  def list_new_foos() do   Foo   |> where([foo], foo.bar == 1337)   |> limit(100)   |> print_sql   |> Repo.all() end 
like image 43
Dan Andreasson Avatar answered Sep 29 '22 23:09

Dan Andreasson