jsonelixirectopostgrex

Postgrex how to define json library


I'm just trying to use Postgrex without any kind of ecto setup, so just the example from the documentation readme.

Here is what my module looks like:

defmodule Receive do

  def start(_type, _args) do
    {:ok, pid} = Postgrex.start_link(
      hostname: "localhost",
      username: "john",
      # password: "",
      database: "property_actions",
      extensions: [{Postgrex.Extensions.JSON}]
    )
    Postgrex.query!(
      pid,
      "INSERT INTO actions (search_terms) VALUES ($1)",
      [
        %{foo: 'bar'}
      ]
    )

  end
end

when I run the code I get

** (RuntimeError) type `json` can not be handled by the types module Postgrex.DefaultTypes, it must define a `:json` library in its options to support JSON types

Is there something I'm not setting up correctly? From what I've gathered in the documentation, I shouldn't even need to have that extensions line because json is handled by default.


Solution

  • On Postgrex <= 0.13, you need to define your own types:

    Postgrex.Types.define(MyApp.PostgrexTypes, [], json: Poison)
    

    and then when starting Postgrex:

    Postgrex.start_link(types: MyApp.PostgrexTypes)
    

    On Postgrex >= 0.14 (currently master), it was made easier:

    config :postgrex, :json_library, Poison