本文介绍了如何在ecto Repo中使用原始SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个增补要求,因此我需要调用一个postgres存储过程或使用一个公共表表达式。我还使用pgcrypto扩展名作为密码,并希望使用postgres函数(例如 crypt来编码/解码密码)。

I have an upsert requirement, so I need to call a postgres stored procedure or use a common table expression. I also use the pgcrypto exgtension for passwords and would like to use postgres functions (such as "crypt" to encode/decode passwords).

但是我找不到方法为了让Ecto可以部分或全部使用原始sql,是不是打算ecto只支持elixir dsl,而在dsl不够用时不允许脱壳到原始sql?

But I can not find a way to get Ecto to play with raw sql in part or whole, is it intended that ecto will only support the elixir dsl and not allow shelling out to raw sql when the dsl is not sufficient?

我发现我可以通过适配器查询(火箭是应用程序的名称)

I've found that I can query via the adapter (Rocket is the name of the app)

q = Ecto.Adapters.Postgres.query(Rocket.Repo,"select * from users limit 1",[])

但不确定如何将其应用于模型。我是长生不老药,看来我应该可以使用Ecto.Model.Schem。模式 / 3,但是失败

But not sure how to get this to the model. I'm new to elixir and it seems I should be able to use Ecto.Model.Schem.schema/3 but this fails

Rocket.User.__schema__(:load,q.rows |> List.first,0)
** (FunctionClauseError) no function clause matching in Rocket.User.__schema__/3    


推荐答案

在带有Postgres的Ecto 2.0(测试版)中,您可以使用 Ecto.Adapters.SQL.query()(,)执行任意SQL;除了行本身的列表( )之外,它碰巧还会返回列名列表( )。

On Ecto 2.0 (beta) with Postgres, you can use Ecto.Adapters.SQL.query() (current docs, 2.0-beta2 docs) to execute arbitrary SQL; in addition to a list of the rows themselves ("rows"), it happens to return a list of column names ("columns").

在以下示例中,我


  1. 运行一个不带参数的自定义查询,

  2. 将结果的列名从字符串转换为原子,

  3. 将其与结果的每一行合并并映射使用
  4. 将其转换为结构
  1. run a custom query with no parameters,
  2. convert the result's column names from strings to atoms, and
  3. combine those with each row of the results and map it into a struct with Kernel.struct()

(您可能需要运行 query()版本(不要大声疾呼! )并检查 {ok,res} 。)

(You'll probably want to run the query() version (without the bang !) and check for {ok, res}.)

qry = "SELECT * FROM users"
res = Ecto.Adapters.SQL.query!(Repo, qry, []) # a

cols = Enum.map res.columns, &(String.to_atom(&1)) # b

roles = Enum.map res.rows, fn(row) ->
  struct(MyApp.User, Enum.zip(cols, row)) # c
end

这篇关于如何在ecto Repo中使用原始SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 03:42