【问题标题】:How to use a Postrgrex extension to handle JSON data type如何使用 Postrgrex 扩展来处理 JSON 数据类型
【发布时间】:2015-01-31 03:46:05
【问题描述】:

Postgrex 项目页面提到了使用扩展来编码/解码来自 db https://github.com/ericmj/postgrex#extensions 的类型的能力

我正在尝试从项目页面获取代码以返回地图,但我不确定扩展程序应该在哪里挂钩到 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\"}"}]}

【问题讨论】:

标签: elixir ecto


【解决方案1】:

首先,确保您使用的是最新的“主”版本的 Postgrex。您可以在 mix.exs 中通过指定 {:postgrex, git: "git://github.com/ericmj/postgrex.git"} 来执行此操作

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

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

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 2016-01-29
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多