问题描述
我有一个 Ecto.Query
和一个 Repo
,这样我就可以拨打 Repo.all(query)
并获取结果。但是,结果却不是我所期望的。
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.
我如何查看 Repo
将从中生成的原始SQL Ecto.Query
?
How can I see the raw SQL the Repo
will generate from the Ecto.Query
?
推荐答案
您可以使用:
iex> Ecto.Adapters.SQL.to_sql(:all, Repo, Post)
{"SELECT p.id, p.title, p.inserted_at, p.created_at FROM posts as p", []}
如果名称为 to_sql
的存储库下也可以使用此功能您使用的是基于SQL的适配器:
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", []}
查询可以是实现协议,例如上面的 Post
(这是一个导入 Ecto.Schema $ c $的模块c>)。也可以传递
Ecto.Query
:
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]}
这篇关于如何查看为Ecto.Query生成的原始SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!