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

Поиск
Список
Период
Сортировка
Искать

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
Вложения:

Attached is my work in progress to implement the changes to the CAST() function as proposed by Vik Fearing.

This work builds upon the Error-safe User Functions work currently ongoing.

The proposed changes are as follows:

CAST(expr AS typename)
    continues to behave as before.

CAST(expr AS typename ERROR ON ERROR)
    has the identical behavior as the unadorned CAST() above.

CAST(expr AS typename NULL ON ERROR)
    will use error-safe functions to do the cast of expr, and will return NULL if the cast fails.

CAST(expr AS typename DEFAULT expr2 ON ERROR)
    will use error-safe functions to do the cast of expr, and will return expr2 if the cast fails.

There is an additional FORMAT parameter that I have not yet implemented, my understanding is that it is largely intended for DATE/TIME field conversions, but others are certainly possible.
CAST(expr AS typename FORMAT fmt DEFAULT expr2 ON ERROR)

What is currently working:
- Any scalar expression that can be evaluated at parse time. These tests from cast.sql all currently work:

VALUES (CAST('error' AS integer));
VALUES (CAST('error' AS integer ERROR ON ERROR));
VALUES (CAST('error' AS integer NULL ON ERROR));
VALUES (CAST('error' AS integer DEFAULT 42 ON ERROR));

SELECT CAST('{123,abc,456}' AS integer[] DEFAULT '{-789}' ON ERROR) as array_test1;

- Scalar values evaluated at runtime.

CREATE TEMPORARY TABLE t(t text);
INSERT INTO t VALUES ('a'), ('1'), ('b'), (2);
SELECT CAST(t.t AS integer DEFAULT -1 ON ERROR) AS foo FROM t;
 foo
-----
  -1
   1
  -1
   2
(4 rows)


Along the way, I made a few design decisions, each of which is up for debate:

First, I created OidInputFunctionCallSafe, which is to OidInputFunctionCall what InputFunctionCallSafe is to InputFunctionCall. Given that the only place I ended up using it was stringTypeDatumSafe(), it may be possible to just move that code inside stringTypeDatumSafe.

Next, I had a need for FuncExpr, CoerceViaIO, and ArrayCoerce to all report if their expr argument failed, and if not, just past the evaluation of expr2. Rather than duplicate this logic in several places, I chose instead to modify CoalesceExpr to allow for an error-test mode in addition to its default null-test mode, and then to provide this altered node with two expressions, the first being the error-safe typecast of expr and the second being the non-error-safe typecast of expr2.

I still don't have array-to-array casts working, as the changed I would likely need to make to ArrayCoerce get somewhat invasive, so this seemed like a good time to post my work so far and solicit some feedback beyond what I've already been getting from Jeff Davis and Michael Paquier.

I've sidestepped domains as well for the time being as well as avoiding JIT issues entirely.

No documentation is currently prepared. All but one of the regression test queries work, the one that is currently failing is:

SELECT CAST('{234,def,567}'::text[] AS integer[] DEFAULT '{-1011}' ON ERROR) as array_test2;

Other quirks:
- an unaliased CAST ON DEFAULT will return the column name of "coalesce", which internally is true, but obviously would be quite confusing to a user.

As a side observation, I noticed that the optimizer already tries to resolve expressions based on constants and to collapse expression trees where possible, which makes me wonder if the work done to do the same in transformTypeCast/ and coerce_to_target_type and coerce_type isn't also wasted.

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

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Corey Huinker  writes:
> The proposed changes are as follows:
> CAST(expr AS typename)
>     continues to behave as before.
> CAST(expr AS typename ERROR ON ERROR)
>     has the identical behavior as the unadorned CAST() above.
> CAST(expr AS typename NULL ON ERROR)
>     will use error-safe functions to do the cast of expr, and will return
> NULL if the cast fails.
> CAST(expr AS typename DEFAULT expr2 ON ERROR)
>     will use error-safe functions to do the cast of expr, and will return
> expr2 if the cast fails.

While I approve of trying to get some functionality in this area,
I'm not sure that extending CAST is a great idea, because I'm afraid
that the SQL committee will do something that conflicts with it.
If we know that they are about to standardize exactly this syntax,
where is that information available?  If we don't know that,
I'd prefer to invent some kind of function or other instead of
extending the grammar.

			regards, tom lane


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

От:
vignesh C <vignesh21@gmail.com>
Дата:
On Tue, 20 Dec 2022 at 04:27, Corey Huinker  wrote:
>
>
> Attached is my work in progress to implement the changes to the CAST() function as proposed by Vik Fearing.
>
> This work builds upon the Error-safe User Functions work currently ongoing.
>
> The proposed changes are as follows:
>
> CAST(expr AS typename)
>     continues to behave as before.
>
> CAST(expr AS typename ERROR ON ERROR)
>     has the identical behavior as the unadorned CAST() above.
>
> CAST(expr AS typename NULL ON ERROR)
>     will use error-safe functions to do the cast of expr, and will return NULL if the cast fails.
>
> CAST(expr AS typename DEFAULT expr2 ON ERROR)
>     will use error-safe functions to do the cast of expr, and will return expr2 if the cast fails.
>
> There is an additional FORMAT parameter that I have not yet implemented, my understanding is that it is largely intended for DATE/TIME field conversions, but others are certainly possible.
> CAST(expr AS typename FORMAT fmt DEFAULT expr2 ON ERROR)
>
> What is currently working:
> - Any scalar expression that can be evaluated at parse time. These tests from cast.sql all currently work:
>
> VALUES (CAST('error' AS integer));
> VALUES (CAST('error' AS integer ERROR ON ERROR));
> VALUES (CAST('error' AS integer NULL ON ERROR));
> VALUES (CAST('error' AS integer DEFAULT 42 ON ERROR));
>
> SELECT CAST('{123,abc,456}' AS integer[] DEFAULT '{-789}' ON ERROR) as array_test1;
>
> - Scalar values evaluated at runtime.
>
> CREATE TEMPORARY TABLE t(t text);
> INSERT INTO t VALUES ('a'), ('1'), ('b'), (2);
> SELECT CAST(t.t AS integer DEFAULT -1 ON ERROR) AS foo FROM t;
>  foo
> -----
>   -1
>    1
>   -1
>    2
> (4 rows)
>
>
> Along the way, I made a few design decisions, each of which is up for debate:
>
> First, I created OidInputFunctionCallSafe, which is to OidInputFunctionCall what InputFunctionCallSafe is to InputFunctionCall. Given that the only place I ended up using it was stringTypeDatumSafe(), it may be possible to just move that code inside stringTypeDatumSafe.
>
> Next, I had a need for FuncExpr, CoerceViaIO, and ArrayCoerce to all report if their expr argument failed, and if not, just past the evaluation of expr2. Rather than duplicate this logic in several places, I chose instead to modify CoalesceExpr to allow for an error-test mode in addition to its default null-test mode, and then to provide this altered node with two expressions, the first being the error-safe typecast of expr and the second being the non-error-safe typecast of expr2.
>
> I still don't have array-to-array casts working, as the changed I would likely need to make to ArrayCoerce get somewhat invasive, so this seemed like a good time to post my work so far and solicit some feedback beyond what I've already been getting from Jeff Davis and Michael Paquier.
>
> I've sidestepped domains as well for the time being as well as avoiding JIT issues entirely.
>
> No documentation is currently prepared. All but one of the regression test queries work, the one that is currently failing is:
>
> SELECT CAST('{234,def,567}'::text[] AS integer[] DEFAULT '{-1011}' ON ERROR) as array_test2;
>
> Other quirks:
> - an unaliased CAST ON DEFAULT will return the column name of "coalesce", which internally is true, but obviously would be quite confusing to a user.
>
> As a side observation, I noticed that the optimizer already tries to resolve expressions based on constants and to collapse expression trees where possible, which makes me wonder if the work done to do the same in transformTypeCast/ and coerce_to_target_type and coerce_type isn't also wasted.

CFBot shows some compilation errors as in [1], please post an updated
version for the same:
[02:53:44.829] time make -s -j${BUILD_JOBS} world-bin
[02:55:41.164] llvmjit_expr.c: In function ‘llvm_compile_expr’:
[02:55:41.164] llvmjit_expr.c:928:6: error: ‘v_resnull’ undeclared
(first use in this function); did you mean ‘v_resnullp’?
[02:55:41.164] 928 | v_resnull = LLVMBuildLoad(b, v_reserrorp, "");
[02:55:41.164] | ^~~~~~~~~
[02:55:41.164] | v_resnullp
[02:55:41.164] llvmjit_expr.c:928:6: note: each undeclared identifier
is reported only once for each function it appears in
[02:55:41.164] llvmjit_expr.c:928:35: error: ‘v_reserrorp’ undeclared
(first use in this function); did you mean ‘v_reserror’?
[02:55:41.164] 928 | v_resnull = LLVMBuildLoad(b, v_reserrorp, "");
[02:55:41.164] | ^~~~~~~~~~~
[02:55:41.164] | v_reserror
[02:55:41.165] make[2]: *** [: llvmjit_expr.o] Error 1
[02:55:41.165] make[2]: *** Waiting for unfinished jobs....
[02:55:45.495] make[1]: *** [Makefile:42: all-backend/jit/llvm-recurse] Error 2
[02:55:45.495] make: *** [GNUmakefile:21: world-bin-src-recurse] Error 2

[1] - https://cirrus-ci.com/task/6687753371385856?logs=gcc_warning#L448

Regards,
Vignesh


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

От:
Andrew Dunstan <andrew@dunslane.net>
Дата:

On 2023-01-02 Mo 10:57, Tom Lane wrote:
> Corey Huinker  writes:
>> The proposed changes are as follows:
>> CAST(expr AS typename)
>>     continues to behave as before.
>> CAST(expr AS typename ERROR ON ERROR)
>>     has the identical behavior as the unadorned CAST() above.
>> CAST(expr AS typename NULL ON ERROR)
>>     will use error-safe functions to do the cast of expr, and will return
>> NULL if the cast fails.
>> CAST(expr AS typename DEFAULT expr2 ON ERROR)
>>     will use error-safe functions to do the cast of expr, and will return
>> expr2 if the cast fails.
> While I approve of trying to get some functionality in this area,
> I'm not sure that extending CAST is a great idea, because I'm afraid
> that the SQL committee will do something that conflicts with it.
> If we know that they are about to standardize exactly this syntax,
> where is that information available?  If we don't know that,
> I'd prefer to invent some kind of function or other instead of
> extending the grammar.


+1


cheers


andrew

--
Andrew Dunstan
EDB: https://www.enterprisedb.com



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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:



On Mon, Jan 2, 2023 at 10:57 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
Corey Huinker <corey.huinker@gmail.com> writes:
> The proposed changes are as follows:
> CAST(expr AS typename)
>     continues to behave as before.
> CAST(expr AS typename ERROR ON ERROR)
>     has the identical behavior as the unadorned CAST() above.
> CAST(expr AS typename NULL ON ERROR)
>     will use error-safe functions to do the cast of expr, and will return
> NULL if the cast fails.
> CAST(expr AS typename DEFAULT expr2 ON ERROR)
>     will use error-safe functions to do the cast of expr, and will return
> expr2 if the cast fails.

While I approve of trying to get some functionality in this area,
I'm not sure that extending CAST is a great idea, because I'm afraid
that the SQL committee will do something that conflicts with it.
If we know that they are about to standardize exactly this syntax,
where is that information available?  If we don't know that,
I'd prefer to invent some kind of function or other instead of
extending the grammar.

                        regards, tom lane

I'm going off the spec that Vik presented in https://www.postgresql.org/message-id/f8600a3b-f697-2577-8fea-f40d3e18bea8@postgresfriends.org which is his effort to get it through the SQL committee. I was alreading thinking about how to get the SQLServer TRY_CAST() function into postgres, so this seemed like the logical next step.

While the syntax may change, the underlying infrastructure would remain basically the same: we would need the ability to detect that a typecast had failed, and replace it with the default value, and handle that at parse time, or executor time, and handle array casts where the array has the default but the underlying elements can't.

It would be simple to move the grammar changes to their own patch if that removes a barrier for people.
 

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

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Corey Huinker  writes:
> On Mon, Jan 2, 2023 at 10:57 AM Tom Lane  wrote:
>> While I approve of trying to get some functionality in this area,
>> I'm not sure that extending CAST is a great idea, because I'm afraid
>> that the SQL committee will do something that conflicts with it.

> I'm going off the spec that Vik presented in
> https://www.postgresql.org/message-id/f8600a3b-f697-2577-8fea-f40d3e18bea8@postgresfriends.org
> which is his effort to get it through the SQL committee.

I'm pretty certain that sending something to pgsql-hackers will have
exactly zero impact on the SQL committee.  Is there anything actually
submitted to the committee, and if so what's its status?

			regards, tom lane


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

От:
Vik Fearing <vik@postgresfriends.org>
Дата:
On 1/3/23 19:14, Tom Lane wrote:
> Corey Huinker  writes:
>> On Mon, Jan 2, 2023 at 10:57 AM Tom Lane  wrote:
>>> While I approve of trying to get some functionality in this area,
>>> I'm not sure that extending CAST is a great idea, because I'm afraid
>>> that the SQL committee will do something that conflicts with it.
> 
>> I'm going off the spec that Vik presented in
>> https://www.postgresql.org/message-id/f8600a3b-f697-2577-8fea-f40d3e18bea8@postgresfriends.org
>> which is his effort to get it through the SQL committee.
> 
> I'm pretty certain that sending something to pgsql-hackers will have
> exactly zero impact on the SQL committee.  Is there anything actually
> submitted to the committee, and if so what's its status?

I have not posted my paper to the committee yet, but I plan to do so 
before the working group's meeting early February.  Just like with 
posting patches here, I cannot guarantee that it will get accepted but I 
will be arguing for it.

I don't think we should add that syntax until I do get it through the 
committee, just in case they change something.
-- 
Vik Fearing



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

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Vik Fearing  writes:
> I have not posted my paper to the committee yet, but I plan to do so 
> before the working group's meeting early February.  Just like with 
> posting patches here, I cannot guarantee that it will get accepted but I 
> will be arguing for it.

> I don't think we should add that syntax until I do get it through the 
> committee, just in case they change something.

Agreed.  So this is something we won't be able to put into v16;
it'll have to wait till there's something solid from the committee.

			regards, tom lane


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

От:
"Gregory Stark (as CFM)" <stark.cfm@gmail.com>
Дата:
On Tue, 3 Jan 2023 at 14:16, Tom Lane  wrote:
>
> Vik Fearing  writes:
>
> > I don't think we should add that syntax until I do get it through the
> > committee, just in case they change something.
>
> Agreed.  So this is something we won't be able to put into v16;
> it'll have to wait till there's something solid from the committee.

I guess I'll mark this Rejected in the CF then. Who knows when the SQL
committee will look at this...

-- 
Gregory Stark
As Commitfest Manager


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

От:
Isaac Morland <isaac.morland@gmail.com>
Дата:
On Mon, 19 Dec 2022 at 17:57, Corey Huinker <corey.huinker@gmail.com> wrote:

Attached is my work in progress to implement the changes to the CAST() function as proposed by Vik Fearing.

CAST(expr AS typename NULL ON ERROR)
    will use error-safe functions to do the cast of expr, and will return NULL if the cast fails.

CAST(expr AS typename DEFAULT expr2 ON ERROR)
    will use error-safe functions to do the cast of expr, and will return expr2 if the cast fails.

Is there any difference between NULL and DEFAULT NULL? 

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:


On Tue, Mar 28, 2023 at 2:53 PM Gregory Stark (as CFM) <stark.cfm@gmail.com> wrote:
On Tue, 3 Jan 2023 at 14:16, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> Vik Fearing <vik@postgresfriends.org> writes:
>
> > I don't think we should add that syntax until I do get it through the
> > committee, just in case they change something.
>
> Agreed.  So this is something we won't be able to put into v16;
> it'll have to wait till there's something solid from the committee.

I guess I'll mark this Rejected in the CF then. Who knows when the SQL
committee will look at this...

--
Gregory Stark
As Commitfest Manager

Yes, for now. I'm in touch with the pg-people on the committee and will resume work when there's something to act upon.
 

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
On Tue, Mar 28, 2023 at 3:25 PM Isaac Morland <isaac.morland@gmail.com> wrote:
On Mon, 19 Dec 2022 at 17:57, Corey Huinker <corey.huinker@gmail.com> wrote:

Attached is my work in progress to implement the changes to the CAST() function as proposed by Vik Fearing.

CAST(expr AS typename NULL ON ERROR)
    will use error-safe functions to do the cast of expr, and will return NULL if the cast fails.

CAST(expr AS typename DEFAULT expr2 ON ERROR)
    will use error-safe functions to do the cast of expr, and will return expr2 if the cast fails.

Is there any difference between NULL and DEFAULT NULL? 

What I think you're asking is: is there a difference between these two statements:

SELECT CAST(my_string AS integer NULL ON ERROR) FROM my_table;

SELECT CAST(my_string AS integer DEFAULT NULL ON ERROR) FROM my_table;

And as I understand it, the answer would be no, there is no practical difference. The first case is just a convenient shorthand, whereas the second case tees you up for a potentially complex expression. Before you ask, I believe the ON ERROR syntax could be made optional. As I implemented it, both cases create a default expression which then typecast to integer, and in both cases that expression would be a const-null, so the optimizer steps would very quickly collapse those steps into a plain old constant.


 

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
hi.
more preparation work has been committed.

1. SQL/JSON patch [1] added keyword ERROR
2. CoerceViaIo, CoerceToDomain can be evaluated error safe. see commit [2].
3. ExprState added ErrorSaveContext point, so before calling ExecInitExprRec
set valid ErrorSaveContext for ExprState->escontext we should evaluate
expression error softly.
see commit [2] also.

I only found oracle implement, [3].
Based on my reading of [4], it seems CAST(EXPRESSION AS TYPE DEFAULT
def_expr ON ERROR)
is not included in SQL:2023.

anyway, just share my POC based on the previous patch in this thread.
it will work for domain over composite, composite over domain.
example:
CREATE DOMAIN d_char3_not_null as char(3) NOT NULL;
CREATE TYPE comp_domain_with_typmod AS (a d_char3_not_null, b int);
SELECT CAST('(,42)' AS comp_domain_with_typmod DEFAULT NULL ON ERROR);
--return NULL


[1]: https://git.postgresql.org/cgit/postgresql.git/diff/src/backend/parser/gram.y?id=6185c9737cf48c9540782d88f12bd2912d6ca1cc
[2]: https://git.postgresql.org/cgit/postgresql.git/commit/?id=aaaf9449ec6be62cb0d30ed3588dc384f56274bf
[3] https://docs.oracle.com/en/database/oracle/oracle-database/23/sqlrf/CAST.html
[4] https://peter.eisentraut.org/blog/2023/04/04/sql-2023-is-finished-here-is-whats-new

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

От:
Vik Fearing <vik@postgresfriends.org>
Дата:

On 22/07/2025 03:59, jian he wrote:
> Based on my reading of [4], it seems CAST(EXPRESSION AS TYPE DEFAULT
> def_expr ON ERROR)
> is not included in SQL:2023.
>
> [4]https://peter.eisentraut.org/blog/2023/04/04/sql-2023-is-finished-here-is-whats-new


It was accepted into the standard after 2023 was released.  I am the 
author of this change in the standard, so feel free to ask me anything 
you're unsure about.

-- 

Vik Fearing



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

От:
jian he <jian.universality@gmail.com>
Дата:
On Tue, Jul 22, 2025 at 2:45 PM Vik Fearing  wrote:
>
> It was accepted into the standard after 2023 was released.  I am the
> author of this change in the standard, so feel free to ask me anything
> you're unsure about.
>

is the generally syntax as mentioned in this thread:
CAST(source_expression AS target_type DEFAULT default_expression ON ERROR)

if so, what's the restriction of default_expression?


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

От:
Vik Fearing <vik@postgresfriends.org>
Дата:

On 22/07/2025 12:19, jian he wrote:
> On Tue, Jul 22, 2025 at 2:45 PM Vik Fearing  wrote:
>> It was accepted into the standard after 2023 was released.  I am the
>> author of this change in the standard, so feel free to ask me anything
>> you're unsure about.
>>
> is the generally syntax as mentioned in this thread:
> CAST(source_expression AS target_type DEFAULT default_expression ON ERROR)
>
> if so, what's the restriction of default_expression?


The actual syntax is:


 ::=
     CAST 
          AS 
         [ FORMAT  ]
         [  ON CONVERSION ERROR ]
         


"CONVERSION" is probably a noise word, but it is there because A) Oracle 
wanted it there, and B) it makes sense because if the  fails, that is still a failure of the entire CAST.


The  is:


 ::=
     ERROR
   | NULL
   | DEFAULT 


but I am planning on removing the NULL variant in favor of having the 
 be a .  So it 
would be either ERROR ON CONVERSION ERROR (postgres's current behavior), 
or DEFAULT NULL ON CONVERSION ERROR.


An example of B) above would be: CAST('five' AS INTEGER DEFAULT 'six' ON 
CONVERSION ERROR).  'six' is no more an integer than 'five' is, so that 
would error out because the conversion error does not happen on the 
operand but on the default clause. CAST('five' AS INTEGER DEFAULT 6 ON 
CONVERSION ERROR) would work.

-- 

Vik Fearing



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

От:
Vik Fearing <vik@postgresfriends.org>
Дата:

On 22/07/2025 14:26, Vik Fearing wrote:
> The  is:
>
>  ::=
>     ERROR
>   | NULL
>   | DEFAULT 
>
> but I am planning on removing the NULL variant in favor of having the 
>  be a .  So 
> it would be either ERROR ON CONVERSION ERROR (postgres's current 
> behavior), or DEFAULT NULL ON CONVERSION ERROR. 


Sorry, I meant .


The point being that CAST(ARRAY['1', '2', 'three'] AS INTEGER ARRAY 
DEFAULT NULL ON CONVERSION ERROR) will give you (CAST NULL AS INTEGER 
ARRAY) and *not* ARRAY[1, 2, NULL].

-- 

Vik Fearing



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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:


On Tue, Jul 22, 2025 at 2:45 AM Vik Fearing <vik@postgresfriends.org> wrote:

On 22/07/2025 03:59, jian he wrote:
> Based on my reading of [4], it seems CAST(EXPRESSION AS TYPE DEFAULT
> def_expr ON ERROR)
> is not included in SQL:2023.
>
> [4]https://peter.eisentraut.org/blog/2023/04/04/sql-2023-is-finished-here-is-whats-new


It was accepted into the standard after 2023 was released.  I am the
author of this change in the standard, so feel free to ask me anything
you're unsure about.


That's excellent news. I was already planning on retrying this for v19, but I'll try sooner now.
 

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Tue, Jul 22, 2025 at 8:26 PM Vik Fearing  wrote:
>
> The actual syntax is:
>
>
>  ::=
>      CAST 
>           AS 
>          [ FORMAT  ]
>          [  ON CONVERSION ERROR ]
>          
>
>
> "CONVERSION" is probably a noise word, but it is there because A) Oracle
> wanted it there, and B) it makes sense because if the  behavior> fails, that is still a failure of the entire CAST.
>
>
> The  is:
>
>  ::=
>      ERROR
>    | NULL
>    | DEFAULT 
>
>
> but I am planning on removing the NULL variant in favor of having the
>  be a .  So it
> would be either ERROR ON CONVERSION ERROR (postgres's current behavior),
> or DEFAULT NULL ON CONVERSION ERROR.
>
>
> An example of B) above would be: CAST('five' AS INTEGER DEFAULT 'six' ON
> CONVERSION ERROR).  'six' is no more an integer than 'five' is, so that
> would error out because the conversion error does not happen on the
> operand but on the default clause. CAST('five' AS INTEGER DEFAULT 6 ON
> CONVERSION ERROR) would work.
>

hi.

>  ::=
>      ERROR
>    | NULL
>    | DEFAULT 

for 
I disallow it from returning a set, or using aggregate or window functions.
For example, the following three cases will fail:

+SELECT CAST('a' as int DEFAULT sum(1) ON CONVERSION ERROR); --error
+SELECT CAST('a' as int DEFAULT sum(1) over() ON CONVERSION ERROR); --error
+SELECT CAST('a' as int DEFAULT ret_setint() ON CONVERSION ERROR) --error
(ret_setint function is warped as (select 1 union all select 2))

for array coerce, which you already mentioned, i think the following
is what we expected.
+SELECT CAST('{234,def,567}'::text[] AS integer[] DEFAULT '{-1011}' ON
CONVERSION ERROR);
+  int4
+---------
+ {-1011}
+(1 row)

I didn't implement the [ FORMAT  ] part for now.
please check the attached regress test and tests expected result.

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

От:
jian he <jian.universality@gmail.com>
Дата:
On Tue, Jul 22, 2025 at 8:26 PM Vik Fearing  wrote:
>
>
> On 22/07/2025 12:19, jian he wrote:
> > On Tue, Jul 22, 2025 at 2:45 PM Vik Fearing  wrote:
> >> It was accepted into the standard after 2023 was released.  I am the
> >> author of this change in the standard, so feel free to ask me anything
> >> you're unsure about.
> >>
> > is the generally syntax as mentioned in this thread:
> > CAST(source_expression AS target_type DEFAULT default_expression ON ERROR)
> >
> > if so, what's the restriction of default_expression?
>
>
> The actual syntax is:
>
>
>  ::=
>      CAST 
>           AS 
>          [ FORMAT  ]
>          [  ON CONVERSION ERROR ]
>          
>
> "CONVERSION" is probably a noise word, but it is there because A) Oracle
> wanted it there, and B) it makes sense because if the  behavior> fails, that is still a failure of the entire CAST.
>
>
> The  is:
>
>
>  ::=
>      ERROR
>    | NULL
>    | DEFAULT 
>
>

hi.

just want to confirm my understanding of ``[ FORMAT  ]``.

SELECT CAST('2022-13-32' AS DATE FORMAT 'YYYY-MM-DD' DEFAULT NULL ON
CONVERSION ERROR);
will return NULL.
because  ``SELECT to_date('2022-13-32', 'YYYY-MM-DD');``
will error out, so the above query will fall back to the DEFAULT
expression evaluation.


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

От:
Vik Fearing <vik@postgresfriends.org>
Дата:


On 24/07/2025 03:22, jian he wrote:
+SELECT CAST('a' as int DEFAULT sum(1) ON CONVERSION ERROR); --error
+SELECT CAST('a' as int DEFAULT sum(1) over() ON CONVERSION ERROR); --error


This seems like an arbitrary restriction.  Can you explain why this is necessary?  Those same expressions are allowed as the <cast operand>.


+SELECT CAST('a' as int DEFAULT ret_setint() ON CONVERSION ERROR) --error
(ret_setint function is warped as (select 1 union all select 2))


This makes sense to me.


for array coerce, which you already mentioned, i think the following
is what we expected.
+SELECT CAST('{234,def,567}'::text[] AS integer[] DEFAULT '{-1011}' ON
CONVERSION ERROR);
+  int4
+---------
+ {-1011}
+(1 row)


Yes, that looks correct to me.


I didn't implement the [ FORMAT <cast template> ] part for now.


That is fine, since it's separate feature


please check the attached regress test and tests expected result.


Except for the weird restriction on the default value, this all looks good to me (with the usual caveat that I am not an expert in C).


Are you planning to also implement the <castable predicate>?

-- 

Vik Fearing

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

От:
Vik Fearing <vik@postgresfriends.org>
Дата:

On 24/07/2025 15:44, jian he wrote:
> just want to confirm my understanding of ``[ FORMAT  ]``.
>
> SELECT CAST('2022-13-32' AS DATE FORMAT 'YYYY-MM-DD' DEFAULT NULL ON
> CONVERSION ERROR);
> will return NULL.
> because  ``SELECT to_date('2022-13-32', 'YYYY-MM-DD');``
> will error out, so the above query will fall back to the DEFAULT
> expression evaluation.


That is correct.  Any error produced during typecasting will fall back 
to the DEFAULT value.  If not supplied, the behavior is ERROR ON ERROR 
as it currently is.


Any error produced while converting the DEFAULT value to the requested 
type is raised as an error.

-- 

Vik Fearing




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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:



I didn't implement the [ FORMAT <cast template> ] part for now.
please check the attached regress test and tests expected result.

Question about this:

+/*
+ * Push steps to evaluate a SafeTypeCastExpr and its various subsidiary expressions.
+ * We already handle CoerceViaIO, CoerceToDomain, and ArrayCoerceExpr error
+ * softly.  However, FuncExpr (e.g., int84) cannot be made error-safe.
+ * In such cases, we wrap the source expression and target type information into
+ * a CoerceViaIO node instead.
+ */

I'm not sure we _can_ just fall back to the CoerceViaIO if there is a defined cast from TypeA -> TypeB. I seem to recall there was some reason we couldn't do that, possibly to do with how it handled rounding, but I have no clear memory of it.

Aside from that, I like what you've done with making SafeTypeCastExpr be its own node type and not saddling regular typecasts with the overhead.

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Thu, Jul 31, 2025 at 3:15 AM Corey Huinker  wrote:
>
>
> Question about this:
>
> +/*
> + * Push steps to evaluate a SafeTypeCastExpr and its various subsidiary expressions.
> + * We already handle CoerceViaIO, CoerceToDomain, and ArrayCoerceExpr error
> + * softly.  However, FuncExpr (e.g., int84) cannot be made error-safe.
> + * In such cases, we wrap the source expression and target type information into
> + * a CoerceViaIO node instead.
> + */
>
> I'm not sure we _can_ just fall back to the CoerceViaIO if there is a defined cast from TypeA -> TypeB. I seem to recall there was some reason we couldn't do that, possibly to do with how it handled rounding, but I have no clear memory of it.
>

indeed.
select ('11.1'::numeric::int);
return 11, but '11.1' string can not coerce to int 11. So in this
case, we can not use CoerceViaIO.

so we need to handle numeric source types with fractional points with
special care.
currently, this applies only to numeric, float4, and float8.
(hope this is all the corner case we need to catch...)

select castsource::regtype, casttarget::regtype, castfunc::regproc, castcontext
from   pg_cast pc
where  castsource::regtype = ANY('{numeric, float4, float8}'::regtype[])
and    castmethod = 'f';

only return 17 rows. one row is cast numreic to money, function numeric_cash.
numeric_cash seems more trickly to be error safe, because it will call
numeric_mul.
so I made these 16 function errors safe.
see v3-0001-make-some-numeric-cast-function-error-safe.patch

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
hi.

fix the regress tests failure in
https://api.cirrus-ci.com/v1/artifact/task/5894868779663360/testrun/build/testrun/regress/regress/regression.diffs

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
so we need to handle numeric source types with fractional points with
special care.
currently, this applies only to numeric, float4, and float8.
(hope this is all the corner case we need to catch...)

I'm fairly certain that the committers won't like us special-casing the internal cast functions, as we would have to maintain these special cases as new core types are added, and it still bypasses the defined cast function for user-defined types, which could have similar issues similar to the rounding issue.

I think the way forward here is either to:

1.  add a second function definition to CAST. The potential syntax forr a second function gets clumsy, but might look something like this:

CREATE CAST (source_type AS target_type)
    WITH FUNCTION function_name [ (argument_type [, ...]) ]
    [ AS ASSIGNMENT | AS IMPLICIT ]
   [
    WITH SAFE FUNCTION function_name [ (argument_type [, ...]) ]
    [ AS ASSIGNMENT | AS IMPLICIT ]
   ]

That doesn't seem right to me, it seems easier to:

2. Modify the CAST definition to indicate whether the existing cast function has the regular function signature or a -Safe one. In cases where a CAST has a defined function but the safe flag is turned off, we would have to fail the query with an error like "Defined CAST function from srctype to desttype is not error-safe".

This would involve changing the syntax of CREATE CAST by adding an option SAFE, or ERROR SAFE, or similar:

CREATE CAST (source_type AS target_type)
    WITH [SAFE] FUNCTION function_name [ (argument_type [, ...]) ]
    [ AS ASSIGNMENT | AS IMPLICIT ]

We would add a new value to pg_cast.castmethod, 's' for "safe".

We could refactor all the numeric types to use the modified functions, so no special-case code there anymore, and it gives extension writers an incentive to (eventually) make their own cast functions error-safe.

While method 2 seems a lot cleaner, there may be a performance regression in the now error-safe typecast functions. If so, that might tip the balance to having two functions defined.

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

От:
jian he <jian.universality@gmail.com>
Дата:
On Mon, Aug 4, 2025 at 1:09 PM Corey Huinker  wrote:
>>
>> so we need to handle numeric source types with fractional points with
>> special care.
>> currently, this applies only to numeric, float4, and float8.
>> (hope this is all the corner case we need to catch...)
>
>
> I'm fairly certain that the committers won't like us special-casing the internal cast functions, as we would have to maintain these special cases as new core types are added, and it still bypasses the defined cast function for user-defined types, which could have similar issues similar to the rounding issue.
>
It's not special-casing the internal cast functions.
It's how the cast being evaluated.
There are two ways: CoerceViaIO, FuncExpr.

generally if there is a pg_cast entry, postgres will use FuncExpr. but to safely
cast evaluation (DEFAULT ON CONVERSION ERROR) we can not use FuncExpr in some
cases. Because the FuncExpr associate function is not error safe.
So in v4, we try to use CoerceViaIO to evaluate the case, but it turns
out CoerceViaIO results are
not the same as FuncExpr.
one of the example is:
select ('11.1'::numeric::int);


In the end, it seems we need to make all these functions in the below
query error safe.
select castsource::regtype, casttarget::regtype, castfunc,
castcontext,castmethod, pp.prosrc, pp.proname from pg_cast pc join pg_proc pp on
pp.oid = pc.castfunc and pc.castfunc > 0
order by castsource::regtype;
It's a lot of work, but seems doable, after playing around with it.


I don't think we need to change the pg_cast catalog entry,
we just need to make these function (pg_cast.castmethod) errors safe.


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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:

In the end, it seems we need to make all these functions in the below
query error safe.
select castsource::regtype, casttarget::regtype, castfunc,
castcontext,castmethod, pp.prosrc, pp.proname from pg_cast pc join pg_proc pp on
pp.oid = pc.castfunc and pc.castfunc > 0
order by castsource::regtype;
It's a lot of work, but seems doable, after playing around with it.

It is do-able. But that's just the cast functions that are part of core postgres. 
 


I don't think we need to change the pg_cast catalog entry,
we just need to make these function (pg_cast.castmethod) errors safe.

That would break any user-defined cast functions that were not also error safe, which is to say all of them.

We need a way for user-defined cast functions to indicate whether or not they are error safe, and handle both situations accordingly (i.e. fail a CAST ON DEFAULT when the user-defined cast is not error-safe).
 

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

On Tue, Aug 5, 2025 at 12:10 PM Corey Huinker  wrote:
>>
>> In the end, it seems we need to make all these functions in the below
>> query error safe.
>> select castsource::regtype, casttarget::regtype, castfunc,
>> castcontext,castmethod, pp.prosrc, pp.proname from pg_cast pc join pg_proc pp on
>> pp.oid = pc.castfunc and pc.castfunc > 0
>> order by castsource::regtype;
>> It's a lot of work, but seems doable, after playing around with it.
>
> It is do-able. But that's just the cast functions that are part of core postgres.
>
hi.
it's doable for most of the data types.
but I found geometric type related cast function refactoring to error
safe is quite challenging,
so I skip that part refactoring.

>>
>> I don't think we need to change the pg_cast catalog entry,
>> we just need to make these function (pg_cast.castmethod) errors safe.
>
> That would break any user-defined cast functions that were not also error safe, which is to say all of them.
>
> We need a way for user-defined cast functions to indicate whether or not they are error safe, and handle both situations accordingly (i.e. fail a CAST ON DEFAULT when the user-defined cast is not error-safe).
>

I understand what you mean now.
CREATE CAST can use built-in functions too, we have no way to check
whether these CREATE CAST
associated functions are error safe or not.
for example:
CREATE CAST (jsonpath  AS bytea) WITH FUNCTION jsonpath_send (jsonpath
) AS ASSIGNMENT;
select '$'::jsonpath::bytea;

To avoid this situation, we have to add a new column to pg_cast to
indicate whether a cast function is error-safe.
It's unlikely a pg_cast entry has two functions, one is error safe, one is not,
adding pg_cast.casterrorsafefunc would not be that appropriate.

so I choose pg_cast.casterrorsafe would be fine.
pg_cast.casterrorsafe true means castfunc function is error safe, we
can use it as safe cast evaluation
(CAST... DEFAULT defexpr ON CONVERSION ERROR)

please check the attached V6 script:

v6-0001 to v6-0016 is about making existing pg_cast.castfunc function
error safe.
(commit message have associated query to explain the refactoring, as mentioned
above, geometric and money associated type not refactored yet)

v6-0017-make-ArrayCoerceExpr-error-safe.patch
v6-0018-CAST-expr-AS-newtype-DEFAULT-ON-ERROR.patch
is about (CAST... DEFAULT defexpr ON CONVERSION ERROR).

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

hi.

First of all, rebase v6.

select distinct castsource::regtype, casttarget::regtype, pp.prosrc
from pg_cast pc join pg_proc pp on pp.oid = pc.castfunc
join pg_type pt on pt.oid = castsource
join pg_type pt1 on pt1.oid = casttarget
and pc.castfunc > 0 and pt.typarray <> 0 and pt.typnamespace =
'pg_catalog'::regnamespace
and pt1.typnamespace = 'pg_catalog'::regnamespace
order by castsource::regtype, casttarget::regtype;

The above query will list all cast functions in PG_CATALOG schema that
need to be
refactored to be error-safe.  looking around, I found that the below source data
type, the cast function is already error safe:

boolean
name
"char"  ("char" to integer was handled in integer cast part)
regprocedure
regoper
regoperator
regclass
regtype
regconfig
regdictionary
regproc
oid
regnamespace
regrole
regcollation
regdatabase
int4range
numrange
tsrange
tstzrange
daterange
int8range
xid8
time without time zone
time with time zone

After applying the attached v7 patch patchset,
the below are cast functions that I didn't refactor to error safe yet.

select pc.castsource::regtype,
       pc.casttarget::regtype, castfunc::regproc, pp.prosrc
from pg_cast pc join pg_proc pp on pp.oid = pc.castfunc
join pg_type pt on pt.oid = castsource
join pg_type pt1 on pt1.oid = casttarget
and pc.castfunc > 0 and pt.typnamespace = 'pg_catalog'::regnamespace
and pt1.typnamespace = 'pg_catalog'::regnamespace and not pc.casterrorsafe;

 castsource | casttarget |       castfunc       |    prosrc
------------+------------+----------------------+--------------
 bigint     | money      | pg_catalog.money     | int8_cash
 integer    | money      | pg_catalog.money     | int4_cash
 numeric    | money      | pg_catalog.money     | numeric_cash
 money      | numeric    | pg_catalog."numeric" | cash_numeric
(4 rows)

The reason I don't refactor these cast functions related to money data
type  is because
1. I am not sure if the PGLC_localeconv() function is error safe or not.
2. refactoring such ``DirectFunctionCall1(numeric_int8, amount));``
requires more effort.

please check the attached v7 patch set:
01-error-safe-for-casting-bytea-to-other-types
02-error-safe-for-casting-bit-varbit-to-other-types
03-error-safe-for-casting-character-to-other-types
04-error-safe-for-casting-text-to-other-types
05-error-safe-for-casting-character-varying-to-other-types
06-error-safe-for-casting-inet-to-other-types
07-error-safe-for-casting-macaddr8-to-other-types
08-error-safe-for-casting-integer-to-other-types
09-error-safe-for-casting-bigint-to-other-types
10-error-safe-for-casting-numeric-to-other-types
11-error-safe-for-casting-float4-to-other-types
12-error-safe-for-casting-float8-to-other-types
13-error-safe-for-casting-date-to-other-types
14-error-safe-for-casting-interval-to-other-types
15-error-safe-for-casting-timestamptz-to-other-types
16-error-safe-for-casting-timestamp-to-other-types
17-error-safe-for-casting-jsonb-to-other-types
18-error-safe-for-casting-geometry-data-types
19-invent_some_error_safe_function.patch
20-CAST-expr-AS-newtype-DEFAULT-ON-ERROR.patch

Each patch includes a commit message explaining which function is being
refactored to be error-safe.

I also made some changes for
"20-CAST-expr-AS-newtype-DEFAULT-ON-ERROR.patch"

If the source expression is Const, it can be unknown type or other type.
* for UNKNOWN type, example:
SELECT CAST ('\x112233445566778899'::bytea AS int8 DEFAULT NULL ON
CONVERSION ERROR);
We use CoerceUnknownConstSafe to verify earlier that such Const can be
coerced to target data type or not.

* for other data type, example:
SELECT CAST ('\x112233445566778899'::bytea AS int8 DEFAULT NULL ON
CONVERSION ERROR);
we use evaluate_expr_safe to evaluate it error safe way earlier in
transformTypeSafeCast.
similar to transformPartitionBoundValue call evaluate_expr

The geometry cast functions ``(poly_circle(PG_FUNCTION_ARGS)`` have
problems making it error safe,
working on it.

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

On Fri, Oct 10, 2025 at 8:23 PM jian he  wrote:
> After applying the attached v7 patch patchset,
> the below are cast functions that I didn't refactor to error safe yet.
>
> select pc.castsource::regtype,
>        pc.casttarget::regtype, castfunc::regproc, pp.prosrc
> from pg_cast pc join pg_proc pp on pp.oid = pc.castfunc
> join pg_type pt on pt.oid = castsource
> join pg_type pt1 on pt1.oid = casttarget
> and pc.castfunc > 0 and pt.typnamespace = 'pg_catalog'::regnamespace
> and pt1.typnamespace = 'pg_catalog'::regnamespace and not pc.casterrorsafe;
>
>  castsource | casttarget |       castfunc       |    prosrc
> ------------+------------+----------------------+--------------
>  bigint     | money      | pg_catalog.money     | int8_cash
>  integer    | money      | pg_catalog.money     | int4_cash
>  numeric    | money      | pg_catalog.money     | numeric_cash
>  money      | numeric    | pg_catalog."numeric" | cash_numeric
> (4 rows)
>
> The reason I don't refactor these cast functions related to money data
> type  is because
> 1. I am not sure if the PGLC_localeconv() function is error safe or not.
> 2. refactoring such ``DirectFunctionCall1(numeric_int8, amount));``
> requires more effort.
>
> please check the attached v7 patch set:
> 01-error-safe-for-casting-bytea-to-other-types
> 02-error-safe-for-casting-bit-varbit-to-other-types
> 03-error-safe-for-casting-character-to-other-types
> 04-error-safe-for-casting-text-to-other-types
> 05-error-safe-for-casting-character-varying-to-other-types
> 06-error-safe-for-casting-inet-to-other-types
> 07-error-safe-for-casting-macaddr8-to-other-types
> 08-error-safe-for-casting-integer-to-other-types
> 09-error-safe-for-casting-bigint-to-other-types
> 10-error-safe-for-casting-numeric-to-other-types
> 11-error-safe-for-casting-float4-to-other-types
> 12-error-safe-for-casting-float8-to-other-types
> 13-error-safe-for-casting-date-to-other-types
> 14-error-safe-for-casting-interval-to-other-types
> 15-error-safe-for-casting-timestamptz-to-other-types
> 16-error-safe-for-casting-timestamp-to-other-types
> 17-error-safe-for-casting-jsonb-to-other-types
> 18-error-safe-for-casting-geometry-data-types
> 19-invent_some_error_safe_function.patch
> 20-CAST-expr-AS-newtype-DEFAULT-ON-ERROR.patch
>
> Each patch includes a commit message explaining which function is being
> refactored to be error-safe.
>

Summary of what this patch set is doing:
To implement the syntax:
CAST(source_expr AS target_type DEFAULT def_expr ON CONVERSION ERROR)

we need to ensure that the transformed cast expression is error-safe.
A transformed cast expression can be either a CoerceViaIO or a FuncExpr.
Since CoerceViaIO is already error-safe but FuncExpr cannot be
rewritten as CoerceViaIO
one of the example: SELECT ('11.1'::numeric::int)

So we need to refactor how pg_cast.castfunc works to make it error-safe.
We also need to query pg_cast to determine whether a given pg_cast.castfunc is
error-safe.  For this, a new field casterrorsafe is added to pg_cast.

Patches 01–18: Refactor all pg_cast.castfunc entries (except those with the
money data type) to be error-safe.
Patches 19–20: Implement support for CAST(... AS ... DEFAULT def_expr ON
CONVERSION ERROR)

Please check the attached v8.

It includes minor changes compared to v7:
mainly a small mistake fix in src/backend/jit/llvm/llvmjit_expr.c.
Additionally, one occurrence of NO_XML_SUPPORT(); was replaced with
errsave(escontext, …).

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

On Tue, Oct 14, 2025 at 10:00 AM jian he  wrote:
> Please check the attached v8.
>
hi.

please see the attached V9 patchset.
v9-0001 to v9-0018: refactor pg_cast.castfunc entries, make it error safe.
v9-0019:  CAST(... AS ... DEFAULT def_expr ON CONVERSION ERROR)

select pc.castsource::regtype,pc.casttarget::regtype,
castfunc::regproc, pp.prosrc
from pg_cast pc join pg_proc pp on pp.oid = pc.castfunc
join pg_type pt on pt.oid = castsource
join pg_type pt1 on pt1.oid = casttarget
and pc.castfunc > 0 and pt.typnamespace = 'pg_catalog'::regnamespace
and pt1.typnamespace = 'pg_catalog'::regnamespace and not pc.casterrorsafe;

 castsource | casttarget |       castfunc       |    prosrc
------------+------------+----------------------+--------------
 circle     | polygon    | pg_catalog.polygon   |
 bigint     | money      | pg_catalog.money     | int8_cash
 integer    | money      | pg_catalog.money     | int4_cash
 numeric    | money      | pg_catalog.money     | numeric_cash
 money      | numeric    | pg_catalog."numeric" | cash_numeric
(5 rows)

The above result shows type casts using functions which cannot be error safe.
Money type related casts still can not be error safe.

Cast from circle to polygon cannot be error safe because the associated cast
function (pg_cast.castfunc) is written in SQL
(see src/backend/catalog/system_functions.sql LINE 112).
It appears impossible to make SQL language functions error safe, because
fmgr_sql ignores fcinfo->context.


eval_const_expressions cannot be error safe, so we need to handle
source_expr as an UNKNOWN constant in an error safe beforehand.
For example, we need handle ('1' AS DATE) in an error safe way
for
SELECT CAST('1' AS date  DEFAULT '2011-01-01' ON ERROR);

Since we must handle the source_expr when it is an UNKNOWN constant in an
error safe way, we can apply the same handling when source_expr is a
Const whose type is not UNKNOWN.
For example:
SELECT CAST('[(1,2),(3,4)]'::path AS polygon DEFAULT NULL ON CONVERSION ERROR);

If source_expr is a Const and the cast expression is a FuncExpr, we can be
certain that all arguments (FuncExpr->args) are also Const; see the function
chain coerce_to_target_type → coerce_type → build_coercion_expression.

We don’t need to worry about deparsing the expression because struct
SafeTypeCastExpr includes source_expr, cast_expr, and default_expr.  Even if
cast_expr is NULL, we can still use source_expr to reconstruct the original CAST
expression.

so I introduced:
evaluate_expr_safe: error safe version of evaluate_expr
CoerceUnknownConstSafe: tests whether an UNKNOWN Const can be coerced to the
target type.

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
The above result shows type casts using functions which cannot be error safe.
Money type related casts still can not be error safe.

Cast from circle to polygon cannot be error safe because the associated cast
function (pg_cast.castfunc) is written in SQL
(see src/backend/catalog/system_functions.sql LINE 112).
It appears impossible to make SQL language functions error safe, because
fmgr_sql ignores fcinfo->context.

It is inevitable that some typecast functions are not type safe, either because they cannot easily be made so, or because they come from an extension that has not yet made them so.


 
eval_const_expressions cannot be error safe, so we need to handle
source_expr as an UNKNOWN constant in an error safe beforehand.
For example, we need handle ('1' AS DATE) in an error safe way
for
SELECT CAST('1' AS date  DEFAULT '2011-01-01' ON ERROR);

Since we must handle the source_expr when it is an UNKNOWN constant in an
error safe way, we can apply the same handling when source_expr is a
Const whose type is not UNKNOWN.
For example:
SELECT CAST('[(1,2),(3,4)]'::path AS polygon DEFAULT NULL ON CONVERSION ERROR);

In the case you've presented here, the cast to type "path" doesn't need to be safe, but the cast path->polygon does. Or rather, if it isn't safe we should raise an error.
 

so I introduced:
evaluate_expr_safe: error safe version of evaluate_expr
CoerceUnknownConstSafe: tests whether an UNKNOWN Const can be coerced to the
target type.

Good. That's the missing bit I knew we needed to add. Sorry I wasn't able to find time.

Issue 1:
+++ b/doc/src/sgml/syntax.sgml
@@ -2106,6 +2106,10 @@ CAST ( <replaceable>expression</replaceable> AS <replaceable>type</replaceable>
     The <literal>CAST</literal> syntax conforms to SQL; the syntax with
     <literal>::</literal> is historical <productname>PostgreSQL</productname>
     usage.
+    It can also be written as:
+<synopsis>
+CAST ( <replaceable>expression</replaceable> AS <replaceable>type</replaceable> ERROR ON CONVERSION ERROR )
+</synopsis>

The wording implies that this syntax is a new shortcut to a previously established ON CONVERSION ERROR syntax, when it was the only way to do it until this patch.


Issue 2:
s/is historical/is the original/
s/It can be also be written as:/The equivalent ON CONVERSION ERROR behavior is:/

+ /*
+ * Use evaluate_expr_safe to pre-evaluate simple constant cast
+ * expressions early, in a way that tolter errors.

typo on tolter? This happens in 2 places.


Issue 3:
+ errhint("Currently CAST ... DEFAULT ON CONVERSION ERROR does not support this cast"),

Suggest: errhint("Explicit cast is defined but definition is not declared as safe")

This hint helps distinguish the fact that it's the cast function getting in the way of this cast-on-default working. If the cast had been defined as IO then we wouldn't have had a problem.

It is true that we presently have no means of declaring a cast safe aside from making it so in pg_proc.dat, but that's coming shortly.


 
Issue 4:

catversion.h is not updated. Which isn't a bad thing because that brings me to...


Issue 5:

I think 0019 is a bit big for a committer to digest all in one sitting. Currently it:

- introduces the type-safe cast node
- introduces the cast on default syntax
- redefines 
- adds in test cases for all safe functions defined in patches 1-18.

As tedious as it might be, I think we want to move this patch to the front, move all pg_cast.dat changes to their respective patches that introduce that datatype's safe typecast function, as well as the test cases that are made possible by that new safe typecast. That will make it easier to ensure that each new cast has test coverage.

Yes, that's going to be a lot of catversion bumps, requiring somebody to fudge the dates as we presently only allow for 10 catversion bumps in a day, but the committer will either combine a few of the patches or spread the work out over a few days.

Overall:

I like where this patchset is going. The introduction of error contexts has eliminated a lot of the issues I was having carrying the error state forward into the next eval step.

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

On Thu, Nov 6, 2025 at 6:00 AM Corey Huinker  wrote:
>
> Issue 5:
>
> I think 0019 is a bit big for a committer to digest all in one sitting. Currently it:
>
> - introduces the type-safe cast node
> - introduces the cast on default syntax
> - redefines
> - adds in test cases for all safe functions defined in patches 1-18.
>
> As tedious as it might be, I think we want to move this patch to the front, move all pg_cast.dat changes to their respective patches that introduce that datatype's safe typecast function, as well as the test cases that are made possible by that new safe typecast. That will make it easier to ensure that each new cast has test coverage.
>
> Yes, that's going to be a lot of catversion bumps, requiring somebody to fudge the dates as we presently only allow for 10 catversion bumps in a day, but the committer will either combine a few of the patches or spread the work out over a few days.
>

Currently, patches v9-0001 through v9-0018 focus solely on refactoring
pg_cast.castfunc.  This refactoring is already valuable on its own because it
establishes the infrastructure needed for error safe type casts.
As mentioned before, to make
CAST(source_expr AS target_type DEFAULT expr ON CONVERSION ERROR);
work,
we cannot just simply replace casting FuncExpr nodes with CoerceViaIO, since
type modifiers behave differently in these two Nodes.
(e.g., casting numeric 1.11 to integer is not equivalent to casting the literal
"1.11" to integer).

Also, are we settled on this new pg_cast column name (pg_cast.casterrorsafe)?
Overall, I think it's better not to touch pg_cast.dat in each of these
refactoring patches.

Without first refactoring pg_cast.castfunc (01 to 18), making CAST ...
DEFAULT as the first patch (0001)
won't work, since pg_cast.castfunc itself is not error safe yet, and we
have no way to test the CAST DEFAULT syntax.

So we have to *first* refactor pg_cast.castfunc, make it error safe
then implement CAST DEFAULT.
--------------------------------------------------
The CAST DEFAULT patch is large, I tried to split some newly created function
into a seperate patch.
see v10-0019-invent-some-error-safe-functions.patch.

SELECT CAST('five' AS INTEGER DEFAULT 6 ON CONVERSION ERROR);
is not hard to make it error safe. ('five' is a simple Cons node)

However, I found out, to make
SELECT CAST('five'::INTEGER AS INTEGER DEFAULT 6 ON CONVERSION ERROR);
error safe is hard.

('five'::INTEGER) is a TypeCast node, normally it will error out in
transformTypeCast->
coerce_to_target_type->coerce_type ```(if (inputTypeId == UNKNOWNOID
&& IsA(node, Const)))```
If we do not error out, then we need a Node to represent the failed cast, mainly
for deparse purposes.

that means for CAST(source_expr .... DEFAULT defexpr ON CONVERSION ERROR);
The only corner case we handle is when source_expr is a simple Const node.
In all other cases, source_expr is processed through transformExpr,
which does all
the normal parse analysis for a node.

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

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
As mentioned before, to make
CAST(source_expr AS target_type DEFAULT expr ON CONVERSION ERROR);
work,
we cannot just simply replace casting FuncExpr nodes with CoerceViaIO, since
type modifiers behave differently in these two Nodes.
(e.g., casting numeric 1.11 to integer is not equivalent to casting the literal
"1.11" to integer).

I wasn't suggesting that. I was suggesting that we move tests that use a given type's custom cast function into the same patch that makes that cast safe. This would mean that the initial syntax+nodes+executor patch starts out only with test cases known to not have custom functions.

 

Also, are we settled on this new pg_cast column name (pg_cast.casterrorsafe)?
Overall, I think it's better not to touch pg_cast.dat in each of these
refactoring patches.

I'm fine with it. I can see having 'f' and 's' both mean cast functions, but 's' means safe, but the extra boolean works too and we'll be fine with either method.
 

Without first refactoring pg_cast.castfunc (01 to 18), making CAST ...
DEFAULT as the first patch (0001)
won't work, since pg_cast.castfunc itself is not error safe yet, and we
have no way to test the CAST DEFAULT syntax.

So we have to *first* refactor pg_cast.castfunc, make it error safe
then implement CAST DEFAULT.

Makes sense.
 

However, I found out, to make
SELECT CAST('five'::INTEGER AS INTEGER DEFAULT 6 ON CONVERSION ERROR);
error safe is hard.

That's no problem at all. The CAST () function can't do anything about an input that's already an error before the CAST node executes. Nor should it. It should only concern itself with errors related to the actual casting of a value to the specified type.
 

('five'::INTEGER) is a TypeCast node, normally it will error out in
transformTypeCast->
coerce_to_target_type->coerce_type ```(if (inputTypeId == UNKNOWNOID
&& IsA(node, Const)))```
If we do not error out, then we need a Node to represent the failed cast, mainly
for deparse purposes.

We _must_ error out in that case, before the CAST executes.
 

that means for CAST(source_expr .... DEFAULT defexpr ON CONVERSION ERROR);
The only corner case we handle is when source_expr is a simple Const node.
In all other cases, source_expr is processed through transformExpr,
which does all
the normal parse analysis for a node.

I'll get to reviewing this patchset soon.

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

От:
Amul Sul <sulamul@gmail.com>
Дата:
On Tue, Nov 11, 2025 at 8:37 AM jian he  wrote:
>
> On Thu, Nov 6, 2025 at 6:00 AM Corey Huinker  wrote:
> > [...]
>
> Currently, patches v9-0001 through v9-0018 focus solely on refactoring
> pg_cast.castfunc.

I had a quick look but haven't finished the full review due to lack of
time today. Here are a few initial comments:

v10-0003:

-   NO_XML_SUPPORT();
+   errsave(escontext,
+           errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+           errmsg("unsupported XML feature"),
+           errdetail("This functionality requires the server to be
built with libxml support."));
    return NULL;

Can use ereturn() instead of errsave() followed by return NULL.
--

10-0004:

+/* error safe version of textToQualifiedNameList */
+List *
+textToQualifiedNameListSafe(text *textval, Node *escontext)

If I am not mistaken, it looks like an exact copy of
textToQualifiedNameList(). I think you can simply keep only
textToQualifiedNameListSafe() and call that from
textToQualifiedNameList() with a NULL value for escontext. This way,
all errsave() or ereturn() calls will behave like ereport().

The same logic applies to RangeVarGetRelidExtendedSafe() and
makeRangeVarFromNameListSafe. These can be called from
RangeVarGetRelidExtended() and makeRangeVarFromNameList(),
respectively.
--

+   {
+       errsave(escontext,
+               errcode(ERRCODE_INVALID_NAME),
+               errmsg("invalid name syntax"));
+       return NIL;
+   }

I prefer ereturn() instead of errsave + return.
--

v10-0017

    for (i = 0; i < lengthof(messages); i++)
        if (messages[i].type == type)
-           ereport(ERROR,
+       {
+           errsave(escontext,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg(messages[i].msg, sqltype)));
+           return;
+       }

Here, I think, you can use ereturn() to return void.
--

v10-0018

+   if (unlikely(result == 0.0) && val1 != 0.0 && !isinf(val2))
+   {
+       errsave(escontext,
+               errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+               errmsg("value out of range: underflow"));
+
+       result = 0.0;
+       return result;
+   }

Here, you can use ereturn() to return 0.0. Similar changes are needed
at other places in the same patch.

Regards,
Amul


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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
On Mon, Nov 10, 2025 at 11:36 PM Corey Huinker <corey.huinker@gmail.com> wrote:
As mentioned before, to make
CAST(source_expr AS target_type DEFAULT expr ON CONVERSION ERROR);
work,
we cannot just simply replace casting FuncExpr nodes with CoerceViaIO, since
type modifiers behave differently in these two Nodes.
(e.g., casting numeric 1.11 to integer is not equivalent to casting the literal
"1.11" to integer).

I wasn't suggesting that. I was suggesting that we move tests that use a given type's custom cast function into the same patch that makes that cast safe. This would mean that the initial syntax+nodes+executor patch starts out only with test cases known to not have custom functions.

With a second look at the patches, I think the organization is fine as-is.


Also, are we settled on this new pg_cast column name (pg_cast.casterrorsafe)?
Overall, I think it's better not to touch pg_cast.dat in each of these
refactoring patches.

I'm fine with it. I can see having 'f' and 's' both mean cast functions, but 's' means safe, but the extra boolean works too and we'll be fine with either method.

I can work on this part if you don't have time.


I'll get to reviewing this patchset soon.

Not as soon as I would have liked, but the patchset still applies without error, and survives all of my attempts to break it, including user defined functions that generate errors deterministically as well as non-deterministically, hoping to see it incorrectly use the default rather than reporting the error.

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

От:
jian he <jian.universality@gmail.com>
Дата:
On Mon, Nov 17, 2025 at 9:43 PM Amul Sul  wrote:
>
> 10-0004:
>
> +/* error safe version of textToQualifiedNameList */
> +List *
> +textToQualifiedNameListSafe(text *textval, Node *escontext)
>
> If I am not mistaken, it looks like an exact copy of
> textToQualifiedNameList(). I think you can simply keep only
> textToQualifiedNameListSafe() and call that from
> textToQualifiedNameList() with a NULL value for escontext. This way,
> all errsave() or ereturn() calls will behave like ereport().
>
> The same logic applies to RangeVarGetRelidExtendedSafe() and
> makeRangeVarFromNameListSafe. These can be called from
> RangeVarGetRelidExtended() and makeRangeVarFromNameList(),
> respectively.
> --
>

hi.

List *
textToQualifiedNameList(text *textval)
{
    List       *namelist;
    rawname = text_to_cstring(textval);
    if (!SplitIdentifierString(rawname, '.', &namelist))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_NAME),
                 errmsg("invalid name syntax")));
}

I don’t see any way to pass the escontext (ErrorSaveContext) without changing
the textToQualifiedNameList function signature.

There are around 30 occurrences of textToQualifiedNameList.
changing the function textToQualifiedNameList signature is invasive,
so I tend to avoid it.
I think it's easier to just duplicate textToQualifiedNameList
than changing the function textToQualifiedNameList signature.

Am I missing something?

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


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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
> The same logic applies to RangeVarGetRelidExtendedSafe() and
> makeRangeVarFromNameListSafe. These can be called from
> RangeVarGetRelidExtended() and makeRangeVarFromNameList(),
> respectively.
> --
>

I don’t see any way to pass the escontext (ErrorSaveContext) without changing
the textToQualifiedNameList function signature.
...
Am I missing something?

I think we need to keep these separate. The execution paths that don't care about capturing errors shouldn't be slowed down by minority of paths that do. That may change in the future, but if it does, we'll be getting rid of a lot of internal functions with this type of difference.

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

От:
Amul Sul <sulamul@gmail.com>
Дата:
On Fri, Nov 21, 2025 at 2:11 PM jian he  wrote:
>
> On Mon, Nov 17, 2025 at 9:43 PM Amul Sul  wrote:
> >
> > 10-0004:
> >
> > +/* error safe version of textToQualifiedNameList */
> > +List *
> > +textToQualifiedNameListSafe(text *textval, Node *escontext)
> >
> > If I am not mistaken, it looks like an exact copy of
> > textToQualifiedNameList(). I think you can simply keep only
> > textToQualifiedNameListSafe() and call that from
> > textToQualifiedNameList() with a NULL value for escontext. This way,
> > all errsave() or ereturn() calls will behave like ereport().
> >
> > The same logic applies to RangeVarGetRelidExtendedSafe() and
> > makeRangeVarFromNameListSafe. These can be called from
> > RangeVarGetRelidExtended() and makeRangeVarFromNameList(),
> > respectively.
> > --
> >
>
> hi.
>
> List *
> textToQualifiedNameList(text *textval)
> {
>     List       *namelist;
>     rawname = text_to_cstring(textval);
>     if (!SplitIdentifierString(rawname, '.', &namelist))
>         ereport(ERROR,
>                 (errcode(ERRCODE_INVALID_NAME),
>                  errmsg("invalid name syntax")));
> }
>
> I don’t see any way to pass the escontext (ErrorSaveContext) without changing
> the textToQualifiedNameList function signature.
>
> There are around 30 occurrences of textToQualifiedNameList.
> changing the function textToQualifiedNameList signature is invasive,
> so I tend to avoid it.
> I think it's easier to just duplicate textToQualifiedNameList
> than changing the function textToQualifiedNameList signature.
>
> Am I missing something?
>

The change I was suggesting will be as below:

--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -2684,6 +2684,13 @@ name_text(PG_FUNCTION_ARGS)
  */
 List *
 textToQualifiedNameList(text *textval)
+{
+   textToQualifiedNameListSafe(textval, NULL);
+}
+
+/* error safe version of textToQualifiedNameList */
+List *
+textToQualifiedNameListSafe(text *textval, Node *escontext)
 {
    char       *rawname;
    List       *result = NIL;


We must try to avoid duplication whenever possible, as any bug fixes
or enhancements would need to be copied to multiple places, which is
often overlooked.

Regards,
Amul


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

On Mon, Nov 24, 2025 at 11:38 AM Amul Sul  wrote:
>
> The change I was suggesting will be as below:
>
> --- a/src/backend/utils/adt/varlena.c
> +++ b/src/backend/utils/adt/varlena.c
> @@ -2684,6 +2684,13 @@ name_text(PG_FUNCTION_ARGS)
>   */
>  List *
>  textToQualifiedNameList(text *textval)
> +{
> +   textToQualifiedNameListSafe(textval, NULL);
> +}
> +
> +/* error safe version of textToQualifiedNameList */
> +List *
> +textToQualifiedNameListSafe(text *textval, Node *escontext)
>  {
>     char       *rawname;
>     List       *result = NIL;
>
>
> We must try to avoid duplication whenever possible, as any bug fixes
> or enhancements would need to be copied to multiple places, which is
> often overlooked.
>
hi.
great idea!

I incorporated all of your ideas into v11.
I replaced all errsave to ereturn.
I aslo simplified T_SafeTypeCastExpr expression initialization, evaluation logic
within execExpr.c, execExprInterp.c.

but one thing I didn't touch: float8_div.

+static inline float8
+float8_div_safe(const float8 val1, const float8 val2, struct Node *escontext)

but we can change float8_div to:

static inline float8
float8_div(const float8 val1, const float8 val2)
{
   return float8_div_safe(val1, val2, NULL);
}
I am worried that entering another function would cause a minor performance
degradation.  And since these simple functions are so simple, keeping them
separated should not be a big problem.  also I placed float8_div,
float8_div_safe together.


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

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

On Fri, Nov 21, 2025 at 3:32 PM Corey Huinker  wrote:
>
>>>
>>> Also, are we settled on this new pg_cast column name (pg_cast.casterrorsafe)?
>>> Overall, I think it's better not to touch pg_cast.dat in each of these
>>> refactoring patches.
>>
>>
>> I'm fine with it. I can see having 'f' and 's' both mean cast functions, but 's' means safe, but the extra boolean works too and we'll be fine with either method.
>
>
> I can work on this part if you don't have time.

Do you mean change pg_cast.casterrorsafe from boolean to char?
Currently pg_cast.casterrorsafe works just fine.
if the cast function is not applicable, the castfunc would be InvalidOid.
also the cast function is either error safe or not, I don't see a
usage case for the third value.

attached v12-0004 fixes the xmlparse error, see
https://cirrus-ci.com/task/6181359384788992?logs=build#L1217.

all other patches remain the same as v11.

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

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
>> I'm fine with it. I can see having 'f' and 's' both mean cast functions, but 's' means safe, but the extra boolean works too and we'll be fine with either method.
>
>
> I can work on this part if you don't have time.

Do you mean change pg_cast.casterrorsafe from boolean to char?

No, I meant implementing the syntax for being able to declare a custom CAST function as safe (or not). Basically adding the [SAFE] to
CREATE CAST (source_type AS target_type)    WITH [SAFE] FUNCTION function_name [ (argument_type [, ...]) ]
I'm not tied to this syntax choice, but this one seemed the most obvious and least invasive.

But this brings up an interesting point: if a cast is declared as WITHOUT FUNCTION aka COERCION_METHOD_BINARY, then the cast can never fail, and we should probably check for that because a cast that cannot fail can ignore the DEFAULT clause altogether and fall back to being an ordinary CAST().
 
Currently pg_cast.casterrorsafe works just fine.
if the cast function is not applicable, the castfunc would be InvalidOid.
also the cast function is either error safe or not, I don't see a
usage case for the third value.

Agreed, it's fine. A committer may want a char with 's'/'u' values to keep all the options char types, but even if they do that's a very minor change.

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

От:
Amul Sul <sulamul@gmail.com>
Дата:
On Tue, Nov 25, 2025 at 8:30 AM jian he  wrote:
>
> On Mon, Nov 24, 2025 at 11:38 AM Amul Sul  wrote:
> >
> > [...]
> +static inline float8
> +float8_div_safe(const float8 val1, const float8 val2, struct Node *escontext)
>
> but we can change float8_div to:
>
> static inline float8
> float8_div(const float8 val1, const float8 val2)
> {
>    return float8_div_safe(val1, val2, NULL);
> }
> I am worried that entering another function would cause a minor performance
> degradation.  And since these simple functions are so simple, keeping them
> separated should not be a big problem.  also I placed float8_div,
> float8_div_safe together.

Since you declared float8_div_safe() as static inline, I believe it
wouldn't have any performance degradation since most compilers
optimize it. Also, I suggest you pass the ErrorSafeContext to
float_overflow_error(), float_underflow_error(), and
float_zero_divide_error() so that you can avoid duplicating error
messages.

Regards,
Amul


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

On Mon, Dec 1, 2025 at 8:09 PM Amul Sul  wrote:
>
> Since you declared float8_div_safe() as static inline, I believe it
> wouldn't have any performance degradation since most compilers
> optimize it. Also, I suggest you pass the ErrorSafeContext to
> float_overflow_error(), float_underflow_error(), and
> float_zero_divide_error() so that you can avoid duplicating error
> messages.
>
hi.

First I want to use ereturn, then I found out
float_overflow_error, float_underflow_error, float_zero_divide_error
used both in float4, float8.
ereturn would not be appropriate for both types.
so I choose errsave.
for these 3 functions, now it looks like:

pg_noinline void
float_overflow_error(struct Node *escontext)
{
    errsave(escontext,
            (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
             errmsg("value out of range: overflow")));
}

pg_noinline void
float_underflow_error(struct Node *escontext)
{
    errsave(escontext,
            (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
             errmsg("value out of range: underflow")));
}

pg_noinline void
float_zero_divide_error(struct Node *escontext)
{
    errsave(escontext,
            (errcode(ERRCODE_DIVISION_BY_ZERO),
             errmsg("division by zero")));
}


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

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

От:
Amul Sul <sulamul@gmail.com>
Дата:
On Tue, Dec 2, 2025 at 1:23 PM jian he  wrote:
>
> On Mon, Dec 1, 2025 at 8:09 PM Amul Sul  wrote:
> >
> > Since you declared float8_div_safe() as static inline, I believe it
> > wouldn't have any performance degradation since most compilers
> > optimize it. Also, I suggest you pass the ErrorSafeContext to
> > float_overflow_error(), float_underflow_error(), and
> > float_zero_divide_error() so that you can avoid duplicating error
> > messages.
> >
> hi.
>
> First I want to use ereturn, then I found out
> float_overflow_error, float_underflow_error, float_zero_divide_error
> used both in float4, float8.
> ereturn would not be appropriate for both types.
> so I choose errsave.
> for these 3 functions, now it looks like:

Make sense, thanks for updating the patch.

Regarding v13-0019 and v13-0020 patches, I have a bunch of comments
for the code, but I'd like to understand the implemented design first.
I have some basic questions regarding the commit message and code
comment, as follows:

"
We cannot simply prohibit user-defined functions in pg_cast for safe cast
evaluation because CREATE CAST can also utilize built-in functions. So, to
completely disallow custom casts created via CREATE CAST used in safe cast
evaluation, a new field in pg_cast would unfortunately be necessary.
"

I might not have understood the implementation completely -- can't we
use fmgr_last_builtin_oid to detect built-in functions?
--

+           /*
+            * We have to to use CoerceUnknownConstSafe rather than
+            * coerce_to_target_type. because coerce_to_target_type is not error
+            * safe.
+            */

How difficult would it be to modify coerce_to_target_type() to make it
error safe?

Could we utilize the existing type casting infrastructure for this, perhaps by
simply considering the evolution and use of the additional default
expression? If we could, the resulting implementation would be very
clean, IMHO.

Kindly excuse and point me if that is already discussed.
--

Here are few comments for v13-0018:

 static inline void point_add_point(Point *result, Point *pt1, Point *pt2);
+static inline bool point_add_point_safe(Point *result, Point *pt1, Point *pt2,
+                                       Node *escontext);

+static inline float8 point_dt_safe(Point *pt1, Point *pt2, Node *escontext);
 static inline float8 point_sl(Point *pt1, Point *pt2);

I think we should avoid introducing the "_safe" version of static
routines in the .c file. Instead, we can add the Node *escontext
argument to the existing routines, similar to how single_decode() was
previously modified to accept it.
--

-static void poly_to_circle(CIRCLE *result, POLYGON *poly);
+static bool poly_to_circle_safe(CIRCLE *result, POLYGON *poly, Node
*escontext);

Following the previous suggestion, please keep the existing function
as it is and just add one more argument to it.
--


 }

+
 static inline float4
 float4_mi(const float4 val1, const float4 val2)
 {

A spurious change.
--

Regards,
Amul


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

On Thu, Dec 4, 2025 at 8:47 PM Amul Sul  wrote:
>
> Regarding v13-0019 and v13-0020 patches, I have a bunch of comments
> for the code, but I'd like to understand the implemented design first.
> I have some basic questions regarding the commit message and code
> comment, as follows:
>
> "
> We cannot simply prohibit user-defined functions in pg_cast for safe cast
> evaluation because CREATE CAST can also utilize built-in functions. So, to
> completely disallow custom casts created via CREATE CAST used in safe cast
> evaluation, a new field in pg_cast would unfortunately be necessary.
> "
>
> I might not have understood the implementation completely -- can't we
> use fmgr_last_builtin_oid to detect built-in functions?
> --

hi, Amul.

I have removed the pg_cast.casterrorsafe field.
But in the future, to make the below (Examples) CASTs associated with
built-in function
error safe, I think we need pg_cast.casterrorsafe.  Otherwise,
how can we know if the pg_cast.castfunc (built-in function) is error
safe or not.

CREATE CAST (interval AS uuid ) WITH FUNCTION uuidv7(interval);
CREATE CAST (jsonb AS text) WITH FUNCTION jsonb_array_element_text(jsonb, int);
CREATE CAST (json AS text) WITH FUNCTION json_array_element_text(json, int);

I’ve added a dedicated function: CoercionErrorSafeCheck, which
checks whether the cast can be evaluated safely. If not, we throw an error.


SELECT CAST('A' AS DATE DEFAULT NULL ON CONVERSION ERROR)
Here, 'A' is an Unknown Const. As mentioned earlier, Unknown Const Node must be
coerced error safe, otherwise, it will raise an error instead of returning NULL.

The coercion of Unknown Const happens inside coerce_to_target_type, which means
part of that function must run in an error safe.  coerce_to_target_type is used
widely, adding another parameter to it seems no good, so I introduced
coerce_to_target_type_extended, coerce_type_extend.
CoerceUnknownConstSafe is being removed.


stringTypeDatumSafe, OidInputFunctionCallSafe functions are needed for coercing
Unknown Const to the target type.  Refactoring existing function seems not
ideal, so i invented these two functions.


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

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

От:
jian he <jian.universality@gmail.com>
Дата:
On Mon, Dec 1, 2025 at 1:41 PM Corey Huinker  wrote:
>>
>> >> I'm fine with it. I can see having 'f' and 's' both mean cast functions, but 's' means safe, but the extra boolean works too and we'll be fine with either method.
>> >
>> >
>> > I can work on this part if you don't have time.
>>
>> Do you mean change pg_cast.casterrorsafe from boolean to char?
>
>
> No, I meant implementing the syntax for being able to declare a custom CAST function as safe (or not). Basically adding the [SAFE] to
>
> CREATE CAST (source_type AS target_type)
>     WITH [SAFE] FUNCTION function_name [ (argument_type [, ...]) ]
>
> I'm not tied to this syntax choice, but this one seemed the most obvious and least invasive.
>

hi.
In v14, I have removed pg_cast.casterrorsafe, but for user-defined CREATE CAST,
castfunc can be built-in function or user-defined function, we do need a way to
distinguish if the cast function is error safe or not.

I’ll incorporate pg_cast.casterrorsafe along with the implementation of the
user-defined CREATE CAST syntax into one patch.

> But this brings up an interesting point: if a cast is declared as WITHOUT FUNCTION aka COERCION_METHOD_BINARY, then the cast can never fail, and we should probably check for that because a cast that cannot fail can ignore the DEFAULT clause altogether and fall back to being an ordinary CAST().
>
>>

integer and oid are binary coercible, but the following should fail.
SELECT CAST(11 as oid DEFAULT 'a' ON CONVERSION ERROR);

if you mean that skip
+ ExecInitExprRec((Expr *) stcstate->stcexpr->default_expr,
+ state, resv, resnull);
For binary-coercible types, this approach seems fine. We’ve done something
similar in ExecInitExprRec for T_ArrayCoerceExpr.
```
                if (elemstate->steps_len == 1 &&
                    elemstate->steps[0].opcode == EEOP_CASE_TESTVAL)
                {
                    /* Trivial, so we need no per-element work at runtime */
                    elemstate = NULL;
                }
```
in V14, I didn't do this part, I'll keep this in mind.


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


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

On Tue, Dec 9, 2025 at 11:39 AM jian he  wrote:
>
> On Mon, Dec 1, 2025 at 1:41 PM Corey Huinker  wrote:
> >>
> > No, I meant implementing the syntax for being able to declare a custom CAST function as safe (or not). Basically adding the [SAFE] to
> >
> > CREATE CAST (source_type AS target_type)
> >     WITH [SAFE] FUNCTION function_name [ (argument_type [, ...]) ]
> >
> > I'm not tied to this syntax choice, but this one seemed the most obvious and least invasive.
> >

hi.
please see the attached v15.
the primary implementation of CAST DEFAULT is contained in V15-0021.

changes compared to v14.
1. separate patch (v15-0017) for float error.
-pg_noreturn extern void float_overflow_error(void);
-pg_noreturn extern void float_underflow_error(void);
-pg_noreturn extern void float_zero_divide_error(void);
+extern void float_overflow_error(struct Node *escontext);
+extern void float_underflow_error(struct Node *escontext);
+extern void float_zero_divide_error(struct Node *escontext);

2. separate patch (v15-0018) for newly added float8 functions:
float8_pl_safe
float8_mi_safe
float8_mul_safe
float8_div_safe
refactoring existing functions is too invasive, I choose not to.

3. refactor point_dt (v15-0019). This is necessary for making geometry data type
error-safe, separate from the main patch (v15-0020). I hope to make it easier to
review.
-static inline float8 point_dt(Point *pt1, Point *pt2);
+static inline float8 point_dt(Point *pt1, Point *pt2, Node *escontext);

4. skip compile DEFAULT expression (ExecInitExprRec) for binary coercion cast,
as mentioned before.  See ExecInitSafeTypeCastExpr.

5.  Support user-defined type cast error-safe, see v15-0022.
user-defined error-safe cast syntax:
CREATE CAST (source_type AS target_type)
    WITH [SAFE] FUNCTION function_name [ (argument_type [, ...]) ]
    [ AS ASSIGNMENT | AS IMPLICIT ]

this only adds a new keyword SAFE.
This works for C and internal language functions only now.
To make it really usable, I have made citext, hstore module castfunc error safe.
A new column: pg_cast.casterrorsafe was added, this is needed for
CREATE CAST WITH SAFE FUNCTION.

+select CAST(ARRAY['a','g','b','h',null,'i'] AS hstore
+       DEFAULT NULL ON CONVERSION ERROR);
+ array
+-------
+
+(1 row)
+

6. slightly polished the doc.


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

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

От:
Kirill Reshke <reshkekirill@gmail.com>
Дата:
On Wed, 10 Dec 2025 at 13:58, jian he  wrote:
>
> On Tue, Dec 9, 2025 at 11:39 AM jian he  wrote:
> >
> > On Mon, Dec 1, 2025 at 1:41 PM Corey Huinker  wrote:
> > >>
> > > No, I meant implementing the syntax for being able to declare a custom CAST function as safe (or not). Basically adding the [SAFE] to
> > >
> > > CREATE CAST (source_type AS target_type)
> > >     WITH [SAFE] FUNCTION function_name [ (argument_type [, ...]) ]
> > >
> > > I'm not tied to this syntax choice, but this one seemed the most obvious and least invasive.
> > >
>
> hi.
> please see the attached v15.
> the primary implementation of CAST DEFAULT is contained in V15-0021.
>
> changes compared to v14.
> 1. separate patch (v15-0017) for float error.
> -pg_noreturn extern void float_overflow_error(void);
> -pg_noreturn extern void float_underflow_error(void);
> -pg_noreturn extern void float_zero_divide_error(void);
> +extern void float_overflow_error(struct Node *escontext);
> +extern void float_underflow_error(struct Node *escontext);
> +extern void float_zero_divide_error(struct Node *escontext);
>
> 2. separate patch (v15-0018) for newly added float8 functions:
> float8_pl_safe
> float8_mi_safe
> float8_mul_safe
> float8_div_safe
> refactoring existing functions is too invasive, I choose not to.
>
> 3. refactor point_dt (v15-0019). This is necessary for making geometry data type
> error-safe, separate from the main patch (v15-0020). I hope to make it easier to
> review.
> -static inline float8 point_dt(Point *pt1, Point *pt2);
> +static inline float8 point_dt(Point *pt1, Point *pt2, Node *escontext);
>
> 4. skip compile DEFAULT expression (ExecInitExprRec) for binary coercion cast,
> as mentioned before.  See ExecInitSafeTypeCastExpr.
>
> 5.  Support user-defined type cast error-safe, see v15-0022.
> user-defined error-safe cast syntax:
> CREATE CAST (source_type AS target_type)
>     WITH [SAFE] FUNCTION function_name [ (argument_type [, ...]) ]
>     [ AS ASSIGNMENT | AS IMPLICIT ]
>
> this only adds a new keyword SAFE.
> This works for C and internal language functions only now.
> To make it really usable, I have made citext, hstore module castfunc error safe.
> A new column: pg_cast.casterrorsafe was added, this is needed for
> CREATE CAST WITH SAFE FUNCTION.
>
> +select CAST(ARRAY['a','g','b','h',null,'i'] AS hstore
> +       DEFAULT NULL ON CONVERSION ERROR);
> + array
> +-------
> +
> +(1 row)
> +
>
> 6. slightly polished the doc.
>
>
> --
> jian
> https://www.enterprisedb.com/

Hi!

Overall, I think this patch is doing a good thing. Also, are we
holding it until the next SQL standard release, because sql/23 leaks
this feature?

Below are my 2c.

1)
First of all, I would prefer the `Bumps catversion` comment in the
commit msg of v15-0022.

2)
In v15-0006, if dont understand when memory allocated by
`result = (macaddr *) palloc0(sizeof(macaddr));` will be freed. Does
it persist until the query ends? I tried to get OOM with a query that
errors out macaddr8 casts repeatedly, but failed.

3)
 > * When error_safe set to true, we will evaluate the constant expression in a
 > * error safe way. If the evaluation fails, return NULL instead of throwing
 > * error.

Somebody has to say it - s/error_safe set/error_safe is set/, also
s/throwing error/throwing an error/



--
Best regards,
Kirill Reshke


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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
Overall, I think this patch is doing a good thing. Also, are we
holding it until the next SQL standard release, because sql/23 leaks
this feature?

The impression that I get is that the SQL Standard has become more descriptive and less prescriptive. It takes things that exist and builds the standard around those, so by implementing this draft feature, we help ensure that it makes it into the standard.

This might be counter-intuitive, but that's what dictionaries do: they describe how the language is used (descriptive), rather than dictate how it should be used (prescriptive).

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

hi.

On Wed, Dec 10, 2025 at 9:32 PM Kirill Reshke  wrote:
>
> Hi!
>
> Overall, I think this patch is doing a good thing. Also, are we
> holding it until the next SQL standard release, because sql/23 leaks
> this feature?
>
> Below are my 2c.
>
> 1)
> First of all, I would prefer the `Bumps catversion` comment in the
> commit msg of v15-0022.
>
ok.

> 2)
> In v15-0006, if dont understand when memory allocated by
> `result = (macaddr *) palloc0(sizeof(macaddr));` will be freed. Does
> it persist until the query ends? I tried to get OOM with a query that
> errors out macaddr8 casts repeatedly, but failed.
>

  if ((addr->d != 0xFF) || (addr->e != 0xFE))
- ereport(ERROR,
+ ereturn(fcinfo->context, (Datum) 0,
  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
  errmsg("macaddr8 data out of range to convert to macaddr"),
  errhint("Only addresses that have FF and FE as values in the "

the change is minor, changing ereport to ereturn.
The whole refactoring does not related to OOM errror,
OOM errors will behave exactly as they did previously.


> 3)
>  > * When error_safe set to true, we will evaluate the constant expression in a
>  > * error safe way. If the evaluation fails, return NULL instead of throwing
>  > * error.
>
> Somebody has to say it - s/error_safe set/error_safe is set/, also
> s/throwing error/throwing an error/
>
sure.

mainly rebase due to recent palloc_object, palloc_array conflict.


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

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

От:
Amul Sul <sulamul@gmail.com>
Дата:
Hi,

I am still thinking through a design that avoids having two different
code paths for type casting. Can't we avoid adding a new SafeTypeCast
structure by simply adding a raw_default variable (name could be
simply default) to the existing TypeCast structure? If we do that, we
would need to update transformTypeCast() and other places (like
ExecInterpExpr()) to handle the raw_default. This approach would allow
us to avoid the extra code required for a new node structure (e.g.,
T_SafeTypeCastExpr) and a separate EEOP_SAFETYPE_CAST step.

Here are few other comments:

vv16-0019:

+float8_div_safe(const float8 val1, const float8 val2, struct Node *escontext)

Patches show an inconsistent use of Node* and struct Note * for the
escontext argument. I suggest standardising on Note * to maintain
consistency throughout the code.
--

v16-0020:

@@ -839,7 +839,7 @@ box_distance(PG_FUNCTION_ARGS)
    box_cn(&a, box1);
    box_cn(&b, box2);

-   PG_RETURN_FLOAT8(point_dt(&a, &b));
+   PG_RETURN_FLOAT8(point_dt(&a, &b, NULL));

I think user-callable functions that accept PG_FUNCTION_ARGS;
should directly pass fcinfo->context instead of NULL.
--

v16-0022:

+Sometimes a type cast may fail; to avoid such fail case, an
ON ERROR clause can be
..
+    default expression in ON
ERROR clause.

Shouldn't it be ON CONVERSION ERROR instead of ON ERROR ?
--

+   state->escontext = makeNode(ErrorSaveContext);
+   state->escontext->type = T_ErrorSaveContext;
+   state->escontext->error_occurred = false;
+   state->escontext->details_wanted = false;

No need to assign values to the rest of the escontext members;
makeNode(ErrorSaveContext) is sufficient. I also think
ExecInitExprSafe() should receive escontext from the caller. Instead
of passing an error_safe boolean to evaluate_expr, you can pass the
escontext itself; this can then be passed down to ExecInitExprSafe,
helping capture soft error information at a much higher level.

In that way, you can simply call ExecInitExprSafe() from
ExecInitExpr() and pass NULL for the escontext. This reduces code
duplication, since most of the code is similar except for the
aforementioned initialization lines.


Regards,
Amul


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

On Fri, Jan 2, 2026 at 2:08 PM Amul Sul  wrote:
>
> Hi,
>
> I am still thinking through a design that avoids having two different
> code paths for type casting. Can't we avoid adding a new SafeTypeCast
> structure by simply adding a raw_default variable (name could be
> simply default) to the existing TypeCast structure? If we do that, we
> would need to update transformTypeCast() and other places (like
> ExecInterpExpr()) to handle the raw_default. This approach would allow
> us to avoid the extra code required for a new node structure (e.g.,
> T_SafeTypeCastExpr) and a separate EEOP_SAFETYPE_CAST step.
>

Hi.

transformTypeCast transforms a TypeCast node and may produce one of the
following nodes: FuncExpr, CollateExpr, CoerceToDomain, ArrayCoerceExpr, or
CoerceViaIO.

To avoid EEOP_SAFETY_CAST, the returned node would need an
additional field to store the transformed DEFAULT expression.
This implies adding such a field to the aforementioned node types; otherwise,
the information about the transformed default expression would be lost.

However, adding an extra field to nodes such as FuncExpr seems not doable.
It is not generally applicable to FuncExpr, but rather only relevant to a
specific usage scenario. In addition, it may introduce unnecessary overhead.

T_SafeTypeCastExpr is still needed for holding the transformed cast expression
and default expression, I think.

However, we can add a field to node TypeCast for the raw default expression.
transformTypeSafeCast seems not needed, so I consolidated
the parsing analysis into transformTypeCast.

> Here are few other comments:
>
> vv16-0019:
>
> +float8_div_safe(const float8 val1, const float8 val2, struct Node *escontext)
>
> Patches show an inconsistent use of Node* and struct Note * for the
> escontext argument. I suggest standardising on Note * to maintain
> consistency throughout the code.
> --
>

This inconsistency already exists in the codebase,
we already have many files using "struct Node *escontext".
I guess the reason is to avoid "#include "nodes/nodes.h"
in src/include/utils/float.h

> v16-0020:
>
> @@ -839,7 +839,7 @@ box_distance(PG_FUNCTION_ARGS)
>     box_cn(&a, box1);
>     box_cn(&b, box2);
>
> -   PG_RETURN_FLOAT8(point_dt(&a, &b));
> +   PG_RETURN_FLOAT8(point_dt(&a, &b, NULL));
>
> I think user-callable functions that accept PG_FUNCTION_ARGS;
> should directly pass fcinfo->context instead of NULL.
> --
>

This seems overall good for me. since next time, if we want
other functions to be error safe, we don't need to do this again.


> v16-0022:
>
> +Sometimes a type cast may fail; to avoid such fail case, an
> ON ERROR clause can be
> ..
> +    default expression in ON
> ERROR clause.
>
> Shouldn't it be ON CONVERSION ERROR instead of ON ERROR ?
> --
>

ON CONVERSION ERROR is ok for me.


> +   state->escontext = makeNode(ErrorSaveContext);
> +   state->escontext->type = T_ErrorSaveContext;
> +   state->escontext->error_occurred = false;
> +   state->escontext->details_wanted = false;
>
> No need to assign values to the rest of the escontext members;
> makeNode(ErrorSaveContext) is sufficient. I also think
> ExecInitExprSafe() should receive escontext from the caller. Instead
> of passing an error_safe boolean to evaluate_expr, you can pass the
> escontext itself; this can then be passed down to ExecInitExprSafe,
> helping capture soft error information at a much higher level.
>
> In that way, you can simply call ExecInitExprSafe() from
> ExecInitExpr() and pass NULL for the escontext. This reduces code
> duplication, since most of the code is similar except for the
> aforementioned initialization lines.
>

now i changed it to:

ExprState *
ExecInitExpr(Expr *node, PlanState *parent)
{
    return ExecInitExprExtended(node, NULL, parent);
}

ExprState *
ExecInitExprExtended(Expr *node, Node *escontext, PlanState *parent)


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

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
On Mon, Jan 5, 2026 at 1:01 AM jian he <jian.universality@gmail.com> wrote:
On Fri, Jan 2, 2026 at 2:08 PM Amul Sul <sulamul@gmail.com> wrote:
>
> Hi,
>
> I am still thinking through a design that avoids having two different
> code paths for type casting. Can't we avoid adding a new SafeTypeCast
> structure by simply adding a raw_default variable (name could be
> simply default) to the existing TypeCast structure? If we do that, we
> would need to update transformTypeCast() and other places (like
> ExecInterpExpr()) to handle the raw_default. This approach would allow
> us to avoid the extra code required for a new node structure (e.g.,
> T_SafeTypeCastExpr) and a separate EEOP_SAFETYPE_CAST step.
>

If that code path requires all casting operations to have the overhead of safety, then that may be a significant performance regression and a non-starter. I think we should continue with the design as-is, and if it turns out later than we can merge the safe/unsafe code paths without impacting performance, then we'll do it.

Jian, can you rebase the patch-set? I tried applying it today, without luck.

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

От:
Amul Sul <sulamul@gmail.com>
Дата:
On Mon, Jan 5, 2026 at 11:31 AM jian he  wrote:
>
> On Fri, Jan 2, 2026 at 2:08 PM Amul Sul  wrote:
> >
> transformTypeCast transforms a TypeCast node and may produce one of the
> following nodes: FuncExpr, CollateExpr, CoerceToDomain, ArrayCoerceExpr, or
> CoerceViaIO.
>
> To avoid EEOP_SAFETY_CAST, the returned node would need an
> additional field to store the transformed DEFAULT expression.
> This implies adding such a field to the aforementioned node types; otherwise,
> the information about the transformed default expression would be lost.
>
> However, adding an extra field to nodes such as FuncExpr seems not doable.
> It is not generally applicable to FuncExpr, but rather only relevant to a
> specific usage scenario. In addition, it may introduce unnecessary overhead.
>
>
> T_SafeTypeCastExpr is still needed for holding the transformed cast expression
> and default expression, I think.
>

Oh okay.

> [...]
> However, we can add a field to node TypeCast for the raw default expression.
> transformTypeSafeCast seems not needed, so I consolidated
> the parsing analysis into transformTypeCast.
>

Yeah, but I am a bit unsure about the naming (i.e., raw_default) and
the comment stating this is an "untransformed DEFAULT expression".
What is the status of the arg member of the TypeCast structure -- is
it transformed or untransformed? If that is also untransformed, we can
simply drop "untransformed" word from the comment and rename
raw_default to something more descriptive, such as defaultExpr.
Currently, raw_default doesn't clearly indicate that it represents an
expression, IMO.

Also, a few comments still refer to old transformTypeSafeCast(), which
needs to be corrected.

> > In that way, you can simply call ExecInitExprSafe() from
> > ExecInitExpr() and pass NULL for the escontext. This reduces code
> > duplication, since most of the code is similar except for the
> > aforementioned initialization lines.
> >
>
> now i changed it to:
>
> ExprState *
> ExecInitExpr(Expr *node, PlanState *parent)
> {
>     return ExecInitExprExtended(node, NULL, parent);
> }
>
> ExprState *
> ExecInitExprExtended(Expr *node, Node *escontext, PlanState *parent)
>

Yes, that looks like what I was thinking, but with the Node *escontext
at the last position.

I am not fully confident that the v17-0022 patch is complete. I
believe there is a good chance to improve the patch in terms of
coding, formatting, function and variable naming, as well as some
refactoring and optimization that I still need to think on. Here are a
few comments:

+       /*
+        * The collation of DEFAULT expression must match the collation of the
+        * target type.
+        */
+       defColl = exprCollation(defexpr);
+
+       if (OidIsValid(targetTypecoll) && OidIsValid(defColl) &&
+           targetTypecoll != defColl)
+           ereport(ERROR,
+                   errcode(ERRCODE_DATATYPE_MISMATCH),
+                   errmsg("the collation of CAST DEFAULT expression
conflicts with target type collation"),

What if one collation is an invalid OID and the other is valid?
Shouldn't we throw an error in that case?
--

+       SafeTypeCastState *stcstate;
+
+       stcstate = palloc0(sizeof(SafeTypeCastState));
+       stcstate->stcexpr = stcexpr;
+       stcstate->escontext.type = T_ErrorSaveContext;
+       state->escontext = &stcstate->escontext;

Can't we reuse the state->escontext pointer in the SafeTypeCastState
instead of allocating a separate ErrorSaveContext?
--

+           ErrorSaveContext *saved_escontext;
+
+           saved_escontext = state->escontext;
+
+           state->escontext = NULL;
+
+           ExecInitExprRec((Expr *) stcstate->stcexpr->default_expr,
+                           state, resv, resnull);
+
+           state->escontext = saved_escontext;

Here should be some comment explanation as to why you are setting
state->escontext = NULL, and why that is needed for the default
expression initialization but not for the case_expr evaluation.
--

+
+   fmgr_info(functionId, &flinfo);
+
+   return InputFunctionCallSafe(&flinfo, str, typioparam, typmod,
+                                escontext, result);

Remove the empty line between these two for consistency with other
function's formatting.
--

+               ? errhint("Safe type cast for user-defined types are
not yet supported")
+               : errhint("Explicit cast is defined but definition is
not error safe"),

Hints should end with a period.
--

+               /*
+                * Here, we cannot deparsing cast_expr directly, since
+                * transformTypeSafeCast may have folded it into a simple
+                * constant or NULL. Instead, we use source_expr and
+                * default_expr to reconstruct the CAST DEFAULT clause.
+                */

I am wondering how other places handle expression deparsing; do they
hold the original expression along with the transformed expression?
Also, why are we only folding constants from the source_expr but not
from the default expression?

Regards,
Amul


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

On Tue, Jan 13, 2026 at 1:50 PM Amul Sul  wrote:
>
> > [...]
> > However, we can add a field to node TypeCast for the raw default expression.
> > transformTypeSafeCast seems not needed, so I consolidated
> > the parsing analysis into transformTypeCast.
> >
>
> Yeah, but I am a bit unsure about the naming (i.e., raw_default) and
> the comment stating this is an "untransformed DEFAULT expression".
> What is the status of the arg member of the TypeCast structure -- is
> it transformed or untransformed? If that is also untransformed, we can
> simply drop "untransformed" word from the comment and rename
> raw_default to something more descriptive, such as defaultExpr.
> Currently, raw_default doesn't clearly indicate that it represents an
> expression, IMO.
>

ColumnDef->raw_default comments:
/* default value (untransformed parse tree) */

FunctionParameter->defexpr comments:
/* raw default expr, or NULL if not given */

so i changed it to "defexpr".

> Also, a few comments still refer to old transformTypeSafeCast(), which
> needs to be corrected.
>
ok.

> > ExprState *
> > ExecInitExprExtended(Expr *node, Node *escontext, PlanState *parent)
> >
>
> Yes, that looks like what I was thinking, but with the Node *escontext
> at the last position.
>
ok.

> +       /*
> +        * The collation of DEFAULT expression must match the collation of the
> +        * target type.
> +        */
> +       defColl = exprCollation(defexpr);
> +
> +       if (OidIsValid(targetTypecoll) && OidIsValid(defColl) &&
> +           targetTypecoll != defColl)
> +           ereport(ERROR,
> +                   errcode(ERRCODE_DATATYPE_MISMATCH),
> +                   errmsg("the collation of CAST DEFAULT expression
> conflicts with target type collation"),
>
> What if one collation is an invalid OID and the other is valid?
> Shouldn't we throw an error in that case?

That is unlikely to happen. Since a collatable type can not be cast to
non-collatable type.
To be bullet-proof, use ``if (targetTypecoll != defColl)`` should be fine.

> --
>
> +       SafeTypeCastState *stcstate;
> +
> +       stcstate = palloc0(sizeof(SafeTypeCastState));
> +       stcstate->stcexpr = stcexpr;
> +       stcstate->escontext.type = T_ErrorSaveContext;
> +       state->escontext = &stcstate->escontext;
>
> Can't we reuse the state->escontext pointer in the SafeTypeCastState
> instead of allocating a separate ErrorSaveContext?
> --
>

When entering ExecInitSafeTypeCastExpr, we cannot be
sure about ExprState->escontext, it can be NULL.
Therefore, reusing the state->escontext pointer is not possible, i think.

> +           ErrorSaveContext *saved_escontext;
> +
> +           saved_escontext = state->escontext;
> +
> +           state->escontext = NULL;
> +
> +           ExecInitExprRec((Expr *) stcstate->stcexpr->default_expr,
> +                           state, resv, resnull);
> +
> +           state->escontext = saved_escontext;
>
> Here should be some comment explanation as to why you are setting
> state->escontext = NULL, and why that is needed for the default
> expression initialization but not for the case_expr evaluation.
> --

``
select cast(a as int default b on conversion error) from (values ('a',
'b')) t(a,b);
``

The above example should fail during evaluation of the DEFAULT
expression. Therefore,
we cannot compile `stcstate->stcexpr->defexpr` error safely.

As a result, setting ``state->escontext = NULL;`` is necessary.
Since we do not want to override its previous value, saving and restoring it via
`saved_escontext` is required.

I've added comments to explain it.

summary:
1. when entering ExecInitSafeTypeCastExpr, we can not use
ExprState->escontext directly
2. we evaluation the cast expression error safe, ExprState->escontext
should pass
a valid ErrorSaveContext
3. we do not evaluation the default expression error safe, ExprState->escontext
should be NULL

>
> +
> +   fmgr_info(functionId, &flinfo);
> +
> +   return InputFunctionCallSafe(&flinfo, str, typioparam, typmod,
> +                                escontext, result);
>
> Remove the empty line between these two for consistency with other
> function's formatting.
> --
ok.

> +               ? errhint("Safe type cast for user-defined types are
> not yet supported")
> +               : errhint("Explicit cast is defined but definition is
> not error safe"),
>
> Hints should end with a period.
> --
ok.

> +               /*
> +                * Here, we cannot deparsing cast_expr directly, since
> +                * transformTypeSafeCast may have folded it into a simple
> +                * constant or NULL. Instead, we use source_expr and
> +                * default_expr to reconstruct the CAST DEFAULT clause.
> +                */
>
> I am wondering how other places handle expression deparsing; do they
> hold the original expression along with the transformed expression?
> Also, why are we only folding constants from the source_expr but not
> from the default expression?
>

SELECT CAST(1111 AS "char" DEFAULT 1 ON CONVERSION ERROR);
SELECT CAST(1111 AS "char" DEFAULT (cast (1111 AS "char")) ON CONVERSION ERROR);

We want the first case to succeed and the second case to fail. To ensure the
first case does not fail, we need avoid running eval_const_expressions on
SafeTypeCastExpr->cast_expr. The second case will still fail when
eval_const_expressions_mutator performs constant folding on
SafeTypeCastExpr->default_expr.

We cannot perform constant folding on SafeTypeCastExpr->cast_expr, but still
want to detect some simple cases—specifically, whether the source expression can
be coerced to the target type, so part of the constant-folding logic is in the
transformTypeCast->evaluate_expr. evaluate_expr is error-safe, this is what we
want.  As a consequence, ruleutils.c can only use source_expr.

We already have a similar approach for handling deparsing in get_rule_expr.
```
        case T_JsonValueExpr:
            {
                JsonValueExpr *jve = (JsonValueExpr *) node;
                get_rule_expr((Node *) jve->raw_expr, context, false);
                get_json_format(jve->format, context->buf);
            }
            break;
```

rebased, many variable names have been renamed, comments adjusted.


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

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
> +               /*
> +                * Here, we cannot deparsing cast_expr directly, since
> +                * transformTypeSafeCast may have folded it into a simple
> +                * constant or NULL. Instead, we use source_expr and
> +                * default_expr to reconstruct the CAST DEFAULT clause.
> +                */
>
> I am wondering how other places handle expression deparsing; do they
> hold the original expression along with the transformed expression?

In my initial implementation of this, I modified CoalesceExpr to ensure that the default clause was evaluated if and only if the initial expression failed.

 
rebased, many variable names have been renamed, comments adjusted.

The new SAFE option on user defined cast functions looks good to me.

I am concerned that adding _safe overhead to all cast functions will be received poorly, but if it is poorly received then reverting isn't that hard.

I'm going to re-review the whole patch set, but I wanted to say that I like the main points of the changes so far.

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
On Wed, Jan 14, 2026 at 5:16 PM Corey Huinker <corey.huinker@gmail.com> wrote:
> +               /*
> +                * Here, we cannot deparsing cast_expr directly, since
> +                * transformTypeSafeCast may have folded it into a simple
> +                * constant or NULL. Instead, we use source_expr and
> +                * default_expr to reconstruct the CAST DEFAULT clause.
> +                */
>
> I am wondering how other places handle expression deparsing; do they
> hold the original expression along with the transformed expression?

In my initial implementation of this, I modified CoalesceExpr to ensure that the default clause was evaluated if and only if the initial expression failed.

 
rebased, many variable names have been renamed, comments adjusted.

The new SAFE option on user defined cast functions looks good to me.

I am concerned that adding _safe overhead to all cast functions will be received poorly, but if it is poorly received then reverting isn't that hard.

I'm going to re-review the whole patch set, but I wanted to say that I like the main points of the changes so far.

I picked this back up again, pondered adding the IS CASTABLE AS syntax to the patch, but ultimately decided that it should be a separate patch.

While I still think the patch order is a bit backwards [1], the order chosen does have a sense to it, and whether or not that is the right order is up to the committer. Please post a rebase so I can mark it as ready for committer.


[1] I would have preferred adding the CAST functionality first, then switching over each datatype one-by-one, thus demonstrating that non-safe datatypes can co-exist with this new functionality. But that's just my personal preference.

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

On Wed, Mar 11, 2026 at 12:22 AM Corey Huinker  wrote:
>
> While I still think the patch order is a bit backwards [1], the order chosen does have a sense to it, and whether or not that is the right order is up to the committer. Please post a rebase so I can mark it as ready for committer.
>
>
> [1] I would have preferred adding the CAST functionality first, then switching over each datatype one-by-one, thus demonstrating that non-safe datatypes can co-exist with this new functionality. But that's just my personal preference.

We can evaluate CoerceViaIO in an error-safe manner in the HEAD.
However, as discussed in this thread[1], we cannot simply take a FuncExpr
produced by a TYPE CAST, convert it to a CoerceViaIO node, and rely on
CoerceViaIO to do the actual soft-error evaluation.
Therefore to support the CAST(expr AS newtype DEFAULT expr ON CONVERSION ERROR)
syntax, refactoring the existing cast functions to make them error-safe is
really necessary.
Overall I think refactoring the existing cast function (replacing
ereport to ereturn or errsave) should be done first.

I did one more round of comment refactoring and variable renaming.

[1]: https://www.postgresql.org/message-id/CACJufxGw_OY7K3rfG4kDb902O2guhT-wgTjTJQ%3DpWeVWRTHpHQ%40mail.gmail.com


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

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
On Thu, Mar 12, 2026 at 9:00 PM jian he <jian.universality@gmail.com> wrote:
On Wed, Mar 11, 2026 at 12:22 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>
> While I still think the patch order is a bit backwards [1], the order chosen does have a sense to it, and whether or not that is the right order is up to the committer. Please post a rebase so I can mark it as ready for committer.
>
>
> [1] I would have preferred adding the CAST functionality first, then switching over each datatype one-by-one, thus demonstrating that non-safe datatypes can co-exist with this new functionality. But that's just my personal preference.

We can evaluate CoerceViaIO in an error-safe manner in the HEAD.
However, as discussed in this thread[1], we cannot simply take a FuncExpr
produced by a TYPE CAST, convert it to a CoerceViaIO node, and rely on
CoerceViaIO to do the actual soft-error evaluation.
Therefore to support the CAST(expr AS newtype DEFAULT expr ON CONVERSION ERROR)
syntax, refactoring the existing cast functions to make them error-safe is
really necessary.
Overall I think refactoring the existing cast function (replacing
ereport to ereturn or errsave) should be done first.

I did one more round of comment refactoring and variable renaming.

Can you explain this bit below?

@@ -595,13 +605,23 @@ RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode,
  {
  int elevel = (flags & RVR_SKIP_LOCKED) ? DEBUG1 : ERROR;
 
- if (relation->schemaname)
- ereport(elevel,
+ if (relation->schemaname && elevel == DEBUG1)
+ ereport(DEBUG1,
  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
  errmsg("could not obtain lock on relation \"%s.%s\"",
  relation->schemaname, relation->relname)));
- else
- ereport(elevel,
+ else if (relation->schemaname && elevel == ERROR)
+ ereturn(escontext, InvalidOid,
+ errcode(ERRCODE_LOCK_NOT_AVAILABLE),
+ errmsg("could not obtain lock on relation \"%s.%s\"",
+   relation->schemaname, relation->relname));
+ else if (elevel == DEBUG1)
+ ereport(DEBUG1,
+ errcode(ERRCODE_LOCK_NOT_AVAILABLE),
+ errmsg("could not obtain lock on relation \"%s\"",
+   relation->relname));
+ else if (elevel == ERROR)
+ ereturn(escontext, InvalidOid,

 

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

От:
jian he <jian.universality@gmail.com>
Дата:
On Fri, Mar 13, 2026 at 11:59 AM Corey Huinker  wrote:
>
> Can you explain this bit below?
>
> @@ -595,13 +605,23 @@ RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode,
>   {
>   int elevel = (flags & RVR_SKIP_LOCKED) ? DEBUG1 : ERROR;
>
> - if (relation->schemaname)
> - ereport(elevel,
> + if (relation->schemaname && elevel == DEBUG1)
> + ereport(DEBUG1,
>   (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
>   errmsg("could not obtain lock on relation \"%s.%s\"",
>   relation->schemaname, relation->relname)));
> - else
> - ereport(elevel,
> + else if (relation->schemaname && elevel == ERROR)
> + ereturn(escontext, InvalidOid,
> + errcode(ERRCODE_LOCK_NOT_AVAILABLE),
> + errmsg("could not obtain lock on relation \"%s.%s\"",
> +   relation->schemaname, relation->relname));
> + else if (elevel == DEBUG1)
> + ereport(DEBUG1,
> + errcode(ERRCODE_LOCK_NOT_AVAILABLE),
> + errmsg("could not obtain lock on relation \"%s\"",
> +   relation->relname));
> + else if (elevel == ERROR)
> + ereturn(escontext, InvalidOid,
>

This is for supporting casting text to regclass error safe, for example:
SELECT CAST('abc'::text as regclass default NULL on conversion error);

To do that, we need to refactor the RangeVarGetRelidExtended function
to make it error-safe.
We can also change it as:

if (relation->schemaname)
{
    if (elevel == DEBUG1)
        ereport(DEBUG1,
                (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                errmsg("could not obtain lock on relation \"%s.%s\"",
                        relation->schemaname, relation->relname)));
    else
        ereturn(escontext, InvalidOid,
                errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                errmsg("could not obtain lock on relation \"%s.%s\"",
                    relation->schemaname, relation->relname));
}
else
{
    if (elevel == DEBUG1)
        ereport(DEBUG1,
                errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                errmsg("could not obtain lock on relation \"%s\"",
                    relation->relname));
    else
        ereturn(escontext, InvalidOid,
                (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                errmsg("could not obtain lock on relation \"%s\"",
                        relation->relname)));
}


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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:

To do that, we need to refactor the RangeVarGetRelidExtended function
to make it error-safe.
We can also change it as:

Ok, thanks. 

Hmm, seems we've got a new compile error:
 

FAILED: [code=1] src/backend/postgres_lib.a.p/executor_execExpr.c.o
cc -Isrc/backend/postgres_lib.a.p -Isrc/include -I../src/include -I/usr/include/libxml2 -fdiagnostics-color=always -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -O2 -g -fno-strict-aliasing -fwrapv -fexcess-precision=standard -D_GNU_SOURCE -Wmissing-prototypes -Wpointer-arith -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wcast-function-type -Wshadow=compatible-local -Wformat-security -Wimplicit-fallthrough=5 -Wdeclaration-after-statement -Wmissing-variable-declarations -Wno-format-truncation -Wno-stringop-truncation -fPIC -DWITH_GZFILEOP -pthread -DBUILDING_DLL -MD -MQ src/backend/postgres_lib.a.p/executor_execExpr.c.o -MF src/backend/postgres_lib.a.p/executor_execExpr.c.o.d -o src/backend/postgres_lib.a.p/executor_execExpr.c.o -c ../src/backend/executor/execExpr.c
../src/backend/executor/execExpr.c: In function ‘ExecInitQual’:
../src/backend/executor/execExpr.c:269:49: error: ‘escontext’ undeclared (first use in this function); did you mean ‘errcontext’?
  269 |         state->escontext = (ErrorSaveContext *) escontext;
      |                                                 ^~~~~~~~~
      |                                                 errcontext
../src/backend/executor/execExpr.c:269:49: note: each undeclared identifier is reported only once for each function it appears in
 

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

Hi.
please check the attached v20.



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

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:


On Fri, Mar 13, 2026 at 2:19 AM jian he <jian.universality@gmail.com> wrote:
Hi.
please check the attached v20.



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

LGTM. 

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

On Mon, Mar 16, 2026 at 11:48 AM Corey Huinker  wrote:
>
> LGTM.

Thanks for the review.
For the context of
v20-0022-CAST-expr-AS-newtype-DEFAULT-expr-ON-CONVERSION-ERROR.patch

+/*
+ * Check type coercion is error safe or not.  If not then report error
+ */
+static void
+CoercionErrorSafeCheck(ParseState *pstate, Node *castexpr, Node *source,
+   Oid inputType, Oid targetType)
+{
+ Oid inputBaseType;
+ Oid targetBaseType;
+ Oid inputElementType;
+ Oid inputElementBaseType;
+ Oid targetElementType;
+ Oid targetElementBaseType;
+ inputElementType = get_element_type(inputType);
+
+ if (OidIsValid(inputElementType))
+ inputElementBaseType = getBaseType(inputElementType);
+ else
+ {
+ inputBaseType = getBaseType(inputType);
+ inputElementBaseType = get_element_type(inputBaseType);
+
+ if (!OidIsValid(inputElementBaseType))
+ inputElementBaseType = inputBaseType;
+ }
+
+ targetElementType = get_element_type(targetType);
+
+ if (OidIsValid(targetElementType))
+ targetElementBaseType = getBaseType(targetElementType);
+ else
+ {
+ targetBaseType = getBaseType(targetType);
+ targetElementBaseType = get_element_type(targetBaseType);
+
+ if (!OidIsValid(targetElementBaseType))
+ targetElementBaseType = targetBaseType;
+ }
+
+ if (inputElementBaseType == MONEYOID ||
+ targetElementBaseType == MONEYOID ||
+ (inputElementBaseType == CIRCLEOID &&
+ targetElementBaseType == POLYGONOID))
+ {
+ errorsafe_coercion = false;
+ }
+

Inspired by https://commitfest.postgresql.org/patch/5759/
I found out the above code is wrong, because it failed to imagine
cases like domain over a domain array.
for example:
CREATE DOMAIN d_int42 as int check (value = 42) NOT NULL;
CREATE DOMAIN d_int42arr as d_int42[];
CREATE DOMAIN d_int42arr1 as d_int42arr;
select typname,typtype, typbasetype::regtype, typelem::regtype
from pg_type
where typname in ('d_int42', 'd_int42arr', 'd_int42arr1', '_d_int42');

Therefore we need a little bit of recursive to get the base elements type,
please check new function: CoercionErrorSafe_Internal in v21-0022.

Given the interaction with array and domain coercion, we need to think more
about error-safe type casts for user-defined range, multirange, and composite
types.  For now, we should disallow error-safe casting for these types.



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

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
+ if (inputElementBaseType == MONEYOID ||
+ targetElementBaseType == MONEYOID ||
+ (inputElementBaseType == CIRCLEOID &&
+ targetElementBaseType == POLYGONOID))
+ {
+ errorsafe_coercion = false;
+ }

What if we just reject cast functions with a non-null prosqlbody?
 

Given the interaction with array and domain coercion, we need to think more
about error-safe type casts for user-defined range, multirange, and composite
types.  For now, we should disallow error-safe casting for these types.

I agree. It's far better to get this working for the majority of cases, and we can chip away at more obscure types later. There will *always* be user defined types that we cannot account for.

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

On Wed, Mar 18, 2026 at 11:11 AM Corey Huinker  wrote:
>>
>> + if (inputElementBaseType == MONEYOID ||
>> + targetElementBaseType == MONEYOID ||
>> + (inputElementBaseType == CIRCLEOID &&
>> + targetElementBaseType == POLYGONOID))
>> + {
>> + errorsafe_coercion = false;
>> + }
>
> What if we just reject cast functions with a non-null prosqlbody?
>

src/include/access/transam.h
 *        OIDs 12000-16383 are reserved for unpinned objects created by initdb's
 *        post-bootstrap processing.  initdb forces the OID generator up to
 *        12000 as soon as it's made the pinned objects it's responsible for.
Based on the above comments, I think comparing FirstUnpinnedObjectId
should be enough.

Rebased because of commit:
https://git.postgresql.org/cgit/postgresql.git/commit/?id=ba21f5bf8aff277aa1659a51d26109e0914df182
which add casting between bytea and uuid.

ExecInitFunc now always sets fcinfo->context from state->escontext
```
InitFunctionCallInfoData(*fcinfo, flinfo,
                         nargs, inputcollid,
                         (Node *) state->escontext, NULL);
```
This change in `ExecInitFunc` means **all** FuncExpr evaluations within a
SafeTypeCastExpr context will have their `fcinfo->context` set to the
`ErrorSaveContext`. This is by design for cast functions, but could
accidentally affect non-cast functions that appear in the cast expression
tree and happen to check `fcinfo->context`.

FunctionCallInfoBaseData->context is a generic poiner, it canbe other
than ErrorSaveContext.
For example, in ExecCallTriggerFunc we have:
```
    InitFunctionCallInfoData(*fcinfo, finfo, 0,
                             InvalidOid, (Node *) trigdata, NULL);
```
Because of this, we must differentiate our FuncExpr nodes. Soft-error evaluation
should be only for FuncExpr nodes produced by build_coercion_expression.

We can add a boolean (errorsafe) flag directly to the FuncExpr struct.
This flag to indicate whether this specific expression should be evaluated in an
error-safe manner. In the future, we can also use this flag for

CAST(expr AS type FORMAT 'template' DEFAULT defexpr ON CONVERSION ERROR)

In build_coercion_expression, we set FuncExpr->errorsafe if the specific cast
function needs to be evaluated in an error-safe manner.
build_coercion_expression is also
used in other callers, such as coerce_type_typmod, coerce_to_domain,
that means more refactoring in parse_coerce.c.

V21-0022 JIT related change is totally wrong.
Matheus Alcantara  helped me resolve the JIT issue.
Previously, I wasn't using SET jit_above_cost = 0; to properly
exercise the JIT-related tests.

You mentioned refactoring RangeVarGetRelidExtended in [1],
With a hint from Andrew Dunstan, we can actually reduce the code
duplication, see v22-0004.
[1] https://postgr.es/m/CADkLM=cZ7N+f4Bj-8MiccFcTASjBB2r1_s3BD9OFbbQOwK01cg@mail.gmail.com


As mentioned before, FunctionCallInfoBaseData->context can be other
Node other than ErrorSaveContext.
Therefore for geometry error safe refactoring, we must pass NULL, not
fcinfo->context, for non-cast realted function.
For example, function point_add_point within box_add, the third
parameter should be NULL, not fcinfo->context.

Handling SafeTypeCastExpr->castexpr within eval_const_expressions_mutator is
tricky. However, if it is a FuncExpr node, we can attempt to fold its arguments
(FuncExpr->args).
(Not doing anything for SafeTypeCastExpr->castexpr is easier).

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

On Fri, Mar 20, 2026 at 4:15 PM jian he  wrote:
>
> Handling SafeTypeCastExpr->castexpr within eval_const_expressions_mutator is
> tricky. However, if it is a FuncExpr node, we can attempt to fold its arguments
> (FuncExpr->args).
> (Not doing anything for SafeTypeCastExpr->castexpr is easier).

Just found out that eval_const_expressions_mutator should either
return a Const or recurse to every node field.
If not, the node field may have a COLLATE expression, and
ExecInitExprRec cannot cope with T_CollateExpr. For example:

SELECT CAST('1' collate "C" || 'h' AS text DEFAULT 'fallback' ON
CONVERSION ERROR);
ERROR:  unrecognized node type: 32

Therefore in eval_const_expressions, we cannot skip constant folding
SafeTypeCastExpr->castexpr.
Since eval_const_expressions_mutator is not error-safe, an
ErrorSaveContext pointer was added to eval_const_expressions_context.
It's initialized to NULL, and it will be passed as
``makeNode(ErrorSaveContext)`` inside T_SafeTypeCastExpr.


Previously in [0], I mentioned that SafeTypeCastExpr->castexpr can be FuncExpr,
CollateExpr, CoerceToDomain, ArrayCoerceExpr, or CoerceViaIO or others.

Constant folding in eval_const_expressions for these nodes are
generally processed
through the simplify_function -> evaluate_function -> evaluate_expr.
evaluate_expr can process it in an error-safe manner because the escontext
(ErrorSaveContext) within eval_const_expressions_context is properly populated.

SafeTypeCastExpr->castexpr can also be any Node type if the parse transformed
source expression is the same type as the target type. See
transformTypeCast->coerce_to_target_type_extended->coerce_type_extended:
```
    if (targetTypeId == inputTypeId ||
        node == NULL)
    {
        /* no conversion needed */
        return node;
    }
```
However, if SafeTypeCastExpr->castexpr is the same as
SafeTypeCastExpr->source then
eval_const_expressions premature failure at "source" should be not a
big problem for us.

Since castexpr is evaluated safely in most cases during eval_const_expressions,
I am not too worried about a premature failure occurring with CAST ... DEFAULT."

[0]: https://postgr.es/m/CACJufxHw9Y3fvh+rZj4ukLo=v54Dpafzk7Xvee_wi9zFZ6pOfg@mail.gmail.com

----------------------------------------------------------------
SELECT CAST(1 as date DEFAULT NULL ON CONVERSION ERROR) as a;

transformTypeCast->coerce_to_target_type->coerce_to_target_type_extended
will make SafeTypeCastExpr->castexpr as NULL.
To deparse the above, we need to save the transformed TypeCast->arg.
Therefore, SafeTypeCastExpr->source is necessary.



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

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

От:
Peter Eisentraut <peter@eisentraut.org>
Дата:
I have committed patches v23 0001-0003 and 0005-0016.

In patch 0003, I did not change the NO_XML_SUPPORT() in xmlparse().  I
don't think we should make lack of compiled-in XML support a soft
error.

In patch 0012, I did not apply the changes involving
float_*flow_error() in dtof().  These should be considered together
with the error handling changes in patch 0018 (about which below).

Patch 0004 is probably ok, I just need to study a bit more, since it's
a bit different from the other ones.

In the comment for patch 0008 you write that supporting soft errors in
int4_cash() is not easy.  I suppose this is because of the external
function call to int8mul()?  Maybe that was necessary in ancient
times, but int8mul() is nowadays just a fmgr wrapper around
pg_mul_s64_overflow(), which you can call directly in int4_cash(), and
then it should be easy.

About patch 0017 (jsonb): Calling ereturn() in a function that returns
void, well, you make that work, but it seems a bit weird.  Maybe
cannotCastJsonbValue() could be changed to return a dummy datum, and
then you could just call it like

     return cannotCastJsonbValue(...);

Similarly, about patch 0018 (refactor float error): I think this is a
fragile API.  float_overflow_error() now will either ereport or just
errsave.  But nothing enforces that callers do the right thing.  For
example, in patch 0019, you change float_zero_divide_error(NULL) to
float_zero_divide_error(escontext), but don't insert a return, so the
code will continue to perform the division.  Similar to patch 0017,
maybe these functions should be changed to have a non-void return
value.  Or maybe make separate functions to be used in places where we
want soft error handling.

In the comment for patch 0021 you write that the function casting type
circle to type polygon cannot be error safe, because it's a SQL
language function.  I suggest to convert this to a C function and make 
the required changes there.

About the main feature patch: I'm not a fan of the CREATE CAST
... WITH SAFE FUNCTION syntax.  First, the CREATE CAST syntax is part
of the SQL standard.  It would be weird if we needed a nonstandard
syntax to make two standard features work together.  Second, we didn't
do this when we introduced error-safe type input functions.  There is
a note on the CREATE TYPE man page that use of ereturn() is
encouraged, and then we left it to extension authors to do the right
thing.  (And we should now put a similar note on the CREATE CAST man
page.)  And third, requiring this would require a lot of churn in all
affected extensions, requiring new extension SQL files and forcing
upgrades.  The changes you did in patch 0023 don't do this correctly, 
for example.

Tactical suggestion: Add an SQL-callable function, say,
pg_cast_conversion_succeeds(srcvalue, desttype) that checks whether
the cast would succeed.  This would be similar to the
pg_input_is_valid() function that we added to test the type input
functions.  (I did not call my proposal pg_cast_is_valid() because
that might indicate merely that a casting path exists.)  With that,
the higher-level functionality can be constructed by hand (CASE WHEN
pg_cast_conversion_succeeds(...) THEN CAST(...) ELSE 'default value'
END).  And then we can later work on building out the higher-level
functionality and make more cast functions error safe.



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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
In the comment for patch 0021 you write that the function casting type
circle to type polygon cannot be error safe, because it's a SQL
language function.  I suggest to convert this to a C function and make
the required changes there.


About the main feature patch: I'm not a fan of the CREATE CAST
... WITH SAFE FUNCTION syntax.  First, the CREATE CAST syntax is part
of the SQL standard.  It would be weird if we needed a nonstandard
syntax to make two standard features work together.  Second, we didn't
do this when we introduced error-safe type input functions.  There is
a note on the CREATE TYPE man page that use of ereturn() is
encouraged, and then we left it to extension authors to do the right
thing.  (And we should now put a similar note on the CREATE CAST man
page.)  And third, requiring this would require a lot of churn in all
affected extensions, requiring new extension SQL files and forcing
upgrades.  The changes you did in patch 0023 don't do this correctly,
for example.

This leaves us in a tricky situation if we can't tell ahead of time if a cast function really can handle soft errors. We could just allow any and all (CAST ... ON ERROR) calls even if the casting function can't actually return soft errors. That's unfortunate, but it might be the simplest and best way forward given that the alternative is to raise an error at planner time guaranteeing a query failure when the values presented might not have triggered the conversion errors.
 
Tactical suggestion: Add an SQL-callable function, say,
pg_cast_conversion_succeeds(srcvalue, desttype) that checks whether
the cast would succeed.  This would be similar to the
pg_input_is_valid() function that we added to test the type input
functions.  (I did not call my proposal pg_cast_is_valid() because
that might indicate merely that a casting path exists.)  With that,
the higher-level functionality can be constructed by hand (CASE WHEN
pg_cast_conversion_succeeds(...) THEN CAST(...) ELSE 'default value'
END).  And then we can later work on building out the higher-level
functionality and make more cast functions error safe.

You're describing the the "x IS CASTABLE AS y" syntax proposed in the same standards proposal document :) 

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Tue, Mar 24, 2026 at 9:13 PM Peter Eisentraut  wrote:
>
> In patch 0012, I did not apply the changes involving
> float_*flow_error() in dtof().  These should be considered together
> with the error handling changes in patch 0018 (about which below).
>
> Patch 0004 is probably ok, I just need to study a bit more, since it's
> a bit different from the other ones.
>
> In the comment for patch 0008 you write that supporting soft errors in
> int4_cash() is not easy.  I suppose this is because of the external
> function call to int8mul()?  Maybe that was necessary in ancient
> times, but int8mul() is nowadays just a fmgr wrapper around
> pg_mul_s64_overflow(), which you can call directly in int4_cash(), and
> then it should be easy.
>

cash_numeric is not easy to refactor safely,
To do this, we have to refactor (numeric_round, numeric_div), which
will require refactoring more functions.
So CoercionErrorSafe_Internal still checks whether the source
element/base type is MONEYOID.

> About patch 0017 (jsonb): Calling ereturn() in a function that returns
> void, well, you make that work, but it seems a bit weird.  Maybe
> cannotCastJsonbValue() could be changed to return a dummy datum, and
> then you could just call it like
>
>      return cannotCastJsonbValue(...);
>
ok.

> Similarly, about patch 0018 (refactor float error): I think this is a
> fragile API.  float_overflow_error() now will either ereport or just
> errsave.  But nothing enforces that callers do the right thing.  For
> example, in patch 0019, you change float_zero_divide_error(NULL) to
> float_zero_divide_error(escontext), but don't insert a return, so the
> code will continue to perform the division.  Similar to patch 0017,
> maybe these functions should be changed to have a non-void return
> value.  Or maybe make separate functions to be used in places where we
> want soft error handling.
>

Add argument to float_overflow_error, extern void
float_underflow_error, float_zero_divide_error
requires extensive refactoring.

So I have added
+extern float8 float_overflow_error_ext(struct Node *escontext);
+extern float8 float_underflow_error_ext(struct Node *escontext);
+extern float8 float_zero_divide_error_ext(struct Node *escontext);

> In the comment for patch 0021 you write that the function casting type
> circle to type polygon cannot be error safe, because it's a SQL
> language function.  I suggest to convert this to a C function and make
> the required changes there.
>
Please see 007.
Now with this entire v24 patchset, the only built-in cast function
that is not error safe is numeric_cash.

I'll think about CREATE CAST ... WITH SAFE FUNCTION syntax, later.
Right now, I am still using CoercionErrorSafe_Internal to check if CAST DEFAULT
can be applied to this combination of source type and target type.



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

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

От:
jian he <jian.universality@gmail.com>
Дата:
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/


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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
On Wed, Mar 25, 2026 at 9:14 AM jian he <jian.universality@gmail.com> wrote:
On Tue, Mar 24, 2026 at 9:13 PM Peter Eisentraut <peter@eisentraut.org> wrote:
>
> In patch 0012, I did not apply the changes involving
> float_*flow_error() in dtof().  These should be considered together
> with the error handling changes in patch 0018 (about which below).
>
> Patch 0004 is probably ok, I just need to study a bit more, since it's
> a bit different from the other ones.
>
> In the comment for patch 0008 you write that supporting soft errors in
> int4_cash() is not easy.  I suppose this is because of the external
> function call to int8mul()?  Maybe that was necessary in ancient
> times, but int8mul() is nowadays just a fmgr wrapper around
> pg_mul_s64_overflow(), which you can call directly in int4_cash(), and
> then it should be easy.
>

cash_numeric is not easy to refactor safely,
To do this, we have to refactor (numeric_round, numeric_div), which
will require refactoring more functions.
So CoercionErrorSafe_Internal still checks whether the source
element/base type is MONEYOID.

What if we just...didn't? The MONEY has been deprecated since 7.4. If we simply didn't implement this, and someone attempted to use this cast with default, what bad would happen?

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Thu, Mar 26, 2026 at 4:59 PM jian he  wrote:
>
> 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
>

In ATExecAddColumn, we have:

exprState = ExecPrepareExprWithContext(defval, estate, (Node *) &escontext);

The entire defval expression tree (including all the potential FuncExpr node
subexpression) must be marked as error-safe (all the
FuncExpr->errorsafe must be set to true).
If they aren't, ExecPrepareExprWithContext won't work.
In that scarenio, we need a walker function to set FuncExpr->errorsafe
to true for the above defval, overall feels very ugly.

Therefore, the previous approach (v24) of simply adding an errorsafe boolean to
FuncExpr will not work.
IMHO, it is not feasible to mark only part of an expression tree as error-safe.
Because of this, we should try to make queryA, queryB, queryC return NULL.

However, some inconsistency remains, for example:
SELECT CAST (CAST('a' AS int) AS text DEFAULT NULL ON CONVERSION
ERROR) FROM tcast1;  -- error
SELECT CAST (CAST('a'::text AS int) AS text DEFAULT NULL ON CONVERSION
ERROR) FROM tcast1; -- ok

V24: There is a segfault because of eval_const_expressions_mutator,
T_ArrayCoerceExpr handling,
You can invoke it via:
select cast (cast('{a}'::text[] as int[]) as text[] default null on
conversion error) from t2;

In V24, there were no nested type cast regress tests, now I have added some.

I removed the errorsafe boolean from FuncExpr. As mentioned previously, it is
difficult to make ExecInitExprRec compile expression partically eror safe.

refactoring on transformArrayExpr,  transformTypeCast, ExecInitSafeTypeCastExpr.



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

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

От:
Peter Eisentraut <peter@eisentraut.org>
Дата:
 From the v25 I have committed everything except 0001 and 0009.  I will 
continue reviewing the rest.



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

От:
Amul Sul <sulamul@gmail.com>
Дата:
On Mon, Mar 30, 2026 at 4:57 PM Peter Eisentraut  wrote:
>
>  From the v25 I have committed everything except 0001 and 0009.  I will
> continue reviewing the rest.
>

I’ve had a glance over the remaining patches; here are a few comments:

V25-0001:

-       if (relation->schemaname)
+       if (escontext == NULL)
            ereport(elevel,
-                   (errcode(ERRCODE_UNDEFINED_TABLE),
-                    errmsg("relation \"%s.%s\" does not exist",
-                           relation->schemaname, relation->relname)));
+                   errcode(ERRCODE_LOCK_NOT_AVAILABLE),
+                   relation->schemaname ?
+                   errmsg("relation \"%s.%s\" does not exist",
+                          relation->schemaname, relation->relname) :
+                   errmsg("relation \"%s\" does not exist",
+                          relation->relname));
        else
-           ereport(elevel,
-                   (errcode(ERRCODE_UNDEFINED_TABLE),
-                    errmsg("relation \"%s\" does not exist",
-                           relation->relname)));
+           ereturn(escontext, InvalidOid,
+                   errcode(ERRCODE_LOCK_NOT_AVAILABLE),
+                   relation->schemaname ?
+                   errmsg("relation \"%s.%s\" does not exist",
+                          relation->schemaname, relation->relname) :
+                   errmsg("relation \"%s\" does not exist",
+                          relation->relname));
    }

The error code changed here -- was this intentional?
--

v25-0009 :

+SELECT CAST('abc'::bpchar AS citext DEFAULT NULL ON CONVERSION ERROR); -- error
+ERROR:  cannot cast type character to citext when DEFAULT expression
is specified in CAST ... ON CONVERSION ERROR
+LINE 1: SELECT CAST('abc'::bpchar AS citext DEFAULT NULL ON CONVERSI...
+                    ^
+HINT:  Safe type cast for user-defined types are not yet supported.


"Should the HINT be this DETAIL? I believe a hint should provide
guidance for the user to handle the error, but here the user cannot do
anything with the given information.
--

 /* Generic macro for applying evaluate_expr */
-#define ece_evaluate_expr(node) \
+#define ece_evaluate_expr(node, escontext) \
    ((Node *) evaluate_expr((Expr *) (node), \
                            exprType((Node *) (node)), \
                            exprTypmod((Node *) (node)), \
-                           exprCollation((Node *) (node))))
+                           exprCollation((Node *) (node)), \
+                           escontext))


I think we can simply cast escontext to Node * here, instead of
having the caller do it.

Regards,
Amul


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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Mon, Mar 30, 2026 at 9:10 PM Amul Sul  wrote:
>
> I’ve had a glance over the remaining patches; here are a few comments:
>
> V25-0001:
>
> -       if (relation->schemaname)
> +       if (escontext == NULL)
>             ereport(elevel,
> -                   (errcode(ERRCODE_UNDEFINED_TABLE),
> -                    errmsg("relation \"%s.%s\" does not exist",
> -                           relation->schemaname, relation->relname)));
> +                   errcode(ERRCODE_LOCK_NOT_AVAILABLE),
> +                   relation->schemaname ?
> +                   errmsg("relation \"%s.%s\" does not exist",
> +                          relation->schemaname, relation->relname) :
> +                   errmsg("relation \"%s\" does not exist",
> +                          relation->relname));
>         else
> -           ereport(elevel,
> -                   (errcode(ERRCODE_UNDEFINED_TABLE),
> -                    errmsg("relation \"%s\" does not exist",
> -                           relation->relname)));
> +           ereturn(escontext, InvalidOid,
> +                   errcode(ERRCODE_LOCK_NOT_AVAILABLE),
> +                   relation->schemaname ?
> +                   errmsg("relation \"%s.%s\" does not exist",
> +                          relation->schemaname, relation->relname) :
> +                   errmsg("relation \"%s\" does not exist",
> +                          relation->relname));
>     }
>
> The error code changed here -- was this intentional?

it's a copy-paste error.

> --
>
> v25-0009 :
>
> +SELECT CAST('abc'::bpchar AS citext DEFAULT NULL ON CONVERSION ERROR); -- error
> +ERROR:  cannot cast type character to citext when DEFAULT expression
> is specified in CAST ... ON CONVERSION ERROR
> +LINE 1: SELECT CAST('abc'::bpchar AS citext DEFAULT NULL ON CONVERSI...
> +                    ^
> +HINT:  Safe type cast for user-defined types are not yet supported.
>
>
> "Should the HINT be this DETAIL? I believe a hint should provide
> guidance for the user to handle the error, but here the user cannot do
> anything with the given information.
> --
>
ok.

>  /* Generic macro for applying evaluate_expr */
> -#define ece_evaluate_expr(node) \
> +#define ece_evaluate_expr(node, escontext) \
>     ((Node *) evaluate_expr((Expr *) (node), \
>                             exprType((Node *) (node)), \
>                             exprTypmod((Node *) (node)), \
> -                           exprCollation((Node *) (node))))
> +                           exprCollation((Node *) (node)), \
> +                           escontext))
>
>
> I think we can simply cast escontext to Node * here, instead of
> having the caller do it.
>
ok.

I found a segmentation fault case in v25, it can be produced by:

SELECT CAST(('{' || sum(1 + 2) || '}')::int[] AS int[] DEFAULT NULL ON
CONVERSION ERROR) FROM (VALUES (1), (2)) sub;

We need set SafeTypeCastExpr->source to NULL. We can do this, because
SafeTypeCastExpr->castexpr sure contain all the
information of SafeTypeCastExpr->source.
If we don't nullify it, preprocess_aggref ends up processing both fields, then
parts of the Aggref node being initialized twice, which can ultimately
lead to a segfault.



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

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
hi.

src4=# explain (verbose, costs off) SELECT CAST('a' AS int DEFAULT 2
ON CONVERSION ERROR);
                        QUERY PLAN
-----------------------------------------------------------
 Result
   Output: CAST( AS integer DEFAULT 2 ON CONVERSION ERROR)
 Query Identifier: 2101562107364949876
(3 rows)

The above v26 output is not good, the attached file fixes this issue.
I also polished the comments and more regression tests.

The main big change compare to v26 is in preprocess_aggrefs_walker.
--- a/src/backend/optimizer/prep/prepagg.c
+++ b/src/backend/optimizer/prep/prepagg.c
@@ -358,6 +358,17 @@ preprocess_aggrefs_walker(Node *node, PlannerInfo *root)
          */
         return false;
     }
+    if (IsA(node, SafeTypeCastExpr))
+    {
+        SafeTypeCastExpr *castexpr = (SafeTypeCastExpr *) node;
+
+        /*
+         * "source" may also contain an Aggref node, but since it is kept only
+         * for deparsing purposes, we must not recurse into it when processing
+         * aggregate nodes here.
+         */
+        return expression_tree_walker((Node *) castexpr->castexpr,
preprocess_aggrefs_walker, root);
+    }
     Assert(!IsA(node, SubLink));
     return expression_tree_walker(node, preprocess_aggrefs_walker, root);
 }



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

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.
I've incorporated the changes you sent me off-list.
The attached v1 no-cfbot is your proposed change.
I also did some minor comments adjustments.

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:


On Tue, Mar 31, 2026 at 10:48 AM jian he <jian.universality@gmail.com> wrote:
Hi.
I've incorporated the changes you sent me off-list.
The attached v1 no-cfbot is your proposed change.
I also did some minor comments adjustments.

The remaining patches continue to work for me. I hope we can get all of this into 19, but if we can't I think it would be ok to limit src/dest type combinations to those that can be handled by CoerceViaIO, at least for 19. I think the vast majority of the usage of this function will be mass ETLs where data is first loaded into a table of all text.
 

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

От:
jian he <jian.universality@gmail.com>
Дата:
One more issue I found:
https://git.postgresql.org/cgit/postgresql.git/commit/?id=74c96699be3f53c058c8794c07952221b9625b4f
SELECT JSON_VALUE(jsonb '1234', '$' RETURNING char(2)  DEFAULT '011' ON ERROR);
ERROR:  value too long for type character(2)

Similarly, we can
SELECT CAST(text '1234' as char(2) DEFAULT '111111' ON conversion ERROR);
ERROR:  value too long for type character(2)

Composite types respect typmod, for example:
CREATE TYPE comp AS (a char(3), b int);
SELECT CAST('(14,42)' AS comp DEFAULT '(1234,2)' ON CONVERSION ERROR); -- error

The regression tests are too large; we can order them by the cast
source type's pg_type.type category,
so we won't miss any tests.

What do you think?


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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
On Wed, Apr 1, 2026 at 3:23 AM jian he <jian.universality@gmail.com> wrote:
One more issue I found:
https://git.postgresql.org/cgit/postgresql.git/commit/?id=74c96699be3f53c058c8794c07952221b9625b4f
SELECT JSON_VALUE(jsonb '1234', '$' RETURNING char(2)  DEFAULT '011' ON ERROR);
ERROR:  value too long for type character(2)

Similarly, we can
SELECT CAST(text '1234' as char(2) DEFAULT '111111' ON conversion ERROR);
ERROR:  value too long for type character(2)

Both of these are doomed when we hit the default, so I don't see why we should make any accommodation for them.

 
Composite types respect typmod, for example:
CREATE TYPE comp AS (a char(3), b int);
SELECT CAST('(14,42)' AS comp DEFAULT '(1234,2)' ON CONVERSION ERROR); -- error

This one is trickier, but I'd be willing to reject composite inputs in v19 and solve it in v20.
 
The regression tests are too large; we can order them by the cast
source type's pg_type.type category,
so we won't miss any tests.

We can always remove redundant tests later.

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

От:
Vik Fearing <vik@postgresfriends.org>
Дата:
Вложения:


On 31/03/2026 22:02, Corey Huinker wrote:


On Tue, Mar 31, 2026 at 10:48 AM jian he <jian.universality@gmail.com> wrote:
Hi.
I've incorporated the changes you sent me off-list.
The attached v1 no-cfbot is your proposed change.
I also did some minor comments adjustments.

The remaining patches continue to work for me. I hope we can get all of this into 19, but if we can't I think it would be ok to limit src/dest type combinations to those that can be handled by CoerceViaIO, at least for 19. I think the vast majority of the usage of this function will be mass ETLs where data is first loaded into a table of all text.


Did you see on Discord that I am submitting a bug fix for this paper? I originally took the syntax from json but it special-cases NULL and can't handle <empty specification>, so I want to remove `NULL ON CONVERSION ERROR` and switch the DEFAULT clause to <implicitly typed value specification>.


I am attaching it here in case you missed it.

-- 

Vik Fearing

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Fri, Apr 3, 2026 at 12:03 AM Vik Fearing  wrote:
>
> Did you see on Discord that I am submitting a bug fix for this paper? I originally took the syntax from json but it special-cases NULL and can't handle , so I want to remove `NULL ON CONVERSION ERROR` and switch the DEFAULT clause to .
>
> I am attaching it here in case you missed it.
> --
>
> Vik Fearing

The attached v29 removed `NULL ON CONVERSION ERROR`.
Other than that, everything is the same as v28.



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

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
The attached v29 removed `NULL ON CONVERSION ERROR`.
Other than that, everything is the same as v28.

Indeed it is, and everything still checks out.

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi,

In subquery_planner -> preprocess_expression ->
eval_const_expressions, we attempt
to evaluate certain constant expressions in an error-safe manner by introducing
an ErrorSaveContext in eval_const_expressions_context. However, this may
introduce consistency issues, since not all functions are error-safe.

Consider the following two queries:
SELECT CAST(65536 AS int2 DEFAULT NULL ON CONVERSION ERROR);
SELECT CAST(65536/0 AS int2 DEFAULT NULL ON CONVERSION ERROR);
ERROR:  division by zero

The first query returns NULL, while the second throws an error. Should we accept
this inconsistency, or make the first query error out too?
Similarly, should we reject uncastable CASTs, like `CAST(NULL::date AS int2)`?

More broadly, the patch involved significant effort (refactoring) in
parsing (transformTypeCast),
planning (eval_const_expressions) to ensure expressions do not fail.
These efforts cannot ensure that all operations are error-safe,
therefore there will be consistency issues.
----------------------------------------------------------------
[1] explains why SQL-language functions are inherently not error-safe.

This raises the question: how should we handle user-defined cast functions in
CAST(expr AS target_type DEFAULT defexpr ON CONVERSION ERROR)?

There are three options:
Option 1: Disallow them entirely.
Reject any cast expression backed by a user-defined function at parse time.

Option 2: Allow them with documented caveats.
Permit user-defined cast functions, but explicitly document the limitations:
- SQL-language functions are inherently incapable of error-safe execution.
- C-language functions must ensure that all their subroutines are also
error-safe.
- It is the user's responsibility to ensure the cast function is error-safe; if
it is not, errors will propagate as normal rather than being caught by the
DEFAULT clause.

Option 2 means that CAST(expr AS target_type DEFAULT defexpr ON
CONVERSION ERROR) does not check if the underlying cast function
actually supports error-safe operations.

Option 3: Disallow SQL-language functions, but allow C-language and
Internal-language functions.
Also document that you must ensure the C function is error-safe if you
want it to catch the error.


Currently, we are using Option 1.
Anyway, I rebased the patch and added comments in a few places that I
realized were necessary in hindsight.

[1]: https://postgr.es/m/CACJufxHM2e3DQmbRdDZvWyG3ZCLyOg6XFifvOz_TGy1tGw7NHw@mail.gmail.com



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

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
On Mon, Jun 22, 2026 at 10:51 PM jian he <jian.universality@gmail.com> wrote:
Hi,

In subquery_planner -> preprocess_expression ->
eval_const_expressions, we attempt
to evaluate certain constant expressions in an error-safe manner by introducing
an ErrorSaveContext in eval_const_expressions_context. However, this may
introduce consistency issues, since not all functions are error-safe.

Consider the following two queries:
SELECT CAST(65536 AS int2 DEFAULT NULL ON CONVERSION ERROR);
SELECT CAST(65536/0 AS int2 DEFAULT NULL ON CONVERSION ERROR);
ERROR:  division by zero

The first query returns NULL, while the second throws an error. Should we accept
this inconsistency, or make the first query error out too?

It's not an inconsistency. The expression 65536/0 is evaluated and raises an error before the cast is executed.

Similarly, should we reject uncastable CASTs, like `CAST(NULL::date AS int2)`?

Right now that fails. I think it still should fail because there was no possible conversion to do, so the conversion didn't fail.

I could be convinced that in the case of `SELECT CAST($1::date AS int2 DEFAULT 3 ON CONVERSION ERROR)` can recognize that there is no conversion path from "date" to "int2", and it should be optimized to just 3::int2 the same way that `(CASE WHEN FALSE THEN 5 ELSE 3 END)::int2` would be.
 
More broadly, the patch involved significant effort (refactoring) in
parsing (transformTypeCast),
planning (eval_const_expressions) to ensure expressions do not fail.
These efforts cannot ensure that all operations are error-safe,
therefore there will be consistency issues.

We only have to keep the _conversion_ error-safe. That conversion could be a no-op, could be an CoerceViaIO, or it could be a custom function. If the method is CoerceViaIO and the destination type does not have a safe input function, then the command should fail before execution. Likewise, if there is a custom function from type1->type2 defined, and it isn't error-safe, then the command should similarly fail. The user can then modify the SQL to remove the DEFAULT...ON CONVERSION ERROR clause from the CAST that can't be made safe and re-run.
 
This raises the question: how should we handle user-defined cast functions in
CAST(expr AS target_type DEFAULT defexpr ON CONVERSION ERROR)?

There are three options:
Option 1: Disallow them entirely.
Reject any cast expression backed by a user-defined function at parse time.

I strongly dislike this option.

Option 2: Allow them with documented caveats.
Permit user-defined cast functions, but explicitly document the limitations:
- SQL-language functions are inherently incapable of error-safe execution.
- C-language functions must ensure that all their subroutines are also
error-safe.
- It is the user's responsibility to ensure the cast function is error-safe; if
it is not, errors will propagate as normal rather than being caught by the
DEFAULT clause.

Option 2 means that CAST(expr AS target_type DEFAULT defexpr ON
CONVERSION ERROR) does not check if the underlying cast function
actually supports error-safe operations.

I think this would be a significant POLA violation.
 
Option 3: Disallow SQL-language functions, but allow C-language and
Internal-language functions.
Also document that you must ensure the C function is error-safe if you
want it to catch the error.

This is why I argued for adding a "SAFE" keyword on CREATE CAST and a corresponding safe flag in pg_cast or a value of 's' for castmethod to indicate a function that is declared error-safe back in [1]. There was pushback on the syntax itself, but I think the concept is still the best way forward.

I don't think we disallow SQL functions for being SQL functions, but also there's presently no way for a SQL function to be safe. So the effect is the same.




Currently, we are using Option 1.
Anyway, I rebased the patch and added comments in a few places that I
realized were necessary in hindsight.

[1]: https://postgr.es/m/CACJufxHM2e3DQmbRdDZvWyG3ZCLyOg6XFifvOz_TGy1tGw7NHw@mail.gmail.com


I'll give this new patch a look, but resolving Option 1/2/3 seems most important.

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

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

While reviewing the error-safe text->regclass cast -- the first patch,
"error safe for casting text to other types per pg_cast" -- I built it and
ran a few cases under ON CONVERSION ERROR to see how the cast behaves.
Three behaviors stand out, and together they surface one inconsistency and
a policy question I'd like to raise.  The concrete site and fix below are in
that patch, independently of the main DEFAULT-syntax patch; ON CONVERSION
ERROR is only the lens that makes the cast's soft/hard behavior observable.
(Examples use ::text so they exercise the text_regclass cast function rather
than the regclass input function.)

* Observed behaviors (built from this patch, tested)

(i) A value-conversion error is caught and replaced by the DEFAULT, as
intended:

    SELECT CAST('x' AS integer DEFAULT 0 ON CONVERSION ERROR);   -- 0

(ii) The DEFAULT expression itself is evaluated without the soft-error net
(expr2 being the "non-error-safe typecast", as described early in this
thread).  For a value type that never matters, but for a binding type like
regclass a DEFAULT that names a missing object hard-aborts:

    SELECT CAST('public.nosuchA'::text AS regclass
                DEFAULT 'public.nosuchB'::text ON CONVERSION ERROR);
    -- ERROR: relation "public.nosuchb" does not exist   (DEFAULT NULL is fine)

This is by design; I note it only because a binding-type DEFAULT can itself
fail, unlike a value-type DEFAULT.

(iii) A "not found" lookup failure is mostly treated as soft.  A missing
relation folds into the DEFAULT, and the regclass input function already
reports a missing schema softly (as "relation does not exist", 42P01):

    SELECT CAST('public.nosuchtable'::text AS regclass
                DEFAULT 999 ON CONVERSION ERROR);                 -- 999
    SELECT message, sql_error_code
      FROM pg_input_error_info('nosuch_schema.foo','regclass');
    -- relation "nosuch_schema.foo" does not exist | 42P01

I couldn't find a point in the thread where it was decided whether a
lookup/not-found failure should be caught by ON CONVERSION ERROR at all --
the reg* casts seem to have been swept into the error-safe batch alongside
value casts, without distinguishing a binding failure from a value
conversion.  The de-facto behavior, though, is soft.

* The inconsistency

Against that mostly-soft behavior, one not-found is hard: a missing SCHEMA
in a schema-qualified name.  text_regclass() calls

    RangeVarGetRelidExtendedSafe(rv, NoLock, 0, NULL, NULL, fcinfo->context)

with flags=0 (so missing_ok=false), and the schema-resolution step
LookupExplicitNamespace() -> get_namespace_oid() is not threaded with
escontext, so it raises ERRCODE_UNDEFINED_SCHEMA as a hard ereport:

    SELECT CAST('nosuch_schema.foo'::text AS regclass
                DEFAULT NULL ON CONVERSION ERROR);
    -- ERROR: schema "nosuch_schema" does not exist   (get_namespace_oid, namespace.c)

So a missing schema hard-aborts, while the parallel missing relation one
branch below is soft (and regclassin softens the same missing-schema input).

* The question

This reads less like a localized slip and more like a policy decision that
was never made: under ON CONVERSION ERROR, should a "not found"
(lookup/binding) failure be hard or soft?

- If soft (consistent with the current majority behavior and with
  regclassin), then LookupExplicitNamespace()/get_namespace_oid() need
  escontext threaded on the not-found path -- equivalently text_regclass()
  could pass RVR_MISSING_OK as regclassin does -- while the USAGE-permission
  check stays hard, which it correctly does today:

      -- as a role lacking USAGE on schema s1:
      SELECT CAST('s1.t'::text AS regclass DEFAULT NULL ON CONVERSION ERROR);
      -- ERROR: permission denied for schema s1    (stays hard, not folded)

- If hard, then the inconsistency runs the other way: the relation-not-found
  softening and regclassin's behavior would need revisiting, and whether
  catalog-resolving reg* casts belong in ON CONVERSION ERROR at all deserves
  a second look.

Either way, the current schema-vs-relation split is inconsistent.  I'd
rather see the policy settled than just patch the one site.

Best regards,
Henson

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

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

Continuing to check what ON CONVERSION ERROR should actually cover.  By
definition the clause is about a conversion error, and a reference
implementation (Oracle) likewise propagates operand errors and catches
only the conversion.  By that measure three behaviors are clear defects;
two others look like design/policy choices that have not been made.
(This is separate from the not-found soft/hard asymmetry I raised
earlier.)

All examples were built and run on the current WIP branch.


Clear defects
=============

A. An error in evaluating the operand is folded into the DEFAULT, and
   inconsistently so.

A numeric->text conversion cannot fail, yet an overflow while computing
the operand is swallowed and replaced by the DEFAULT:

    SELECT CAST(1e100000::numeric * 1e100000::numeric AS text
                DEFAULT 'oops' ON CONVERSION ERROR);
    -- oops

But a different operand error is not swallowed:

    SELECT CAST(1/0 AS text DEFAULT 'oops' ON CONVERSION ERROR);
    -- ERROR: division by zero

The only difference is that the numeric multiplication's overflow is
swallowed while the integer division's error is not.  Which operand
errors fold into the DEFAULT varies by operation, with no stated rule.

Oracle catches only the conversion; an error in the operand propagates:

    CAST(1e70*1e70 AS NUMBER DEFAULT -1 ON CONVERSION ERROR)  -> ORA-01426 (overflow)
    CAST(1/0       AS NUMBER DEFAULT -1 ON CONVERSION ERROR)  -> ORA-01476 (div by zero)
    CAST(CAST(99999 AS NUMBER(3)) AS NUMBER DEFAULT -1 ON CONVERSION ERROR)
                                                             -> ORA-01438 (inner cast)

whereas a genuine value-conversion failure is caught, as intended:

    CAST('abc' AS NUMBER DEFAULT -1 ON CONVERSION ERROR)     -> -1


B. The same operand swallowing diverges between plan time and run time,
   depending on constant folding.

It is the same operand swallowing as (A), but here the result of one
and the same valid query depends on whether the operand folds:

    -- operand is constant, folded at plan time, so the overflow propagates:
    SELECT CAST(CAST(1 AS int DEFAULT 0 ON CONVERSION ERROR) + 70000::int2::int4
                AS int DEFAULT -1 ON CONVERSION ERROR);
    -- ERROR: smallint out of range

    -- same expression with the operand fed from a column, not folded:
    CREATE TABLE nums(x int);  INSERT INTO nums VALUES (70000);
    SELECT CAST(CAST(1 AS int DEFAULT 0 ON CONVERSION ERROR) + x::int2::int4
                AS int DEFAULT -1 ON CONVERSION ERROR) FROM nums;
    -- -1   (swallowed)

Oracle has no such fold-dependent split, because an operand error
propagates either way.


C. A nested DEFAULT can turn a hard error into a silent wrong answer.

    CREATE TABLE t(a text, b text);
    INSERT INTO t VALUES ('foo', 'bar');

    SELECT CAST(CAST(a AS int DEFAULT b::int ON CONVERSION ERROR)
                AS int2 DEFAULT -1 ON CONVERSION ERROR) FROM t;
    -- -1

The inner DEFAULT b::int (b = 'bar') fails at run time.  At top level
the same failing DEFAULT raises:

    SELECT CAST('x' AS int DEFAULT ('zzz')::int ON CONVERSION ERROR);
    -- ERROR: invalid input syntax for type integer: "zzz"

Nested, it is instead taken for the outer cast's own conversion failure
and the outer DEFAULT (-1) is returned silently.  A hard error becoming
a silent value is the concern here, independently of the DEFAULT policy
in (D).


Look like policy decisions
==========================

D. May the DEFAULT be an arbitrary expression, or only a literal/bind?

We currently allow an arbitrary expression as the DEFAULT:

    SELECT CAST('x' AS int DEFAULT (length('abc') * 2) ON CONVERSION ERROR);
    -- 6

Oracle restricts the DEFAULT to a literal or bind variable:

    CAST(x AS NUMBER DEFAULT TO_NUMBER('bad') ON CONVERSION ERROR)
        -- ORA-43907: Argument in DEFAULT ... ON CONVERSION ERROR clause
        --            must be a literal or bind variable.

which structurally prevents (C).  This expression DEFAULT can itself
fail; if it is intended to stay, its evaluation scope needs to be
pinned down so the nested case in (C) cannot arise.


E. User-defined types reached via I/O coercion: reject, or support?

The documentation says only built-in casts are supported, and a
user-defined WITH FUNCTION cast is rejected at parse time:

    CREATE FUNCTION int_to_point(int) RETURNS point
       AS 'SELECT point($1, $1)' LANGUAGE sql IMMUTABLE;
    CREATE CAST (int AS point) WITH FUNCTION int_to_point(int);
    SELECT CAST(1 AS point DEFAULT NULL ON CONVERSION ERROR);
    -- ERROR: cannot cast type integer to point with DEFAULT expression
    --        in CAST ... ON CONVERSION ERROR
    -- DETAIL: Safe type casts for user-defined types are not yet supported.

But a user-defined type reached through I/O coercion (a WITH INOUT
cast, or a plain text->type explicit cast) is accepted, and a
hard-erroring input function then leaks straight through
ON CONVERSION ERROR instead of being rejected or folding into the
DEFAULT.  widget_in/widget_out below are the deliberately hard-erroring
I/O functions from the regression suite (src/test/regress/regress.c),
with :regresslib set to the regression shared library as in
test_setup.sql:

    CREATE TYPE hardtype;
    CREATE FUNCTION hardtype_in(cstring)  RETURNS hardtype
       AS :'regresslib', 'widget_in'  LANGUAGE C STRICT IMMUTABLE;
    CREATE FUNCTION hardtype_out(hardtype) RETURNS cstring
       AS :'regresslib', 'widget_out' LANGUAGE C STRICT IMMUTABLE;
    CREATE TYPE hardtype (internallength = 24, input = hardtype_in,
       output = hardtype_out, alignment = double);
    CREATE CAST (text AS hardtype) WITH INOUT;

    SELECT CAST('bad'::text AS hardtype DEFAULT NULL ON CONVERSION ERROR);
    -- ERROR: invalid input syntax for type widget: "bad"  (leaked, not DEFAULT/NULL;
    --   the error says "widget" because the reused widget_in reports its own name)

So the "not supported" rule is enforced for one path but not the other.


(A), (B), and (C) are clear defects.  In all three, an error that is
not the conversion itself -- raised while evaluating the operand or an
inner cast -- is caught by ON CONVERSION ERROR, so a valid query either
returns a silently wrong value or its result depends on constant
folding.  That contradicts the clause's definition, that ON CONVERSION
ERROR applies to the conversion only.  (D) and (E), by contrast, are
genuine design choices that have not been made.

Best regards,
Henson

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

От:
jian he <jian.universality@gmail.com>
Дата:
On Thu, Jul 2, 2026 at 10:06 PM Henson Choi  wrote:
>>

>>
>> C. A nested DEFAULT can turn a hard error into a silent wrong answer.
>>
>>     CREATE TABLE t(a text, b text);
>>     INSERT INTO t VALUES ('foo', 'bar');
>>
>>     SELECT CAST(CAST(a AS int DEFAULT b::int ON CONVERSION ERROR)
>>                 AS int2 DEFAULT -1 ON CONVERSION ERROR) FROM t;
>>     -- -1
>>
>> The inner DEFAULT b::int (b = 'bar') fails at run time.  At top level
>> the same failing DEFAULT raises:
>>
>>     SELECT CAST('x' AS int DEFAULT ('zzz')::int ON CONVERSION ERROR);
>>     -- ERROR: invalid input syntax for type integer: "zzz"
>>
>> Nested, it is instead taken for the outer cast's own conversion failure
>> and the outer DEFAULT (-1) is returned silently.  A hard error becoming
>> a silent value is the concern here, independently of the DEFAULT policy
>> in (D).
>>
>>

For C:
I tried that in
https://www.postgresql.org/message-id/CACJufxH_1EtEBMb0JvxaM3Gmnt33HYrS37m5eYjJ_OfBkMVFJg%40mail.gmail.com

It seems infeasible to evaluate some subexpressions in an error-safe manner
while others are not. Therefore, if the top-level expression is error-safe, the
entire expression will compile to support error-safe evaluation for its
subexpressions as well.

For D, this is intended i suppose, see
https://www.postgresql.org/message-id/762ae707-7fdc-43d8-a77a-3a10d12ce21d%40postgresfriends.org


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

От:
jian he <jian.universality@gmail.com>
Дата:
On Thu, Jul 2, 2026 at 10:06 PM Henson Choi  wrote:
>>
>>
>> E. User-defined types reached via I/O coercion: reject, or support?
>>
>> The documentation says only built-in casts are supported, and a
>> user-defined WITH FUNCTION cast is rejected at parse time:
>>
>>     CREATE FUNCTION int_to_point(int) RETURNS point
>>        AS 'SELECT point($1, $1)' LANGUAGE sql IMMUTABLE;
>>     CREATE CAST (int AS point) WITH FUNCTION int_to_point(int);
>>     SELECT CAST(1 AS point DEFAULT NULL ON CONVERSION ERROR);
>>     -- ERROR: cannot cast type integer to point with DEFAULT expression
>>     --        in CAST ... ON CONVERSION ERROR
>>     -- DETAIL: Safe type casts for user-defined types are not yet supported.
>>
>> But a user-defined type reached through I/O coercion (a WITH INOUT
>> cast, or a plain text->type explicit cast) is accepted, and a
>> hard-erroring input function then leaks straight through
>> ON CONVERSION ERROR instead of being rejected or folding into the
>> DEFAULT.  widget_in/widget_out below are the deliberately hard-erroring
>> I/O functions from the regression suite (src/test/regress/regress.c),
>> with :regresslib set to the regression shared library as in
>> test_setup.sql:
>>
>>     CREATE TYPE hardtype;
>>     CREATE FUNCTION hardtype_in(cstring)  RETURNS hardtype
>>        AS :'regresslib', 'widget_in'  LANGUAGE C STRICT IMMUTABLE;
>>     CREATE FUNCTION hardtype_out(hardtype) RETURNS cstring
>>        AS :'regresslib', 'widget_out' LANGUAGE C STRICT IMMUTABLE;
>>     CREATE TYPE hardtype (internallength = 24, input = hardtype_in,
>>        output = hardtype_out, alignment = double);
>>     CREATE CAST (text AS hardtype) WITH INOUT;
>>
>>     SELECT CAST('bad'::text AS hardtype DEFAULT NULL ON CONVERSION ERROR);
>>     -- ERROR: invalid input syntax for type widget: "bad"  (leaked, not DEFAULT/NULL;
>>     --   the error says "widget" because the reused widget_in reports its own name)
>>
>> So the "not supported" rule is enforced for one path but not the other.
>>

But src/test/regress/regress.c have below comments:
    /*
     * Note: DON'T convert this error to "soft" style (errsave/ereturn).  We
     * want this data type to stay permanently in the hard-error world so that
     * it can be used for testing that such cases still work reasonably.
     */

That means
SELECT CAST('bad'::text AS hardtype DEFAULT NULL ON CONVERSION ERROR);
is bound to error out.

SELECT pg_input_is_valid('bad', 'widget');
will also error out.

User-defined types coerced through I/O functions are assumed to be error-safe.
If the input function is implemented to support error-safe execution, the
coercion can also be evaluated in an error-safe manner; see EEOP_IOCOERCE_SAFE.
That's our current status, so I don't think we need to do anything special.

----------------------------------------------------------------------------------------------------
Since not all functions support error-safe execution, scenario A is
unavoidable. Scenarios C and D are explained in [1], while scenario B
mentioned in [2] is a bug.

[1] https://www.postgresql.org/message-id/CACJufxEawrK%2BFhFzyWMPKZ_r11jEqbzq4soUM2ZRBNSintQ%2BAQ%40mail.gmail.com
[2] https://www.postgresql.org/message-id/CAAAe_zDMjcFgZJoS%3DzQn5VdetZ5qQcoHiZmLriAdrYLGPTsPZg%40mail.gmail.com


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


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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.

Summary of where we are for:
CAST(expr AS type DEFAULT defexpr ON CONVERSION ERROR)

A. The default expression (defexpr) is coerced to the target type with no
soft-error handling, if defexpr itself fails to convert, that's a hard error.

B. Not all functions are error-safe, CAST ... DEFAULT can never be made
bulletproof in general; in some cases we simply won't be able to fall back to
evaluating the default expression. This inconsistency is not solvable, i think.

C. At parsing stage, if the source expression (expr) is a Const of type UNKNOWN,
we try to use InputFunctionCallSafe to perform the conversion in an error-safe
manner, as mentioned in point A, we don't do this for the default expression.

D. At planning stage, eval_const_expressions tries to do constant
folding the transformed
cast expression in an error-safe manner, as mentioned before, not all function
is error safe, so this stage may encounter hard-error.
Example: SELECT CAST((1/0.0) AS numeric DEFAULT NULL ON CONVERSION ERROR).

E. We need a way to distinguish whether a given function is error-safe, since we
can't simply assume every function will be evaluated safely, that would a bad
user-experience.

F. A subexpression within the source expression may force error-safe evaluation
even where we'd rather not: we can't evaluate some subexpressions in an
error-safe manner while others aren't, once part of the expression requires it,
the rest ends up dragged into the same mode.
Example:
CREATE TABLE t AS SELECT 'bar' as b;
SELECT CAST(CAST('b' AS int DEFAULT b ON CONVERSION ERROR) AS int2
                          DEFAULT -1 ON CONVERSION ERROR)
FROM t;
SELECT CAST('b' AS int DEFAULT b ON CONVERSION ERROR) from t;

-------------------------------------------------------------------------------------------------------
To address point E: distinguishing whether an expression is error-safe-capable.

We first tried using CREATE CAST WITH [SAFE] FUNCTION in [1]. Then in
[2], Henson Choi pointed
out that being error safe or not is a property of the function itself,
not related to catalog pg_cast, and indeed it is.
Also storing this property on pg_proc rather than pg_cast is future-proof;
Since we eventually want to fully support
CAST(expr AS type FORMAT 'fmt' DEFAULT defexpr ON CONVERSION ERROR).

Looking at the CREATE FUNCTION synopsis, we already have

PARALLEL { UNSAFE | RESTRICTED | SAFE }

Adding a bare SAFE keyword (e.g. CREATE FUNCTION ... SAFE) would read
oddly alongside that.
That led me to

ERROR { SAFE | UNSAFE }

backed by a new pg_proc column, proerrorsafe, which is default to false; every
build-in pg_cast.castfunc function is marked proerrorsafe => true.

This works because error-safe evaluation either via CoerceViaIO or a
FuncExpr. (ArrayCoerce's element expression is likewise one of those two).

For CoerceViaIO we have EEOP_IOCOERCE_SAFE, which currently just assumes
unconditionally that the input function has been refactored to be error-safe.
pg_proc.proerrorsafe tells us check whether a given function is
error-safe-capable, instead of unconditionally assuming it.
------------------------------------------------------------------------------------------------------------
Summary of the attachment:
1.v31-0001-error-safe-for-casting-text-to-other-types-per-pg_cast.patch
Same as before, but the bug menion in [3] is resolved.
2. v31-0002-introduce-pg_proc.proerrorsafe.patch
This is for distinguishing whether a function is error-safe capable.
3. v31-0003-CAST-expr-AS-newtype-DEFAULT-expr-ON-CONVERSION-ERROR.patch
Implement CAST(expr AS newtype DEFAULT expr ON CONVERSION  ERROR).
Using pg_proc.proerrorsafe flag in 0002. If a function's proerrrorsafe
is false, then it cannot participate in CAST DEFAULT.

[1] https://www.postgresql.org/message-id/CACJufxFEzD3mqc%2BMDpgzvdt%2B4Azbn2pF6TWW%3DdSCqSK7OHoL6A%40mail.gmail.com
[2] https://www.postgresql.org/message-id/CAAAe_zDuTTbDGy_OPrcw3DEHqcjMdrWoo3954v03r6HogGQ37w%40mail.gmail.com
[3] https://www.postgresql.org/message-id/CAAAe_zAi%3DPGO4j89w5Hu_Gu%2BnjKeWY9YeX0hp91qvWVMXt0igw%40mail.gmail.com


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

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Thu, Jul 2, 2026 at 10:06 PM Henson Choi  wrote:
>>
>> Look like policy decisions
>> ==========================
>>
>> D. May the DEFAULT be an arbitrary expression, or only a literal/bind?
>>
>> We currently allow an arbitrary expression as the DEFAULT:
>>
>>     SELECT CAST('x' AS int DEFAULT (length('abc') * 2) ON CONVERSION ERROR);
>>     -- 6
>>
>> Oracle restricts the DEFAULT to a literal or bind variable:
>>
>>     CAST(x AS NUMBER DEFAULT TO_NUMBER('bad') ON CONVERSION ERROR)
>>         -- ORA-43907: Argument in DEFAULT ... ON CONVERSION ERROR clause
>>         --            must be a literal or bind variable.
>>
>> which structurally prevents (C).  This expression DEFAULT can itself
>> fail; if it is intended to stay, its evaluation scope needs to be
>> pinned down so the nested case in (C) cannot arise.
>>

Quote from [1]
<<>>
An example of B) above would be: CAST('five' AS INTEGER DEFAULT 'six' ON
CONVERSION ERROR).  'six' is no more an integer than 'five' is, so that
would error out because the conversion error does not happen on the
operand but on the default clause. CAST('five' AS INTEGER DEFAULT 6 ON
CONVERSION ERROR) would work.
<<>>

As you can see, evaluation of the DEFAULT defexpr can error out, the
standard doesn't distinguish between a parse stage failure and an execution
stage failure. I've added a sentence noting that evaluation of the default
expression may fail.  If others feel more strongly that the default expression
should be reduced to a Const after eval_const_expressions, we can certainly
enforce that during eval_const_expressions.

-----------------------------------------------------------------
Please check the rebased v32. Minor changes made in v32:

Previously, the source expression could be an UNKNOWN Const, or an UNKNOWN Const
wrapped inside a nested CollateExpr node. I added logic to coerce both cases to
TEXTOID.

in v31:
CAST('2022-01-01' COLLATE "C" COLLATE "POSIX" AS DATE DEFAULT NULL ON
CONVERSION ERROR)
would deparse back to itself.
Now it deparses as:
CAST('2022-01-01'::text COLLATE "POSIX" AS DATE DEFAULT NULL ON
CONVERSION ERROR)

Renamed EXPR_KIND_CAST_DEFAULT to EXPR_KIND_TYPECAST_DEFAULT.

In gram.y, renamed makeTypeCastWithDefault to makeTypeCastOpt, since another
patch (https://commitfest.postgresql.org/patch/5957) will be adding another
field to the TypeCast struct, a more generic name like makeTypeCastOpt will be
more future-proof.

[1]: https://www.postgresql.org/message-id/762ae707-7fdc-43d8-a77a-3a10d12ce21d%40postgresfriends.org



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

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
Please check the rebased v32. Minor changes made in v32:

I'm cautiously optimistic about the 0002 patch. It adds the capability that we need from cast functions without imposing any load on the executor - fortunately context already dictates whether a function is called with an error context or not. It also guarantees that custom types are not presumed to be cast-safe until their author explicitly declares them so.

To that end, I think there will be considerable debate about how we describe and document this new attribute. Our choice of function names ending in -Safe and our keyword choice can give the reader the impression that the function cannot fail under any circumstances, and we need to be clear that what we mean is that the function is capable of generating soft errors of some sort, presumably related to the inputs to the function, but does not guarantee that all possible errors are caught and captured in the error context. So far, we've been comfortable calling such a situation "safe", but this exposes that shorthand to a larger audience and we should be proactive in dispelling the confusion before it starts.

The usage and testing of in 0003 seems adequate.

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
The attached v33 has nontrivial changes compared with v32.

previously v32 I did:
1. add coerce_to_target_type_extended _extended function seems not
future-proof enough.
--- a/src/include/parser/parse_coerce.h
+++ b/src/include/parser/parse_coerce.h
@@ -43,15 +43,29 @@ extern Node *coerce_to_target_type(ParseState *pstate,
    CoercionContext ccontext,
    CoercionForm cformat,
    int location);
+extern Node *coerce_to_target_type_extended(ParseState *pstate,
+ Node *expr,
+ Oid exprtype,
+ Oid targettype,
+ int32 targettypmod,
+ CoercionContext ccontext,
+ CoercionForm cformat,
+ int location,
+ Node *escontext);

To support CAST('error' AS integer DEFAULT 1 ON CONVERSION ERROR), the
conversion of an unknown literal to a Const, done inside coerce_to_target_type,
must be able to fail softly.  Passing an ErrorSaveContext pointer down through
those functions is ugly and not future-proof, so adding a p_escontext field to
struct ParseState. This also lets other parse-analysis code do error-safe
conversions the same way, if they want.

2.
+/*
+ * SafeTypeCastExpr -
+ * Transformed representation of
+ * CAST(expr AS typename DEFAULT expr ON CONVERSION ERROR)
+ */
+typedef struct SafeTypeCastExpr
+{
+ Expr xpr;
+
+ /*
+ * The transformed source expression.
+ *
+ * Cases like ``CAST(1 AS date DEFAULT NULL ON CONVERSION ERROR)`` where
+ * the castexpr evaluates to NULL, we need this field to reconstruct the
+ * original query.
+ */
+ Expr   *source;
+
+ /*
+ * transformed cast expression, NULL means cannot coerce to target type.
+ *
+ * For query jumbling, ignore this node because castexpr expression may
+ * contain the "source" expression. Including it would cause the same
+ * expression to be jumbled twice.
+ */
+ Expr   *castexpr pg_node_attr(query_jumble_ignore);

"castexpr" could already contain the "source" expression, so every
tree walker would see the same subtree twice.
That has unintended ramification, for example a
SubLink or an Aggref in the argument would be processed twice, and avoiding
that requires special care at each such place, which is fragile.
So instead "castexpr" is built over a CaseTestExpr placeholder, and
the argument is stored once.

3.
For FuncExpr, we should do something equivalent to ExecEvalCoerceViaIOSafe.

As I mentioned before, our error safe type cast evaluation mainly involves
processing/evaluating FuncExpr and CoerceViaIO nodes.  For CoerceViaIO,
ExecEvalCoerceViaIOSafe already sets resvalue and resnull on a soft error.
Function calls (FuncExpr) need the same treatment.  A function that reports an
error softly returns a dummy datum with isnull *still* false! and the next step
would consume it.  After a soft error the step must instead produce resvalue = 0
*and* resnull = true.  That has to happen at the call site, not in the consumer.

    CAST('\x01'::bytea::uuid AS text DEFAULT 'x1' ON CONVERSION ERROR)

Here, function bytea_uuid() reports the bad length with ereturn(), which records
the error and returns Datum 0 without setting fcinfo->isnull.  The next step
would then call uuid_out() on a null pointer.  By the errsave convention the
return value is garbage and the caller must check the context, so the
function-call step does that and returns NULL instead.

So four ExprEvalOp opcodes are added:
EEOP_FUNCEXPR_SAFE,
EEOP_FUNCEXPR_STRICT_SAFE,
EEOP_FUNCEXPR_SAFE_FUSAGE,
EEOP_FUNCEXPR_STRICT_SAFE_FUSAGE

4. extensive changes in clauses.c also required.

Rationale:
    CAST(('abc'::text)::int + abs(NULL) AS int DEFAULT 3 ON CONVERSION ERROR)

To make the above query does not fail, which is what we want (at least, I think
so), we need to make evaluate_expr handle soft errors.
This means evaluate_expr needs an ErrorSaveContext node. As a result, we’ll need
to refactor every occurrence of ece_evaluate_expr.



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

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:

Thank you for your continued work on this patch.

To support CAST('error' AS integer DEFAULT 1 ON CONVERSION ERROR), the
conversion of an unknown literal to a Const, done inside coerce_to_target_type,
must be able to fail softly.  Passing an ErrorSaveContext pointer down through
those functions is ugly and not future-proof, so adding a p_escontext field to
struct ParseState. This also lets other parse-analysis code do error-safe
conversions the same way, if they want.

I suspect that this may be the cause of the d_nota test results at the bottom of this review.
 

4. extensive changes in clauses.c also required.

Rationale:
    CAST(('abc'::text)::int + abs(NULL) AS int DEFAULT 3 ON CONVERSION ERROR)

To make the above query does not fail, which is what we want (at least, I think
so), we need to make evaluate_expr handle soft errors.
This means evaluate_expr needs an ErrorSaveContext node. As a result, we’ll need
to refactor every occurrence of ece_evaluate_expr.


I disagree on this point. I believe that the leading a_expr

      ('abc'::text)::int

should fail. We're looking for conversion errors on the cast operation itself, not before.

 
REVIEW

Sorry for the delays in reviewing this. It's been a while, so I tried to give everything a fresh look.  As such, I had to fall back to an earlier commit to get it to apply. My first attempt was c9c660e6ae03, which I chose it because the commit date was near the patch date, and since the patch applied clean I didn't go looking for a better one, knowing that I'd have to rebase.

Applies over c9c660e6ae03 and cleanly rebases to master, passes.

0001
====

Everything is clear here, no notes.

0002
====

Overall the new ERROR SAFE/UNSAFE configuration is exactly what I had hoped for, it simplifies whether a cast can be made safe or not, allows types from extensions and other custom datatypes to continue to function as-is, and be able to use the on-error-default functionality as soon as they make themselves (soft) error-safe.

I see that there is nothing stopping language SQL and language plpgsql functions from being declared error safe, even though there is currently no mechanism for making them functionally error safe. I don't think this is a problem in the short term, as this safe/unsafe check is initially used only for cast functions, so for the moment I'm ok with allowing this impossible assertion to be made. It isn't that much different than our ability to declare a function immutable with no check as to whether it actually is immutable. Plus, it opens the possiblity of adding such functionality to non-C functions later on.

I like the test that looks for any builtin input functions that are not declared error safe. For the time being, I would suggest temporarily adding another test looking for any functions that are declared error safe but are not input/cast related. Obviously this proposed second check will outlive its usefulness once we find a second use for error safe declarations, so it may only make sense for the committer's peace of mind during testing and be discarded thereafter.

0003
====

- The tests on bpchar are good

doc/src/sgml/syntax.sgml
----------------------------------

+     A type cast may occasionally fail at run time.  To guard against such
+     failures, you can provide an <literal>ON CONVERSION ERROR</literal>
+     clause to control what happens when a cast fails.  The available forms
+     are:

The wording here is awkward. The word "may occasionaly fail" implies that success or failure of a cast is not deterministic or depends on some input other than the value to be cast. 

I suggest replacing

    A type cast may occasionally fail at run time.

with 

    A type cast will fail if the input value cannot be resolved to a value of the destination type.

or

    A type cast will fail if the input value has no equivalent value of the destination type.

+     With <literal>DEFAULT <replaceable>expression</replaceable> ON CONVERSION ERROR</literal>,
+     the default <replaceable>expression</replaceable> is evaluated and
+     returned instead.  The <literal>ERROR ON CONVERSION ERROR</literal>
+     form raises an error on failure, which is also the default behavior
+     when no <literal>ON CONVERSION ERROR</literal> clause is specified.
+     Note: The <literal>DEFAULT</literal> <replaceable>expression</replaceable>
+     is itself evaluated normally, so it may also raise an error during that evaluation.

I suggest:

    When <literal>DEFAULT <replaceable>expression</replaceable> ON CONVERSION ERROR</literal>
    is specified, if the first <replaceable>expression</replaceable> cannot be cast to the destination type,
    then the specified <literal>DEFAULT</literal> <replaceable>expression</replaceable>
    is evaluated and cast to the destination type, which itself will raise an error if the value cannot
    be cast to the destination type.

src/backend/executor/execExpr.c
--------------------------------------------

+ fusage = (pgstat_track_functions > flinfo->fn_stats);

This line is a bit unclear, and I can find no equivalent usage in the codebase. I can see the "collect stats if track_functions > this" comment in fmgr.h, so you're following the prescribed pattern, but it looks weird to me because we're comparing a value assigned from an enum to an unsigned char, so there's an ick-factor here. Clearly it is working, but I wonder if we want to explicitly type that enum in C23, or encapsulate that test in a macro in the mean time...though all of these concerns are outside the scope for this patch.

src/backend/executor/execExprInterp.c
----------------------------------------------------

Everything here seems ok, but I'd feel better if somebody with more executor experience had a look.


cast.out
-----------

+SELECT CAST('2'::jsonb AS text DEFAULT 'fallback' ON CONVERSION ERROR);
+ text
+------
+ 2
+(1 row)

Was this meant to be a double-fail? I ask mostly because all CASTs up to this point have been testing whether the datatype can fail over to default, and this tests whether a default is ignored on a correct cast. It might help to have a comment line explaining what part of the functionality is being tested before each block of CASTs of that test type.

+-- source expression is a unknown const
+SELECT CAST('a' as int DEFAULT sum(1) ON CONVERSION ERROR); -- error
+ERROR:  aggregate functions are not allowed in CAST DEFAULT expressions
+LINE 1: SELECT CAST('a' as int DEFAULT sum(1) ON CONVERSION ERROR);

Header comment doesn't match what is being tested.

+SELECT CAST('a' as int DEFAULT (SELECT NULL) ON CONVERSION ERROR); -- error
+ERROR:  cannot use subquery in CAST DEFAULT expression
+LINE 1: SELECT CAST('a' as int DEFAULT (SELECT NULL) ON CONVERSION E...

I hadn't thought about this case until now, but it seems like a reasonable limitation.

+SELECT CAST('a' as int DEFAULT 'b' ON CONVERSION ERROR); -- error
+ERROR:  invalid input syntax for type integer: "b"
+LINE 1: SELECT CAST('a' as int DEFAULT 'b' ON CONVERSION ERROR);

This test is especially important as it demonstrates some of the fact that the second expression is casted error-unsafe.

To that end we should have a test like this to drive home that this can be chained if you really need such a thing

    SELECT CAST ('b' AS integer
                DEFAULT CAST('c' AS INTEGER
                                                 DEFAULT 0 ON CONVERSION ERROR)
               ON CONVERSION ERROR)


+-- source expression contain subquery
+SELECT CAST((SELECT b FROM generate_series(1, 1), (VALUES('H')) s(b))
+            AS int2vector[] DEFAULT '{1 3}'  ON CONVERSION ERROR);

I'm curious why this doesn't work, both the initial expression and the default expression are both a_expr. I can live with the limitation if it is truly necessary, but it does feel mildly inconsistent.

+SET jit_above_cost TO DEFAULT;
+SELECT CAST(a AS int2 DEFAULT NULL ON CONVERSION ERROR) FROM tcast0;

What is this testing? We should add a comment to indicate its purpose.


+CREATE DOMAIN ddomain AS numeric CHECK ((1/ (VALUE - 1)) > 0);
+SELECT CAST ('1' AS ddomain DEFAULT NULL ON CONVERSION ERROR); -- error
+ERROR:  division by zero
+SELECT CAST (1 AS ddomain DEFAULT NULL ON CONVERSION ERROR); -- error
+ERROR:  division by zero

Good test, needs a comment to explain why this sort of error should be raised because it's not a _conversion_ error.

+SELECT CAST (CAST('a' AS int) AS text DEFAULT NULL ON CONVERSION ERROR) FROM tcast1;  -- error
+ERROR:  invalid input syntax for type integer: "a"
+LINE 1: SELECT CAST (CAST('a' AS int) AS text DEFAULT NULL ON CONVER...

Also a good test. Needs comment. We shouldn't waste any opportunity to explain the rules of cast on error.


+SELECT CAST (CAST(a AS d_nota) AS text DEFAULT NULL ON CONVERSION ERROR) FROM tcast1;
+ a
+---
+
+(1 row)
+
+SELECT CAST (CAST('a' AS d_nota) AS text DEFAULT NULL ON CONVERSION ERROR) FROM tcast1;
+ text
+------
+
+(1 row)

These should be failures at the inner cast level, before the on-conversion cast is attempted.

Overall
======

I'm concerned about the d_nota cast results as well as the no-subquery in the default expression limitation, but everything else is looking pretty good.

It may be worth thinking about whether the SAFE/UNSAFE function designation has utility outside of cast-default, as that may be committable independent of the cast changes.

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

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Wed, Oct 14, 2026 at 12:38 PM Corey Huinker  wrote:
>> 4. extensive changes in clauses.c also required.
>>
>> Rationale:
>>     CAST(('abc'::text)::int + abs(NULL) AS int DEFAULT 3 ON CONVERSION ERROR)
>>
>> To make the above query does not fail, which is what we want (at least, I think
>> so), we need to make evaluate_expr handle soft errors.
>> This means evaluate_expr needs an ErrorSaveContext node. As a result, we’ll need
>> to refactor every occurrence of ece_evaluate_expr.
>
> I disagree on this point. I believe that the leading a_expr
>
>       ('abc'::text)::int
>
> should fail. We're looking for conversion errors on the cast operation itself, not before.
>

CREATE DOMAIN d_nota AS text CHECK (VALUE <> 'a');

> +SELECT CAST (CAST(a AS d_nota) AS text DEFAULT NULL ON CONVERSION ERROR) FROM tcast1;
> + a
> +---
> +
> +(1 row)
> +
> +SELECT CAST (CAST('a' AS d_nota) AS text DEFAULT NULL ON CONVERSION ERROR) FROM tcast1;
> + text
> +------
> +
> +(1 row)
>
> These should be failures at the inner cast level, before the on-conversion cast is attempted.
>
> Overall
> ======
>
> I'm concerned about the d_nota cast results as well as the no-subquery in the default expression limitation, but everything else is looking pretty good.
>

Previously I am using EXPR_KIND_TYPECAST_DEFAULT.  After removing
EXPR_KIND_TYPECAST_DEFAULT, DEFAULT expressions can now include aggregates,
window functions, or subqueries, but expression return sets are still not
supported.
--------------------------

SELECT CAST(ARRAY[a, '7'] AS int[] DEFAULT '{1}' ON CONVERSION ERROR)
FROM (VALUES('a'), ('1')) t(a); -- QueryA
SELECT CAST(ARRAY[a::int] AS int[] DEFAULT NULL ON CONVERSION ERROR)
FROM (VALUES('a'), ('1')) t(a); -- QueryB

We want the QueryA to fail and QueryB not to. It is not trivial to do that.

transformArrayExpr has to transform each element of the ARRAY
constructor (ARRAY[expr]) the
same way as a non-array argument: the element expression itself is evaluated
normally, and only its conversion to the target element type is error-safe. The
result is an ArrayExpr whose element conversions report into the cast's
ErrorSaveContext, so that ArrayExpr must be evaluated under that context.
Otherwise the conversions cannot fail softly.

However, always evaluating SafeTypeCastExpr->arg under the cast's
ErrorSaveContext would make the source expression error-safe as well, so that

CAST(('abc'::text)::int AS int DEFAULT 3 ON CONVERSION ERROR)
would return 3 instead of failing.

For SafeTypeCastExpr->arg, the escontext needs to be passed down to
arg only when arg is an ARRAY constructor (ARRAY[expr]), not for any
other expression type.
Hence add a boolean field arg_errorsafe to SafeTypeCastExpr to record this.

I've attached inconsistency.sql; let me know which SQL query output is
unexpected.

> It may be worth thinking about whether the SAFE/UNSAFE function designation has utility outside of cast-default, as that may be committable independent of the cast changes.
I do not fully understand this part.
Can you expand on this?



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

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:


SELECT CAST(ARRAY[a, '7'] AS int[] DEFAULT '{1}' ON CONVERSION ERROR)
FROM (VALUES('a'), ('1')) t(a); -- QueryA
SELECT CAST(ARRAY[a::int] AS int[] DEFAULT NULL ON CONVERSION ERROR)
FROM (VALUES('a'), ('1')) t(a); -- QueryB

We want the QueryA to fail and QueryB not to. It is not trivial to do that.

I believe the exact opposite should be true, and your later comments imply that you agree, so this might just be a typo. In case it isn't, I believe ARRAY[a,7] will correctly evaluate to ARRAY['a','7'] on the first row and ARRAY['1','7'] on the second row. the first row will have a conversion error to the result set will be:

{1}
{1,7}

The second one should fail outright when 'a'::int is executed, which means the array expression never completed, so the cast was never attempted.
 

transformArrayExpr has to transform each element of the ARRAY
constructor (ARRAY[expr]) the
same way as a non-array argument: the element expression itself is evaluated
normally, and only its conversion to the target element type is error-safe. The
result is an ArrayExpr whose element conversions report into the cast's
ErrorSaveContext, so that ArrayExpr must be evaluated under that context.
Otherwise the conversions cannot fail softly.

However, always evaluating SafeTypeCastExpr->arg under the cast's
ErrorSaveContext would make the source expression error-safe as well, so that

I agree, what I don't understand is how the expression ('abc'::text)::int knows it's part of a larger CAST ON DEFAULT expression.
 

CAST(('abc'::text)::int AS int DEFAULT 3 ON CONVERSION ERROR)
would return 3 instead of failing.

I agree that we want CAST(('abc'::text)::int AS int DEFAULT 3 ON CONVERSION ERROR) to fail outright.

 
For SafeTypeCastExpr->arg, the escontext needs to be passed down to
arg only when arg is an ARRAY constructor (ARRAY[expr]), not for any
other expression type.
Hence add a boolean field arg_errorsafe to SafeTypeCastExpr to record this.

I've attached inconsistency.sql; let me know which SQL query output is
unexpected.


Some comments

-- 6. An element whose conversion is known to fail before run time makes the
-- result the DEFAULT, whatever its position, and the argument is not
-- evaluated.  An untyped literal like 'x' fails at parse time; a typed
-- constant like 'x'::text, or a parameter in a custom plan, fails when the
-- planner folds its conversion.

Unfortunately, I don't think we can elide these cant-ever-succeed casts into the default expression precisely because they might themselves contain expressions that blow up the query, but that feeling is coming from an assumption that we evaluate nodes for elimination bottom-up, and if the SQL standard says we should do it top-down, then my expectations would change.

SELECT CAST(1 / z AS point DEFAULT NULL ON CONVERSION ERROR) FROM tinc; -- ok

Oddly enough, I think this should become a N-by-1 result set of NULL values, unless a z value causes a div-by-zero or similar exception. Again, if the standards people feel that top-down elimination is how its defined, then I'd feel differently.

SELECT CAST(CAST('{a}'::text[] AS date[]) AS int[] DEFAULT NULL ON CONVERSION ERROR); -- ok

Similar thing, it's an error if we evaluate bottom-up, and ok if it's top-down.

 
> It may be worth thinking about whether the SAFE/UNSAFE function designation has utility outside of cast-default, as that may be committable independent of the cast changes.
I do not fully understand this part.
Can you expand on this?

It may be that we could expand our PLs in a way that allows them to fetch these error contexts and handle them instead of having to create an expensive exception block. 



Patch applies, but I get this 

[441/1149] Compiling C object src/backend/postgres_lib.a.p/parser_parse_collate.c.o
../src/backend/parser/parse_collate.c:461:8: warning: variable 'collation' is used uninitialized whenever switch case is taken [-Wsometimes-uninitialized]
  461 |                 case T_SafeCastElement:
      |                      ^~~~~~~~~~~~~~~~~
../src/backend/parser/parse_collate.c:792:24: note: uninitialized use occurs here
  792 |         merge_collation_state(collation,
      |                               ^~~~~~~~~
../src/backend/parser/parse_collate.c:445:8: warning: variable 'collation' is used uninitialized whenever switch case is taken [-Wsometimes-uninitialized]
  445 |                 case T_SafeTypeCastExpr:
      |                      ^~~~~~~~~~~~~~~~~~
../src/backend/parser/parse_collate.c:792:24: note: uninitialized use occurs here
  792 |         merge_collation_state(collation,
      |                               ^~~~~~~~~
../src/backend/parser/parse_collate.c:258:17: note: initialize the variable 'collation' to silence this warning
  258 |         Oid                     collation;
      |                                          ^
      |                                           = 0
../src/backend/parser/parse_collate.c:461:8: warning: variable 'strength' is used uninitialized whenever switch case is taken [-Wsometimes-uninitialized]
  461 |                 case T_SafeCastElement:
      |                      ^~~~~~~~~~~~~~~~~
../src/backend/parser/parse_collate.c:793:9: note: uninitialized use occurs here
  793 |                                                   strength,
      |                                                   ^~~~~~~~
../src/backend/parser/parse_collate.c:445:8: warning: variable 'strength' is used uninitialized whenever switch case is taken [-Wsometimes-uninitialized]
  445 |                 case T_SafeTypeCastExpr:
      |                      ^~~~~~~~~~~~~~~~~~
../src/backend/parser/parse_collate.c:793:9: note: uninitialized use occurs here
  793 |                                                   strength,
      |                                                   ^~~~~~~~
../src/backend/parser/parse_collate.c:259:2: note: variable 'strength' is declared here
  259 |         CollateStrength strength;
      |         ^
../src/backend/parser/parse_collate.c:461:8: warning: variable 'location' is used uninitialized whenever switch case is taken [-Wsometimes-uninitialized]
  461 |                 case T_SafeCastElement:
      |                      ^~~~~~~~~~~~~~~~~
../src/backend/parser/parse_collate.c:794:9: note: uninitialized use occurs here
  794 |                                                   location,
      |                                                   ^~~~~~~~
../src/backend/parser/parse_collate.c:445:8: warning: variable 'location' is used uninitialized whenever switch case is taken [-Wsometimes-uninitialized]
  445 |                 case T_SafeTypeCastExpr:
      |                      ^~~~~~~~~~~~~~~~~~
../src/backend/parser/parse_collate.c:794:9: note: uninitialized use occurs here
  794 |                                                   location,
      |                                                   ^~~~~~~~
../src/backend/parser/parse_collate.c:260:16: note: initialize the variable 'location' to silence this warning
  260 |         int                     location;
      |                                         ^
      |                                          = 0

This new node type seems to cross-cut the potential solutions, but I suspect that the solution is to do what T_Var/T_Const/etc do in the same situation.


Moving onto the code

0001 - no changes from what I can detect.
0002 - no changes from what I can detect.

0003

I think there might be a bug here:

if (stcexpr->castexpr == NULL)
{
state->escontext = saved_escontext;
ExecInitExprRec(stcexpr->defexpr, state, resv, resnull);
return;
}

In this case, the comment says we want to execute the expression so it can raise errors, but we caught those in an errcontext and we never look at the errcontext to see if it found anything.


I'm going to stop there for now.

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

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
Вложения:

I'm going to stop there for now.

Contrary to my previous statement, I wasn't able to leave things be, and I started asking Claude about the compiler warnings, and then further asked about the ability to enforce short-circuiting (i.e. must evaluate the expression to be cast-ed and raise any errors found, must not evaluate the default expression until the value expression has correctly evaluated and the cast itself failed). This resulted into two patches that I've added to the existing patchset.

Patches 0001-0003 are the v34 patches, unchanged.

Patch 0004 is about removing the unassigned variables warnings (and some regressions tests that fail because of it). The LLM's solution was to move the two new node type cases from the main switch into the default switch.

Patch 0005 address requiring errors in the value expression not be ignored, but also to only evaluate the default expression if the cast operation itself failed. I'm unsure that adding no_eval to eval_const_expressions_context is the right way to go about it as there might be a more established pattern for doing such things, but it does appear to resolve all the issues I had with the behavior of the new feature.

Obviously we want to give this generated code a lot of scrutiny, but it at least demonstrates that the desired behavior as I see it is at least possible. Whether or not my idea of the expected behavior matches other's expectations is still up for debate, obviously. 

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

От:
jian he <jian.universality@gmail.com>
Дата:
On Fri, Nov 6, 2026 at 2:37 PM Corey Huinker  wrote:
>>
> Patch 0005 address requiring errors in the value expression not be ignored, but also to only evaluate the default expression if the cast operation itself failed. I'm unsure that adding no_eval to eval_const_expressions_context is the right way to go about it as there might be a more established pattern for doing such things, but it does appear to resolve all the issues I had with the behavior of the new feature.
>
> Obviously we want to give this generated code a lot of scrutiny, but it at least demonstrates that the desired behavior as I see it is at least possible. Whether or not my idea of the expected behavior matches other's expectations is still up for debate, obviously.

Hi.

https://www.postgresql.org/docs/devel/sql-expressions.html#SYNTAX-EXPRESS-EVAL
says
"""
Furthermore, if the result of an expression can be determined by
evaluating only some parts of it, then other subexpressions might not
be evaluated at all
"""

That means it is OK to let
SELECT CAST(1/0 AS date DEFAULT NULL ON CONVERSION ERROR);
SELECT CAST(ARRAY['x', (1/0)::text] AS date[] DEFAULT NULL ON CONVERSION ERROR);

not produce
ERROR:  division by zero

Because we can determine that the source expression (1/0), ('x') is
not castable to the date data type before actually evaluating the
source expression.

Regarding V5:
+SELECT CAST('1' AS int DEFAULT 1/0 ON CONVERSION ERROR);
+ SELECT CAST(ARRAY['1'] AS int[] DEFAULT ('{' || (1/0) || '}')::int[]
ON CONVERSION ERROR);

I agree it is OK for the above 2 not produce ERROR:  division by zero
------------------------------
+SELECT CAST(1/0 AS date DEFAULT NULL ON CONVERSION ERROR);
+SELECT CAST((('abc'::text)::integer) AS date DEFAULT NULL ON CONVERSION ERROR);
+SELECT CAST((1/(g-g)) AS date DEFAULT NULL ON CONVERSION ERROR) FROM
generate_series(1,1) g;
+SELECT CAST(ARRAY['x', (1/0)::text] AS date[] DEFAULT NULL ON
CONVERSION ERROR);
+SELECT CAST(ARRAY['x', (1/(g-g))::text] AS date[] DEFAULT NULL ON
CONVERSION ERROR) FROM generate_series(1,1) g;

Since the source expression cannot be converted to the target type in
all the above cases, the result is always the DEFAULT.
So here, I disagree with you, the above examples should just return NULL, IMHO.

-----------------------------
https://www.postgresql.org/docs/devel/sql-expressions.html#SYNTAX-EXPRESS-EVAL
says "The order of evaluation of subexpressions is not defined".
So I want to follow this logic:
* The source expression's data type is known before it is evaluated.
* During planner constant folding:
  If the source expression cannot be cast to the target type, skip
evaluating the source and return the DEFAULT.
  If constant folding shows that the source expression converts
successfully to the target type, skip evaluating the DEFAULT.
* At run time, the source expression is evaluated only if a cast exists from
  its type to the target type, and the DEFAULT only if the conversion fails.

What do you think?



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


FAQ