Postgrex项目页面提到了使用扩展来编码/解码来自db https://github.com/ericmj/postgrex#extensions的类型的能力
我正在尝试从项目页面获取代码以返回地图,但我不确定扩展应该挂钩到Postgrex的哪个位置,如果重要的话,我试图在凤凰网络应用程序中这样做:
defmodule Extensions.JSON do
alias Postgrex.TypeInfo
@behaviour Postgrex.Extension
def matching,
do: [type: "json"]
def format,
do: :binary
def encode(%TypeInfo{type: "json"}, map, _types),
do: Poison.encode!(map)
def decode(%TypeInfo{type: "json"}, json, _types),
do: Poison.decode!(json)
end
#in iex
iex(5)> Ecto.Adapters.SQL.query Rocket.Repo, ~s(select '{"troy":"is cool"}'::json),[]
09:51:53.423 [debug] select '{"troy":"is cool"}'::json (1.3ms)
%{columns: ["json"], command: :select, num_rows: 1,
rows: [{"{\"troy\":\"is cool\"}"}]}
Run Code Online (Sandbox Code Playgroud)
小智 5
首先,确保您使用的是Postgrex的最新"主"版本.您可以mix.exs通过指定来完成此操作{:postgrex, git: "git://github.com/ericmj/postgrex.git"}
然后,您必须将扩展添加到您的连接opts,如下所示:
{:ok, pid} = Postgrex.Connection.start_link(database: "postgres", extensions: [Extensions.JSON])
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
593 次 |
| 最近记录: |