如何使用Postrgrex扩展来处理JSON数据类型

时间:2015-01-30 17:57:11

标签: elixir ecto

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\"}"}]}

1 个答案:

答案 0 :(得分:5)

首先,确保您使用的是最新的" master" Postgrex的版本。您可以通过指定mix.exs

{:postgrex, git: "git://github.com/ericmj/postgrex.git"}中执行此操作

然后,您必须将扩展名添加到您的连接选项中,如下所示:

{:ok, pid} = Postgrex.Connection.start_link(database: "postgres", extensions: [Extensions.JSON])

希望这有帮助!

相关问题