Re: CAST(... ON DEFAULT) - WIP build on top of Error-Safe User Functions

From: jian he <jian(dot)universality(at)gmail(dot)com>
To: Peter Eisentraut <peter(at)eisentraut(dot)org>
Cc: Corey Huinker <corey(dot)huinker(at)gmail(dot)com>, Amul Sul <sulamul(at)gmail(dot)com>, Kirill Reshke <reshkekirill(at)gmail(dot)com>, Vik Fearing <vik(at)postgresfriends(dot)org>, Isaac Morland <isaac(dot)morland(at)gmail(dot)com>, pgsql-hackers(at)lists(dot)postgresql(dot)org
Subject: Re: CAST(... ON DEFAULT) - WIP build on top of Error-Safe User Functions
Date: 2026-03-26 08:59:56
Message-ID: CACJufxH_1EtEBMb0JvxaM3Gmnt33HYrS37m5eYjJ_OfBkMVFJg@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Currently, when a valid ErrorSaveContext is passed to state->escontext
(ExprState->escontext),
ExecInitExprRec is designed to compile the entire expression tree
using soft errors.
Consider the following example:
create table t1(a text, b text, c int, d int8);
create domain d2 as text check (value <> 'a');
insert into t1(a, d) values('a', 2147483648);
select cast (cast(d as int) as text default null on conversion
error) from t1; -- queryA
select cast (cast(a as d2) as text default null on conversion
error) from t1; -- queryB
select cast (cast(a as int) as text default null on conversion
error) from t1; -- queryC

With V24, for queryC, ExecInitExprRec will compile the inner ``cast(a as int)``
error-safe way. This is just a subexpression of the main outer
cast(... as text default ...) node,
we may want the inner cast to be evaluated not error-safe.

To resolve this, we need to differentiate whether the specific nodes produced by
coerce_to_target_type->build_coercion_expression/coerce_to_domain
should be error-safe.
This means the resulting nodes (FuncExpr, ArrayCoerceExpr,
CoerceViaIO, CoerceToDomain) need a boolean flag.

We have already solved this for FuncExpr in [1] by adding an errorsafe field. We
now need to add a similar errorsafe boolean to CoerceViaIO and CoerceToDomain.

Therefore, for safe error evaluation: 1. ExecInitExprRec, ExprState->escontext
must be a valid ErrorSaveContext 2. The expression node (need a booleaan) to
tell ExecInitExprRec that compile this in an error safe manner.

[1]: https://postgr.es/m/CACJufxGbw9iNT8QVm4QD9cPFKnDnvDBQp7AGxkoqDa-JjzVXmg@mail.gmail.com

Summary: Making the above queryA, queryB, and queryC return NULL is
straightforward; however, forcing all of them to throw an error is non-trivial
because it involves compiling/evaluating some subexpressions in an
error-safe manner while
others are not.

What do you think?

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

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message John Naylor 2026-03-26 09:22:07 Re: Adjust error message for CREATE STATISTICS to account for expressions
Previous Message David Geier 2026-03-26 08:50:28 Re: Use correct collation in pg_trgm