SQL/JSON DEFAULT ON ERROR/ON EMPTY evaluation fail should rethrow error unconditionally

Started by jian he2 months ago10 messageshackers
Jump to latest
#1jian he
jian.universality@gmail.com

Hi.

Please see function ExecInitJsonExpr below code
``````
/*
* Steps to evaluate the ON ERROR expression; handle errors softly to
* rethrow them in COERCION_FINISH step that will be added later.
*/
saved_escontext = state->escontext;
state->escontext = escontext;
ExecInitExprRec((Expr *) jsexpr->on_error->expr,
state, resv, resnull);
state->escontext = saved_escontext;

/* Step to coerce the ON ERROR expression if needed */
if (jsexpr->on_error->coerce)
ExecInitJsonCoercion(state, jsexpr->returning, escontext,
jsexpr->omit_quotes, false,
resv, resnull);

/*
* Add a COERCION_FINISH step to check for errors that may occur when
* coercing and rethrow them.
*/
if (jsexpr->on_error->coerce ||
IsA(jsexpr->on_error->expr, CoerceViaIO) ||
IsA(jsexpr->on_error->expr, CoerceToDomain))
{
scratch->opcode = EEOP_JSONEXPR_COERCION_FINISH;
scratch->resvalue = resv;
scratch->resnull = resnull;
scratch->d.jsonexpr.jsestate = jsestate;
ExprEvalPushStep(state, scratch);
}
``````
The above code relates to SQL/JSON ON ERROR, apply the same logic to ON EMPTY.

1.
The whole expression (jsexpr->on_error->expr) could be compiled under
the ErrorSaveContext, so any part of it
may report an error softly; without a COERCION_FINISH step afterwards
unconditionally, that
error is never handled.
That is not OK if we later want to raise the error, which is the case here.

2.
By the time the coercion step from ExecInitJsonCoercion runs, a soft error
may already have occurred during expression evaluation (DEFAULT ON
ERROR, DEFAULT ON EMPTY).
ExecEvalJsonCoercion should check for that first and, if so,
set resnull and resvalue and return earlier.

I found this issue while working on
https://commitfest.postgresql.org/patch/5941.

I don't think we need to add any extra comments.
/*
* Steps to evaluate the ON ERROR expression; handle errors softly to
* rethrow them in COERCION_FINISH step that will be added later.
*/
This comment is OK even if we unconditionally add a COERCION_FINISH step.

We could executing EEOP_JSONEXPR_COERCION_FINISH only when escontext
is non-NULL.
But, adding EEOP_JSONEXPR_COERCION_FINISH unconditionally feels more
intuitive and the cost seems very little.

--
jian
https://www.enterprisedb.com/

Attachments:

t253803_1
v1-0001-fix-SQL-JSON-DEFAULT-expression-error-rethrow.patchtext/x-patch; charset=US-ASCII; name=v1-0001-fix-SQL-JSON-DEFAULT-expression-error-rethrow.patchDownload+58-22
#2Amit Langote
amitlangote09@gmail.com
In reply to: jian he (#1)
Re: SQL/JSON DEFAULT ON ERROR/ON EMPTY evaluation fail should rethrow error unconditionally

Hi Jian,

On Wed, Sep 16, 2026 at 11:21 AM jian he <jian.universality@gmail.com> wrote:

Hi.

Please see function ExecInitJsonExpr below code
``````
/*
* Steps to evaluate the ON ERROR expression; handle errors softly to
* rethrow them in COERCION_FINISH step that will be added later.
*/
saved_escontext = state->escontext;
state->escontext = escontext;
ExecInitExprRec((Expr *) jsexpr->on_error->expr,
state, resv, resnull);
state->escontext = saved_escontext;

/* Step to coerce the ON ERROR expression if needed */
if (jsexpr->on_error->coerce)
ExecInitJsonCoercion(state, jsexpr->returning, escontext,
jsexpr->omit_quotes, false,
resv, resnull);

/*
* Add a COERCION_FINISH step to check for errors that may occur when
* coercing and rethrow them.
*/
if (jsexpr->on_error->coerce ||
IsA(jsexpr->on_error->expr, CoerceViaIO) ||
IsA(jsexpr->on_error->expr, CoerceToDomain))
{
scratch->opcode = EEOP_JSONEXPR_COERCION_FINISH;
scratch->resvalue = resv;
scratch->resnull = resnull;
scratch->d.jsonexpr.jsestate = jsestate;
ExprEvalPushStep(state, scratch);
}
``````
The above code relates to SQL/JSON ON ERROR, apply the same logic to ON EMPTY.

1.
The whole expression (jsexpr->on_error->expr) could be compiled under
the ErrorSaveContext, so any part of it
may report an error softly; without a COERCION_FINISH step afterwards
unconditionally, that
error is never handled.
That is not OK if we later want to raise the error, which is the case here.

2.
By the time the coercion step from ExecInitJsonCoercion runs, a soft error
may already have occurred during expression evaluation (DEFAULT ON
ERROR, DEFAULT ON EMPTY).
ExecEvalJsonCoercion should check for that first and, if so,
set resnull and resvalue and return earlier.

I found this issue while working on
https://commitfest.postgresql.org/patch/5941.

I don't think we need to add any extra comments.
/*
* Steps to evaluate the ON ERROR expression; handle errors softly to
* rethrow them in COERCION_FINISH step that will be added later.
*/
This comment is OK even if we unconditionally add a COERCION_FINISH step.

We could executing EEOP_JSONEXPR_COERCION_FINISH only when escontext
is non-NULL.
But, adding EEOP_JSONEXPR_COERCION_FINISH unconditionally feels more
intuitive and the cost seems very little.

I haven't looked at the patch, but could you specify whether your
patch fixes a live bug or is an improvement you found while working on
the linked thread? I don't understand which is the case because your
report doesn't have an example.

--
Thanks, Amit Langote

#3jian he
jian.universality@gmail.com
In reply to: Amit Langote (#2)
Re: SQL/JSON DEFAULT ON ERROR/ON EMPTY evaluation fail should rethrow error unconditionally

On Wed, Sep 16, 2026 at 10:48 AM Amit Langote <amitlangote09@gmail.com> wrote:

Hi Jian,

I haven't looked at the patch, but could you specify whether your
patch fixes a live bug or is an improvement you found while working on
the linked thread? I don't understand which is the case because your
report doesn't have an example.

Apologies for the poor communication.

In src/test/regress/expected/sqljson_queryfuncs.out, we have lots of
ERROR: could not coerce ON ERROR expression (DEFAULT) to the RETURNING type

The comments in ExecInitJsonExpr also says that, for DEFAULT expr ON ERROR and
DEFAULT expr ON EMPTY, we evaluate the DEFAULT expression in an error-soft way
*but* rethrow the error, I assume the purpose is for better error message.

However, in the master branch, there are some cases where we do not
rethrow the soft error.
For example, I believe the query below should return an ERROR.
SELECT JSON_VALUE('"a"', '$' RETURNING int DEFAULT (('a' || (random()
* 0)::int)::int + 0) ON ERROR);

--
jian
https://www.enterprisedb.com/

#4Amit Langote
amitlangote09@gmail.com
In reply to: jian he (#3)
Re: SQL/JSON DEFAULT ON ERROR/ON EMPTY evaluation fail should rethrow error unconditionally

On Wed, Sep 16, 2026 at 12:01 PM jian he <jian.universality@gmail.com> wrote:

On Wed, Sep 16, 2026 at 10:48 AM Amit Langote <amitlangote09@gmail.com> wrote:

Hi Jian,

I haven't looked at the patch, but could you specify whether your
patch fixes a live bug or is an improvement you found while working on
the linked thread? I don't understand which is the case because your
report doesn't have an example.

Apologies for the poor communication.

In src/test/regress/expected/sqljson_queryfuncs.out, we have lots of
ERROR: could not coerce ON ERROR expression (DEFAULT) to the RETURNING type

The comments in ExecInitJsonExpr also says that, for DEFAULT expr ON ERROR and
DEFAULT expr ON EMPTY, we evaluate the DEFAULT expression in an error-soft way
*but* rethrow the error, I assume the purpose is for better error message.

However, in the master branch, there are some cases where we do not
rethrow the soft error.
For example, I believe the query below should return an ERROR.
SELECT JSON_VALUE('"a"', '$' RETURNING int DEFAULT (('a' || (random()
* 0)::int)::int + 0) ON ERROR);

Thanks for providing the example. While playing around with that, I
noticed that you do get error when parentheses are moved:

postgres=# SELECT JSON_VALUE('"a"', '$' RETURNING int DEFAULT ('a' ||
((random()* 0)::int)::int + 0) ON ERROR);
ERROR: could not coerce ON ERROR expression (DEFAULT) to the RETURNING type
DETAIL: invalid input syntax for type integer: "a0"

I haven't checked but I suppose your patch ensures the query you
shared produces the error like this.

--
Thanks, Amit Langote

#5jian he
jian.universality@gmail.com
In reply to: Amit Langote (#4)
Re: SQL/JSON DEFAULT ON ERROR/ON EMPTY evaluation fail should rethrow error unconditionally

On Wed, Sep 16, 2026 at 11:29 AM Amit Langote <amitlangote09@gmail.com> wrote:

Thanks for providing the example. While playing around with that, I
noticed that you do get error when parentheses are moved:

postgres=# SELECT JSON_VALUE('"a"', '$' RETURNING int DEFAULT ('a' ||
((random()* 0)::int)::int + 0) ON ERROR);
ERROR: could not coerce ON ERROR expression (DEFAULT) to the RETURNING type
DETAIL: invalid input syntax for type integer: "a0"

I haven't checked but I suppose your patch ensures the query you
shared produces the error like this.

Yes.

I think
SELECT JSON_VALUE('"a"', '$' RETURNING int DEFAULT (('a' || (random()
* 0)::int)::int + 0) ON ERROR);

SELECT JSON_VALUE('"a"', '$' RETURNING int DEFAULT (('a' || (random()
* 0)::int)::int ) ON ERROR);

They should behave the same; the resulting values might differ
(assuming no overflow).

While working on the CAST DEFAULT patch
(https://commitfest.postgresql.org/patch/5941/), I found another bug related to
this thread: after a soft error has been reported, we didn't return earlier.
and let the code continues. Since it mostly affects SQL/JSON, I'm posting it
here too.

CREATE DOMAIN dchk AS int CHECK ((1 / coalesce(VALUE, 0)) IS NOT NULL);
SELECT JSON_VALUE(jsonb '"x"', '$' RETURNING dchk DEFAULT 11 ON ERROR);
SELECT JSON_VALUE(jsonb '"x"', '$' RETURNING int DEFAULT 11 ON ERROR);

I belive the above should return the same result 11. Currentlty the
first one failed with
ERROR: division by zero

SELECT JSON_QUERY(jsonb '["x"]', '$' RETURNING dchk[] DEFAULT '{11}' ON ERROR);
It should return {11} instead of throwing an error.

So in many places, once SOFT_ERROR_OCCURRED is true, we should return
early or handle the error specially, rather than carry on.
Please review the attached patch commit message, which I believe
explains it clearly (i hope).

--
jian
https://www.enterprisedb.com/

Attachments:

t253803_5
v2-0001-Fix-SQL-JSON-error-handling-after-a-soft-error-ha.patchtext/x-patch; charset=US-ASCII; name=v2-0001-Fix-SQL-JSON-error-handling-after-a-soft-error-ha.patchDownload+178-26
#6Amit Langote
amitlangote09@gmail.com
In reply to: jian he (#5)
Re: SQL/JSON DEFAULT ON ERROR/ON EMPTY evaluation fail should rethrow error unconditionally

Hi Jian,

On Mon, Oct 26, 2026 at 9:12 PM jian he <jian.universality@gmail.com> wrote:

On Wed, Sep 16, 2026 at 11:29 AM Amit Langote <amitlangote09@gmail.com> wrote:

Thanks for providing the example. While playing around with that, I
noticed that you do get error when parentheses are moved:

postgres=# SELECT JSON_VALUE('"a"', '$' RETURNING int DEFAULT ('a' ||
((random()* 0)::int)::int + 0) ON ERROR);
ERROR: could not coerce ON ERROR expression (DEFAULT) to the RETURNING type
DETAIL: invalid input syntax for type integer: "a0"

I haven't checked but I suppose your patch ensures the query you
shared produces the error like this.

Yes.

I think
SELECT JSON_VALUE('"a"', '$' RETURNING int DEFAULT (('a' || (random()
* 0)::int)::int + 0) ON ERROR);

SELECT JSON_VALUE('"a"', '$' RETURNING int DEFAULT (('a' || (random()
* 0)::int)::int ) ON ERROR);

They should behave the same; the resulting values might differ
(assuming no overflow).

While working on the CAST DEFAULT patch
(https://commitfest.postgresql.org/patch/5941/), I found another bug related to
this thread: after a soft error has been reported, we didn't return earlier.
and let the code continues. Since it mostly affects SQL/JSON, I'm posting it
here too.

CREATE DOMAIN dchk AS int CHECK ((1 / coalesce(VALUE, 0)) IS NOT NULL);
SELECT JSON_VALUE(jsonb '"x"', '$' RETURNING dchk DEFAULT 11 ON ERROR);
SELECT JSON_VALUE(jsonb '"x"', '$' RETURNING int DEFAULT 11 ON ERROR);

I belive the above should return the same result 11. Currentlty the
first one failed with
ERROR: division by zero

SELECT JSON_QUERY(jsonb '["x"]', '$' RETURNING dchk[] DEFAULT '{11}' ON ERROR);
It should return {11} instead of throwing an error.

So in many places, once SOFT_ERROR_OCCURRED is true, we should return
early or handle the error specially, rather than carry on.
Please review the attached patch commit message, which I believe
explains it clearly (i hope).

Thanks for reminding me of this thread. I agree about the second bug
and your proposed fix.

I’ve looked at the patch and it seems to be fixing the following two bugs:

1. Lack of a COERCION_FINISH step after ON ERROR/EMPTY expression
evaluation in some cases meant the soft error saved during that
evaluation was never rethrown and the query silently returned NULL.

2. Once a soft error has occurred, the dummy NULL it leaves behind
should not be processed any further, but in a few places
(CoerceToDomain, populate_domain(), populate_record(),
ExecEvalJsonCoercion() called on the DEFAULT result) it currently is.

I decided to break it down into attached two patches along those lines.

--
Thanks, Amit Langote

Attachments:

t253803_6
v3-0002-SQL-JSON-fix-error-handling-when-coercing-to-a-do.patchapplication/x-patch; name=v3-0002-SQL-JSON-fix-error-handling-when-coercing-to-a-do.patchDownload+129-1
v3-0001-SQL-JSON-always-rethrow-soft-errors-from-DEFAULT-.patchapplication/x-patch; name=v3-0001-SQL-JSON-always-rethrow-soft-errors-from-DEFAULT-.patchDownload+51-12
#7jian he
jian.universality@gmail.com
In reply to: Amit Langote (#6)
Re: SQL/JSON DEFAULT ON ERROR/ON EMPTY evaluation fail should rethrow error unconditionally

On Tue, Oct 27, 2026 at 9:22 PM Amit Langote <amitlangote09@gmail.com> wrote:

I’ve looked at the patch and it seems to be fixing the following two bugs:

1. Lack of a COERCION_FINISH step after ON ERROR/EMPTY expression
evaluation in some cases meant the soft error saved during that
evaluation was never rethrown and the query silently returned NULL.

Hi. in ExecInitJsonExpr, first we have:

escontext = jsexpr->on_error->btype != JSON_BEHAVIOR_ERROR ?
&jsestate->escontext : NULL;

then

if (jsexpr->on_error->btype != JSON_BEHAVIOR_ERROR &&
(!(IsA(jsexpr->on_error->expr, Const) &&
((Const *) jsexpr->on_error->expr)->constisnull) ||
returning_domain))
{
}

Within the IF branch above, escontext is never NULL, so the `if
(escontext)` check can be removed.
The comment there needs updating accordingly.

For ON EMPTY clause

if (jsexpr->on_empty != NULL &&
jsexpr->on_empty->btype != JSON_BEHAVIOR_ERROR &&
(!(IsA(jsexpr->on_empty->expr, Const) &&
((Const *) jsexpr->on_empty->expr)->constisnull) ||
returning_domain))
{

}

escontext can be NULL. So, the comment
/*
* Steps to evaluate the ON EMPTY expression; handle errors softly to
* rethrow them in COERCION_FINISH step that will be added later.
*/

is not fully accurate. We can change it to:

/*
* Steps to evaluate the ON EMPTY expression. Unless ON ERROR is
* ERROR, errors are handled softly, to be rethrown by the
* COERCION_FINISH step added below; otherwise they are thrown
* directly.
*/

2. Once a soft error has occurred, the dummy NULL it leaves behind
should not be processed any further, but in a few places
(CoerceToDomain, populate_domain(), populate_record(),
ExecEvalJsonCoercion() called on the DEFAULT result) it currently is.

--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -5188,6 +5188,21 @@ ExecEvalJsonCoercion(ExprState *state, ExprEvalStep *op,
 {
  ErrorSaveContext *escontext = op->d.jsonexpr_coercion.escontext;
+ /*
+ * An ON ERROR or ON EMPTY DEFAULT expression is evaluated with escontext
+ * in effect, so if it failed, the error has been saved in escontext and
+ * the value we were given to coerce is a dummy NULL.  Return it as is;
+ * the COERCION_FINISH step that follows will throw the saved error, and
+ * running the coercion on the NULL might instead throw a hard error or
+ * overwrite that saved error.
+ */
+ if (SOFT_ERROR_OCCURRED(escontext))
+ {
+ *op->resnull = true;
+ *op->resvalue = (Datum) 0;
+ return;
+ }
+
The first sentence of the comment is not entirely accurate.
The value in op->resvalue is not guaranteed to be a dummy NULL.
For example, ExecInitCoerceToDomain, writes the result of domain CHECK
constraint check into
scratch->d.domaincheck.checkvalue rather than op->resvalue, so after a soft
CHECK violation op->resvalue still holds the original value.

--
jian
https://www.enterprisedb.com/

#8Amit Langote
amitlangote09@gmail.com
In reply to: jian he (#7)
Re: SQL/JSON DEFAULT ON ERROR/ON EMPTY evaluation fail should rethrow error unconditionally

Hi,

On Wed, Oct 28, 2026 at 2:38 PM jian he <jian.universality@gmail.com> wrote:

On Tue, Oct 27, 2026 at 9:22 PM Amit Langote <amitlangote09@gmail.com> wrote:

I’ve looked at the patch and it seems to be fixing the following two bugs:

1. Lack of a COERCION_FINISH step after ON ERROR/EMPTY expression
evaluation in some cases meant the soft error saved during that
evaluation was never rethrown and the query silently returned NULL.

Hi. in ExecInitJsonExpr, first we have:

escontext = jsexpr->on_error->btype != JSON_BEHAVIOR_ERROR ?
&jsestate->escontext : NULL;

then

if (jsexpr->on_error->btype != JSON_BEHAVIOR_ERROR &&
(!(IsA(jsexpr->on_error->expr, Const) &&
((Const *) jsexpr->on_error->expr)->constisnull) ||
returning_domain))
{
}

Within the IF branch above, escontext is never NULL, so the `if
(escontext)` check can be removed.
The comment there needs updating accordingly.

For ON EMPTY clause

if (jsexpr->on_empty != NULL &&
jsexpr->on_empty->btype != JSON_BEHAVIOR_ERROR &&
(!(IsA(jsexpr->on_empty->expr, Const) &&
((Const *) jsexpr->on_empty->expr)->constisnull) ||
returning_domain))
{

}

escontext can be NULL. So, the comment
/*
* Steps to evaluate the ON EMPTY expression; handle errors softly to
* rethrow them in COERCION_FINISH step that will be added later.
*/

is not fully accurate. We can change it to:

/*
* Steps to evaluate the ON EMPTY expression. Unless ON ERROR is
* ERROR, errors are handled softly, to be rethrown by the
* COERCION_FINISH step added below; otherwise they are thrown
* directly.
*/

2. Once a soft error has occurred, the dummy NULL it leaves behind
should not be processed any further, but in a few places
(CoerceToDomain, populate_domain(), populate_record(),
ExecEvalJsonCoercion() called on the DEFAULT result) it currently is.

--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -5188,6 +5188,21 @@ ExecEvalJsonCoercion(ExprState *state, ExprEvalStep *op,
{
ErrorSaveContext *escontext = op->d.jsonexpr_coercion.escontext;
+ /*
+ * An ON ERROR or ON EMPTY DEFAULT expression is evaluated with escontext
+ * in effect, so if it failed, the error has been saved in escontext and
+ * the value we were given to coerce is a dummy NULL.  Return it as is;
+ * the COERCION_FINISH step that follows will throw the saved error, and
+ * running the coercion on the NULL might instead throw a hard error or
+ * overwrite that saved error.
+ */
+ if (SOFT_ERROR_OCCURRED(escontext))
+ {
+ *op->resnull = true;
+ *op->resvalue = (Datum) 0;
+ return;
+ }
+
The first sentence of the comment is not entirely accurate.
The value in op->resvalue is not guaranteed to be a dummy NULL.
For example, ExecInitCoerceToDomain, writes the result of domain CHECK
constraint check into
scratch->d.domaincheck.checkvalue rather than op->resvalue, so after a soft
CHECK violation op->resvalue still holds the original value.

You're correct on all counts. I've fixed that in the attached patch.
Thanks for checking.

--
Thanks, Amit Langote

Attachments:

t253803_8
v4-0002-SQL-JSON-fix-error-handling-when-coercing-to-a-do.patchapplication/octet-stream; name=v4-0002-SQL-JSON-fix-error-handling-when-coercing-to-a-do.patchDownload+128-1
v4-0001-SQL-JSON-always-rethrow-soft-errors-from-DEFAULT-.patchapplication/octet-stream; name=v4-0001-SQL-JSON-always-rethrow-soft-errors-from-DEFAULT-.patchDownload+58-21
#9jian he
jian.universality@gmail.com
In reply to: Amit Langote (#8)
Re: SQL/JSON DEFAULT ON ERROR/ON EMPTY evaluation fail should rethrow error unconditionally

On Wed, Oct 28, 2026 at 6:46 PM Amit Langote <amitlangote09@gmail.com> wrote:

You're correct on all counts. I've fixed that in the attached patch.
Thanks for checking.

These new comments and commit message look good to me.
v4 looks good to me.

--
jian
https://www.enterprisedb.com/

#10Amit Langote
amitlangote09@gmail.com
In reply to: jian he (#9)
Re: SQL/JSON DEFAULT ON ERROR/ON EMPTY evaluation fail should rethrow error unconditionally

On Thu, Oct 29, 2026 at 8:57 AM jian he <jian.universality@gmail.com> wrote:

On Wed, Oct 28, 2026 at 6:46 PM Amit Langote <amitlangote09@gmail.com> wrote:

You're correct on all counts. I've fixed that in the attached patch.
Thanks for checking.

These new comments and commit message look good to me.
v4 looks good to me.

Thanks, pushed.

--
Thanks, Amit Langote