Skip to content

Commit 13a8335

Browse files
committed
Provide additional context on JSON field error
1 parent 1311bc9 commit 13a8335

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
defmodule Ecto.Integration.ExceptionsTest do
2+
use Ecto.Integration.Case, async: true
3+
4+
alias Ecto.Integration.TestRepo
5+
alias Ecto.Integration.Post
6+
import Ecto.Query, only: [from: 2]
7+
8+
test "on bad JSON interpolation" do
9+
assert_raise Postgrex.Error,
10+
~r/If you are trying to query a JSON field, the parameter must be interpolated/,
11+
fn -> TestRepo.all(from p in Post, where: p.meta["field"] == "example") end
12+
end
13+
end

lib/ecto/adapters/postgres/connection.ex

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,23 @@ if Code.ensure_loaded?(Postgrex) do
6767

6868
@impl true
6969
def prepare_execute(conn, name, sql, params, opts) do
70-
Postgrex.prepare_execute(conn, name, sql, params, opts)
70+
case Postgrex.prepare_execute(conn, name, sql, params, opts) do
71+
{:error, %Postgrex.Error{postgres: %{pg_code: "22P02", message: message}} = error} ->
72+
context = """
73+
. If you are trying to query a JSON field, the parameter must be interpolated. Instead of
74+
75+
p.json["field"] == "value"
76+
77+
do
78+
79+
p.json["field"] == ^"value"
80+
"""
81+
82+
{:error, put_in(error.postgres.message, message <> context)}
83+
other ->
84+
other
85+
end
86+
7187
end
7288

7389
@impl true

0 commit comments

Comments
 (0)