如何使用 Postrgrex 扩展来处理 JSON 数据类型
How to use a Postrgrex extension to handle JSON data type
Postgrex 项目页面提到了对来自数据库 https://github.com/ericmj/postgrex#extensions
的 encode/decode 类型使用扩展的能力
我正在尝试将代码从项目页面获取到 return 地图,但我不确定扩展程序应该在何处挂接到 Postgrex,如果重要的话,我正在尝试在 Phoenix 网络应用程序中执行此操作:
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\"}"}]}
首先,确保您使用的是最新的 "master" 版本的 Postgrex。您可以通过指定 {:postgrex, git: "git://github.com/ericmj/postgrex.git"}
在 mix.exs
中执行此操作
然后,您必须将扩展添加到您的连接选项中,如下所示:
{:ok, pid} = Postgrex.Connection.start_link(database: "postgres", extensions: [Extensions.JSON])
希望对您有所帮助!
Postgrex 项目页面提到了对来自数据库 https://github.com/ericmj/postgrex#extensions
的 encode/decode 类型使用扩展的能力我正在尝试将代码从项目页面获取到 return 地图,但我不确定扩展程序应该在何处挂接到 Postgrex,如果重要的话,我正在尝试在 Phoenix 网络应用程序中执行此操作:
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\"}"}]}
首先,确保您使用的是最新的 "master" 版本的 Postgrex。您可以通过指定 {:postgrex, git: "git://github.com/ericmj/postgrex.git"}
mix.exs
中执行此操作
然后,您必须将扩展添加到您的连接选项中,如下所示:
{:ok, pid} = Postgrex.Connection.start_link(database: "postgres", extensions: [Extensions.JSON])
希望对您有所帮助!