implement CAST(expr AS type FORMAT 'template')

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

implement CAST(expr AS type FORMAT 'template')

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

while working on CAST(... DEFAULT ON ERROR), I came across link[1].  I don't
have access to the SQL standard, but based on the information in link[1], for
CAST(val AS type FORMAT 'template'), I make the  as an A_Const
node in gram.y.

so the attached patch is to implement
     CAST 
          AS 
         [ FORMAT  ]
         

The implementation is pretty straightforward.
CAST(val AS type FORMAT 'template')
internally, it will be transformed into a FuncExpr node whose funcid
corresponds to
function name as one of (to_number, to_date, to_timestamp, to_char).
template as a Const node will make life easier.

select proname, prosrc, proallargtypes, proargtypes,
prorettype::regtype, proargnames
from pg_proc
where proname in ('to_number', 'to_date',  'to_timestamp', 'to_char');

based on the query results, only a limited set of type casts are supported with
formatted casts.  so error out early if the source or target type doesn't meet
these conditions.  for example, if the source or target is a composite, array,
or polymorphic type.

demo:
select cast('2018-13-12' as date format 'YYYY-MM-DD'); --error
select cast('2018-13-12' as date format 'YYYY-DD-MM'); --no error
select to_char(cast('2018-13-12' as date format 'YYYY-DD-MM'), 'YYYY-Mon-DD');
returns
2018-Dec-13

[1]: https://wiki.postgresql.org/wiki/PostgreSQL_vs_SQL_Standard#Major_features_simply_not_implemented_yet

Re: implement CAST(expr AS type FORMAT 'template')

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

On 27/07/2025 17:43, jian he wrote:
> hi.
>
> while working on CAST(... DEFAULT ON ERROR), I came across link[1].  I don't
> have access to the SQL standard, but based on the information in link[1], for
> CAST(val AS type FORMAT 'template'), I make the  as an A_Const
> node in gram.y.


Why does it have to be an A_const?  Shouldn't any a_expr work there?


> so the attached patch is to implement
>       CAST 
>            AS 
>           [ FORMAT  ]
>           


This is correct syntax.  Thanks for working on it!


> The implementation is pretty straightforward.
> CAST(val AS type FORMAT 'template')
> internally, it will be transformed into a FuncExpr node whose funcid
> corresponds to
> function name as one of (to_number, to_date, to_timestamp, to_char).
> template as a Const node will make life easier.


This doesn't seem very postgres-y to me.  Wouldn't it be better to add 
something like castformatfuncid to pg_cast?  That way any types that 
have that would just call that.  It would allow extensions to add 
formatted casting to their types, for example.


> select proname, prosrc, proallargtypes, proargtypes,
> prorettype::regtype, proargnames
> from pg_proc
> where proname in ('to_number', 'to_date',  'to_timestamp', 'to_char');
>
> based on the query results, only a limited set of type casts are supported with
> formatted casts.  so error out early if the source or target type doesn't meet
> these conditions.  for example, if the source or target is a composite, array,
> or polymorphic type.


The standard is strict on what types can be cast to another, but I see 
no reason not to be more generic.

-- 

Vik Fearing



Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Mon, Jul 28, 2025 at 2:31 AM Vik Fearing  wrote:
>
>
> On 27/07/2025 17:43, jian he wrote:
> > hi.
> >
> > while working on CAST(... DEFAULT ON ERROR), I came across link[1].  I don't
> > have access to the SQL standard, but based on the information in link[1], for
> > CAST(val AS type FORMAT 'template'), I make the  as an A_Const
> > node in gram.y.
>
>
> Why does it have to be an A_const?  Shouldn't any a_expr work there?
>

you are right. a_expr should work.
the attached patch changed accordingly.

so now
select cast(NULL as date format NULL::date); ---error
select cast(NULL as date format lower('a')); --no error, returns NULL

>
> > so the attached patch is to implement
> >       CAST 
> >            AS 
> >           [ FORMAT  ]
> >           
>

> This is correct syntax.  Thanks for working on it!
>

>
> This doesn't seem very postgres-y to me.  Wouldn't it be better to add
> something like castformatfuncid to pg_cast?  That way any types that
> have that would just call that.  It would allow extensions to add
> formatted casting to their types, for example.
>

select oid, castsource::regtype, casttarget::regtype,
castfunc::regproc, castcontext, castmethod
from pg_cast
where casttarget::regtype::text in ('text') or
castsource::regtype::text in ('text');

As you can see from the query output, cast from other type to text or
cast from text to other type is not in the pg_cast catalog entry.
there are in type input/output functions. it will be represented as a
CoerceViaIO node.
see function find_coercion_pathway (src/backend/parser/parse_coerce.c
line:3577).

adding these pg_cast entries seems tricky.
for example:
(assume castsource as numeric, casttarget as text)
will
(castsource as numeric, casttarget as text, castfunc as numeric_out,
castformatfunc as numeric_to_char)
ever work?
but numeric_out' result type is cstring.
so I tend to think adding castformatfunc to pg_cast will not work.

Re: implement CAST(expr AS type FORMAT 'template')

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

On 28/07/2025 10:41, jian he wrote:
> select oid, castsource::regtype, casttarget::regtype,
> castfunc::regproc, castcontext, castmethod
> from pg_cast
> where casttarget::regtype::text in ('text') or
> castsource::regtype::text in ('text');
>
> As you can see from the query output, cast from other type to text or
> cast from text to other type is not in the pg_cast catalog entry.
> there are in type input/output functions. it will be represented as a
> CoerceViaIO node.
> see function find_coercion_pathway (src/backend/parser/parse_coerce.c
> line:3577).


This is the same issue I came across when I tried to implement it 
several years ago.


> adding these pg_cast entries seems tricky.
> for example:
> (assume castsource as numeric, casttarget as text)
> will
> (castsource as numeric, casttarget as text, castfunc as numeric_out,
> castformatfunc as numeric_to_char)
> ever work?
> but numeric_out' result type is cstring.


I had been imagining another castcontext that would only specify the 
castfunc when the FORMAT claused is used, otherwise the current method 
of passing through IO would be used.


> so I tend to think adding castformatfunc to pg_cast will not work.


Perhaps not, but we need to find a way to make this generic so that 
custom types can define formatting rules for themselves.

-- 

Vik Fearing



Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Mon, Jul 28, 2025 at 6:47 PM Vik Fearing  wrote:
>
> > adding these pg_cast entries seems tricky.
> > for example:
> > (assume castsource as numeric, casttarget as text)
> > will
> > (castsource as numeric, casttarget as text, castfunc as numeric_out,
> > castformatfunc as numeric_to_char)
> > ever work?
> > but numeric_out' result type is cstring.
>
>
> I had been imagining another castcontext that would only specify the
> castfunc when the FORMAT claused is used, otherwise the current method
> of passing through IO would be used.
>
>
> > so I tend to think adding castformatfunc to pg_cast will not work.
>
>
> Perhaps not, but we need to find a way to make this generic so that
> custom types can define formatting rules for themselves.

We can introduce another column in pg_proc, proformat
hope it's not crazy as it is.

select proname, prosrc, proformat from pg_proc where proformat;
   proname    |       prosrc        | proformat
--------------+---------------------+-----------
 to_char      | timestamptz_to_char | t
 to_char      | numeric_to_char     | t
 to_char      | int4_to_char        | t
 to_char      | int8_to_char        | t
 to_char      | float4_to_char      | t
 to_char      | float8_to_char      | t
 to_number    | numeric_to_number   | t
 to_timestamp | to_timestamp        | t
 to_date      | to_date             | t
 to_char      | interval_to_char    | t
 to_char      | timestamp_to_char   | t

proformat is true means this function is a formatter function.
formatter function requirement:
* first argument or the return type must be TEXT.
* the second argument must be a type of TEXT.
* function should not return a set.
* keyword FORMAT must be specified while CREATE FUNCTION.
* prokind should be PROKIND_FUNCTION, normal function.
* input argument should be two. because I am not sure how to handle
multiple format templates.
like, CAST('A' AS TEXT FORMAT format1 format2).

for example:
CREATE FUNCTION test(TEXT, TEXT) RETURNS JSON AS $$ BEGIN RETURN '1';
END; $$ LANGUAGE plpgsql VOLATILE FORMAT;
this function "test" format text based on second argument(template)
and return json type.

POC attached.
what do you think?

Re: implement CAST(expr AS type FORMAT 'template')

От:
"David G. Johnston" <david.g.johnston@gmail.com>
Дата:
On Monday, July 28, 2025, jian he <jian.universality@gmail.com> wrote:
On Mon, Jul 28, 2025 at 6:47 PM Vik Fearing <vik@postgresfriends.org> wrote:
>
> > adding these pg_cast entries seems tricky.

select proname, prosrc, proformat from pg_proc where proformat;

what do you think?

My first impression of this choice was not good.

How about changing the specification for create type.  Right now input functions must declare either 1 or 3 arguments.  Let’s also allow for 2 and 4-argument functions where the 2nd or 4th is where the format is passed.  If a data type input function lacks one of those signatures it is a runtime error if a format clause is attached to its cast expression.  For output, we go from having zero input arguments to zero or one, with the same resolution behavior.

Pass null for the format if the clause is missing or the cast is done via the :: operator, or any other context format is not able to be specified.

The slight variation to this would be to specify these 2/4 and 1-arg functions as optional “format_in” and “format_out” optional properties (like typmod_in).  The format-aware code can look for these which will end up having the full implementation while the current IO functions would simply stub out calls, passing null as the format. (Or maybe some variation that looks similar to typmod handling…which I haven’t looked at.)

David J.

Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
On Tue, Jul 29, 2025 at 11:54 AM David G. Johnston
 wrote:
>
> The slight variation to this would be to specify these 2/4 and 1-arg functions as optional “format_in” and “format_out” optional properties (like typmod_in).  The format-aware code can look for these which will end up having the full implementation while the current IO functions would simply stub out calls, passing null as the format. (Or maybe some variation that looks similar to typmod handling…which I haven’t looked at.)
>

This may also work.
typmod_in, typmod_out, which is associated with typmod, which is used
in many places.
The only use case for (typformatin, typformatout) is CAST expression.
so we also need to consider the overhead of adding
two oid columns (typformatin, typformatout) to pg_type.

another question is:
should we first implement CAST(expr AS type FORMAT 'template') for limited types
(to_date, to_char, to_number, to_timestamptz)
or first try to make it more generic?


Re: implement CAST(expr AS type FORMAT 'template')

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

On 01/08/2025 10:22, jian he wrote:
> should we first implement CAST(expr AS type FORMAT 'template') for limited types
> (to_date, to_char, to_number, to_timestamptz)
> or first try to make it more generic?


My fear is that if we don't, it will never get done.

-- 

Vik Fearing



Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
hi.
one more question:

For binary coercible type casts, no formatted related function for it,
should we error out?
For example, should the following error out or return text '1'.

select cast('1'::text as text format 'YYYY'::text);


Re: implement CAST(expr AS type FORMAT 'template')

От:
"David G. Johnston" <david.g.johnston@gmail.com>
Дата:
On Sun, Aug 3, 2025 at 8:10 PM jian he <jian.universality@gmail.com> wrote:
hi.
one more question:

For binary coercible type casts, no formatted related function for it,
should we error out?
For example, should the following error out or return text '1'.

select cast('1'::text as text format 'YYYY'::text);

I'm hoping the standard says (or allows us to) error out here.

text as a type has no semantics on which to associate a format so it should be an error to attempt to do so.  Not a silent no-op.

I was under the impression that for format to be allowed in the expression one of the two data types involved has to be text and the other must not be text.

IME we are actually implementing a formatting option for text serialization and deserialization here, not a cast (we are just borrowing existing syntax that is serviceable).  Hence the absence of these entries in pg_cast and why the fit into pg_type seems so reasonable.

The existence of the various "to_char" and "to_date" functions reflects the historical lack of a dedicated syntax for this kind of (de-)serialization.  But it seems unwise to bias ourselves to how the new syntax/feature should be implemented just because these functions exist.  At least one design should be done pretending they don't and see what comes out of it.  Their code can always be moved or reused in whatever we come up with; forcing them to be used directly, as-is, within the new solution adds an unnecessary constraint.

David J.

Re: implement CAST(expr AS type FORMAT 'template')

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
On Sun, Aug 3, 2025 at 11:36 PM David G. Johnston <david.g.johnston@gmail.com> wrote:
On Sun, Aug 3, 2025 at 8:10 PM jian he <jian.universality@gmail.com> wrote:
hi.
one more question:

For binary coercible type casts, no formatted related function for it,
should we error out?
For example, should the following error out or return text '1'.

select cast('1'::text as text format 'YYYY'::text);

I'm hoping the standard says (or allows us to) error out here.

We have some influence in that, I believe.
 

text as a type has no semantics on which to associate a format so it should be an error to attempt to do so.  Not a silent no-op.

+1

 
I was under the impression that for format to be allowed in the expression one of the two data types involved has to be text and the other must not be text.

I hadn't understood that, but also hadn't thought of a case where it might be wanted until just now. What if someone wanted a cast from JSONB to their custom type, and the format was a specific keypath to extract from the JSONB? It's true that could be accomplished by first extracting the keypath and then CASTing that expression, but the same is true for text->date, regexing a YYYY-MM-DD into the locale default.

 

IME we are actually implementing a formatting option for text serialization and deserialization here, not a cast (we are just borrowing existing syntax that is serviceable).  Hence the absence of these entries in pg_cast and why the fit into pg_type seems so reasonable.

The existence of the various "to_char" and "to_date" functions reflects the historical lack of a dedicated syntax for this kind of (de-)serialization.  But it seems unwise to bias ourselves to how the new syntax/feature should be implemented just because these functions exist.  At least one design should be done pretending they don't and see what comes out of it.  Their code can always be moved or reused in whatever we come up with; forcing them to be used directly, as-is, within the new solution adds an unnecessary constraint.

I agree. I'd like the more generic solution, but I don't want to get in the way of getting it done, especially if we can change the internals later with no user impact.

But, once this is implemented, does it then make sense to then parse to_char() and to_date() into casts?

Re: implement CAST(expr AS type FORMAT 'template')

От:
Corey Huinker <corey.huinker@gmail.com>
Дата:
 
another question is:
should we first implement CAST(expr AS type FORMAT 'template') for limited types
(to_date, to_char, to_number, to_timestamptz)
or first try to make it more generic?


That was my plan, essentially rewriting these into safe versions of the existing to_date/to_timestamp/etc functions, but much has changed since then, so while it still seems like a good intermediate step, it may be a distraction as others have stated elsewhere in the thread.


Re: implement CAST(expr AS type FORMAT 'template')

От:
"David G. Johnston" <david.g.johnston@gmail.com>
Дата:
On Sunday, August 3, 2025, Corey Huinker <corey.huinker@gmail.com> wrote:
On Sun, Aug 3, 2025 at 11:36 PM David G. Johnston <david.g.johnston@gmail.com> wrote:
On Sun, Aug 3, 2025 at 8:10 PM jian he <jian.universality@gmail.com> wrote:
hi.
one more question:

For binary coercible type casts, no formatted related function for it,
should we error out?
For example, should the following error out or return text '1'.

select cast('1'::text as text format 'YYYY'::text);

I'm hoping the standard says (or allows us to) error out here.

We have some influence in that, I believe.
 

text as a type has no semantics on which to associate a format so it should be an error to attempt to do so.  Not a silent no-op.

+1

 
I was under the impression that for format to be allowed in the expression one of the two data types involved has to be text and the other must not be text.

I hadn't understood that, but also hadn't thought of a case where it might be wanted until just now. What if someone wanted a cast from JSONB to their custom type, and the format was a specific keypath to extract from the JSONB? It's true that could be accomplished by first extracting the keypath and then CASTing that expression, but the same is true for text->date, regexing a YYYY-MM-DD into the locale default.

Feels like the same basic answer.  Create cast has a single (because it’s one-way) function accepting between 1 and 3 arguments.  Change it to accept between 1 and 4 arguments and the 4th is where the format expression gets passed.  If a format expression is present and the function doesn’t have a 4th argument, error.

But, once this is implemented, does it then make sense to then parse to_char() and to_date() into casts?

I have no principled reason but I wouldn’t bother to turn these calls into casts nor do I think turning casts into these specific function calls by name is a good idea.  Leave the legacy stuff in place for compatibility, unchanged from its present form, and do the new stuff anew.

David J.

Re: implement CAST(expr AS type FORMAT 'template')

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


On 04/08/2025 07:55, David G. Johnston wrote:
On Sunday, August 3, 2025, Corey Huinker <corey.huinker@gmail.com> wrote:
On Sun, Aug 3, 2025 at 11:36 PM David G. Johnston <david.g.johnston@gmail.com> wrote:

I was under the impression that for format to be allowed in the expression one of the two data types involved has to be text and the other must not be text.

I hadn't understood that, but also hadn't thought of a case where it might be wanted until just now. What if someone wanted a cast from JSONB to their custom type, and the format was a specific keypath to extract from the JSONB? It's true that could be accomplished by first extracting the keypath and then CASTing that expression, but the same is true for text->date, regexing a YYYY-MM-DD into the locale default.

Feels like the same basic answer.  Create cast has a single (because it’s one-way) function accepting between 1 and 3 arguments.  Change it to accept between 1 and 4 arguments and the 4th is where the format expression gets passed.  If a format expression is present and the function doesn’t have a 4th argument, error.


This is my position as well.

+1

-- 

Vik Fearing

Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
hi.
please check the attached v4 patch.

1. For binary-coercible casts, if the format template is specified,
raise an error.
Example:
SELECT CAST('1'::text AS text FORMAT 'YYYY'::text); -- error
2. limited implementation — currently only supports to_char, to_date,
to_number, and to_timestamp.
3. coerce_to_target_type function is used in many places, refactoring
add another
argument seems not practical. So, I introduced a new function
coerce_to_target_type_fmt. Similarly, since coerce_type is difficult to
refactor too, I created a new function coerce_type_fmt.

At this stage, we have not modified any pg_cast entries.  Adding to_char,
to_date, etc., into pg_cast has implications that require more consideration
(see [1]).
Also for this patch, including these functions in pg_cast is not really
necessary to achieve the intended behavior.

[1] https://postgr.es/m/CACJufxF4OW=x2rCwa+ZmcgopDwGKDXha09qTfTpCj3QSTG6Y9Q@mail.gmail.com

Re: implement CAST(expr AS type FORMAT 'template')

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

Please check the attached new version.

I’ve integrated the CAST FORMAT logic right into coerce_to_target_type and
coerce_type, see static function coerce_type_with_format. in
coerce_type_with_format, we first first do source type, target type, format
expression check, validation, if everything is ok then, construct a FuncCall
node and let ParseFuncOrColumn do all the remaining job, with that now overall
the patch looks more neat.

I have tried to transform
SELECT CAST(NULL::text as time FORMAT NULL);
into
SELECT CAST( NULL::text AS timestamp with time zone FORMAT NULL::text)::time;

Then later realized it will not work, so CAST FORMAT can only be applied to the
result type of the following formatting functions: to_char, to_number, to_date,
or to_timestamp.

The tests are extensive. I put them right next to the to_char, to_number,
to_date, and to_timestamp tests so it's super easy to compare the results with
CAST FORMAT.



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

Re: implement CAST(expr AS type FORMAT 'template')

От:
"zengman" <zengman@halodbtech.com>
Дата:
Вложения:
> Please check the attached new version.
> 
> I’ve integrated the CAST FORMAT logic right into coerce_to_target_type and
> coerce_type, see static function coerce_type_with_format. in
> coerce_type_with_format, we first first do source type, target type, format
> expression check, validation, if everything is ok then, construct a FuncCall
> node and let ParseFuncOrColumn do all the remaining job, with that now overall
> the patch looks more neat.

Hi,

This patch looks great, and the tests run well. I found a few minor details,
that you might consider fixing:

Typos
- parse_expr.c:2745: "formmatted" → "formatted"
- parse_coerce.c:156: "Cocerce" → "Coerce"

In `coerce_type_with_format()` (parse_coerce.c):

1. The check `if (fmtcategory != TYPCATEGORY_STRING && fmtcategory != TYPCATEGORY_UNKNOWN)`
could be moved earlier. It doesn't depend on any other
calculations, so failing fast here would avoid unnecessary work.

2. consider using` list_make2(node, format)` instead of `list_make1() + lappend()`.

--
Regards,
Man Zeng

Re: implement CAST(expr AS type FORMAT 'template')

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

Typos
- parse_expr.c:2745: "formmatted" → "formatted"
- parse_coerce.c:156: "Cocerce" → "Coerce"

In `coerce_type_with_format()` (parse_coerce.c):

1. The check `if (fmtcategory != TYPCATEGORY_STRING && fmtcategory != TYPCATEGORY_UNKNOWN)`
could be moved earlier. It doesn't depend on any other
calculations, so failing fast here would avoid unnecessary work.

2. consider using` list_make2(node, format)` instead of `list_make1() + lappend()`.

--
Regards,
Man Zeng

Surya and I did a pair-review of this. In addition to the notes above (which we agree with), we have the following notes:

+       if (inputBaseTypeId == targetBaseTypeId)
+               ereport(ERROR,
+                               errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                               errmsg("cannot cast type %s to %s while using a format template",
+                                          format_type_be(inputBaseTypeId),
+                                          format_type_be(targetBaseTypeId)),
+                               errdetail("binary coercible type cast is not supported while using a format template"),
+                               parser_coercion_errposition(pstate, location, node));

This could use a bit more explanation in a comment - is it because there is no plausible type that can take a FORMAT and be cast to itself?

+       if (s_typcategory != TYPCATEGORY_NUMERIC &&
+               s_typcategory != TYPCATEGORY_STRING &&
+               s_typcategory != TYPCATEGORY_DATETIME &&
+               s_typcategory != TYPCATEGORY_TIMESPAN)

In situations like this, the committers have shown a strong preference for switch() statements. Though it may make more sense to package this if into a static function is_formattable_type() or similar.

+       if (t_typcategory == TYPCATEGORY_STRING)
+               funcname = list_make2(makeString("pg_catalog"),
+                                                         makeString("to_char"));
...
+       else
+               elog(ERROR, "failed to find conversion function from %s to %s while using a format template",
+                        format_type_be(inputTypeId), format_type_be(targetTypeId));

Similar thing here, committers will probably want to see a switch.

+create function imm_const() returns text as $$ begin return 'YYYY-MM-DD'; end; $$ language plpgsql immutable;;
+select cast(col1 as date format imm_const()) from tcast;

double-;

Overall, the test coverage appears complete and the close mirroring of existing tests makes the intention very clear.

Re: implement CAST(expr AS type FORMAT 'template')

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello!

There's some inconsistency in deparse, it displays to_char for intervals:

CREATE VIEW test_interval_format AS
  SELECT CAST('1 year 2 months'::interval AS text FORMAT 'YYYY-MM') AS
fmt_interval;
CREATE VIEW test_timestamp_format AS
  SELECT CAST('2024-01-15 00:00:00'::timestamp AS text FORMAT
'YYYY-MM-DD') AS fmt_timestamp;

SELECT pg_get_viewdef('test_interval_format'::regclass);
SELECT pg_get_viewdef('test_timestamp_format'::regclass);


I also see a similar to_char leak in the error message - wouldn't this
confuse users, as they never wrote to_char?

postgres=# SELECT cast('2012-12-12 12:00'::timetz as text format
'YYYY-MM-DD HH:MI:SS TZ');
2026-03-24 06:27:45.792 UTC [5917] ERROR:  function
pg_catalog.to_char(time with time zone, text) does not exist
2026-03-24 06:27:45.792 UTC [5917] DETAIL:  No function of that name
accepts the given argument types.
2026-03-24 06:27:45.792 UTC [5917] HINT:  You might need to add
explicit type casts.
2026-03-24 06:27:45.792 UTC [5917] STATEMENT:  SELECT cast('2012-12-12
12:00'::timetz as text format 'YYYY-MM-DD HH:MI:SS TZ');
ERROR:  function pg_catalog.to_char(time with time zone, text) does not exist
DETAIL:  No function of that name accepts the given argument types.
HINT:  You might need to add explicit type casts.


Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Tue, Mar 24, 2026 at 4:20 AM Corey Huinker  wrote:
>
> Surya and I did a pair-review of this. In addition to the notes above (which we agree with), we have the following notes:
>
> +       if (inputBaseTypeId == targetBaseTypeId)
> +               ereport(ERROR,
> +                               errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
> +                               errmsg("cannot cast type %s to %s while using a format template",
> +                                          format_type_be(inputBaseTypeId),
> +                                          format_type_be(targetBaseTypeId)),
> +                               errdetail("binary coercible type cast is not supported while using a format template"),
> +                               parser_coercion_errposition(pstate, location, node));
>
> This could use a bit more explanation in a comment - is it because there is no plausible type that can take a FORMAT and be cast to itself?
>

We might be able to do it in the future; it's currently not allowed.
I have used the ERRCODE_FEATURE_NOT_SUPPORTED error code.

We should not use
``> +       if (inputBaseTypeId == targetBaseTypeId)``
We need to use IsBinaryCoercible.

src1=# SELECT CAST('52'::int2 as numeric FORMAT '9 9 9 9 9 9 . 9 9');
ERROR:  function pg_catalog.to_number(smallint, text) does not exist
DETAIL:  No function of that name accepts the given argument types.
HINT:  You might need to add explicit type casts.

The above CAST FORMAT error message is not ideal, therefore we need
stricter type restrictions for source and target data types,
and more type checking.
The target type must exactly match the function's result type.
to_char, to_date, to_number, to_timestamp.

> +       if (s_typcategory != TYPCATEGORY_NUMERIC &&
> +               s_typcategory != TYPCATEGORY_STRING &&
> +               s_typcategory != TYPCATEGORY_DATETIME &&
> +               s_typcategory != TYPCATEGORY_TIMESPAN)
>
> In situations like this, the committers have shown a strong preference for switch() statements. Though it may make more sense to package this if into a static function is_formattable_type() or similar.
>

we need more restriction on CAST FORMAT source type and target type.
pg_type->typcategory is not reliable for disallowing source/target types,
So, I use switch() to enumerate all allowed data types and the
switch() default branch handles ereport(ERROR).




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

Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
On Tue, Mar 24, 2026 at 2:31 PM Zsolt Parragi  wrote:
> Hello!
>
> There's some inconsistency in deparse, it displays to_char for intervals:
>
> I also see a similar to_char leak in the error message - wouldn't this
> confuse users, as they never wrote to_char?
>
> postgres=# SELECT cast('2012-12-12 12:00'::timetz as text format
> 'YYYY-MM-DD HH:MI:SS TZ');
> ERROR:  function pg_catalog.to_char(time with time zone, text) does not exist
> DETAIL:  No function of that name accepts the given argument types.
> HINT:  You might need to add explicit type casts.

The nearby v6 fixed these two issues, but,
src1=# SELECT cast('2012-12-12 12:00'::timetz as text format
'YYYY-MM-DD HH:MI:SS TZ');
ERROR:  cannot cast type time with time zone to text using formatted template
LINE 1: SELECT cast('2012-12-12 12:00'::timetz as text format
               ^
DETAIL:  Only categories of numeric, string, datetime, and timespan
source data types are supported for formatted type casting

The errdeatil above is not good and needs further improvement, since
timetz is a datetime category data type.


Re: implement CAST(expr AS type FORMAT 'template')

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
v6 is better, but I found a few more questions:

+select pg_get_viewdef('tcast_v1', true);
+                                       pg_get_viewdef
+--------------------------------------------------------------------------------------------
+  SELECT CAST( col1 AS date FORMAT 'YYYY-MM-DD'::text) AS to_date,
                     +

Is that space after "CAST(" intentional?

+ format = coerce_to_target_type(pstate, fmt,
+    exprType(fmt), TEXTOID,
+    exprTypmod(fmt),
+    ccontext, cformat,
+    exprLocation(fmt));

Is exprTypmod(fmt) correct, shouldn't it use -1?

This one also shows a not so userfriendly error:

postgres=# SELECT CAST('hello' AS name FORMAT 'test') ;
2026-03-30 22:12:53.651 UTC [750980] ERROR:  function
pg_catalog.to_char(text, text) does not exist
2026-03-30 22:12:53.651 UTC [750980] DETAIL:  No function of that name
accepts the given argument types.
2026-03-30 22:12:53.651 UTC [750980] HINT:  You might need to add
explicit type casts.
2026-03-30 22:12:53.651 UTC [750980] STATEMENT:  SELECT CAST('hello'
AS name FORMAT 'test') ;
ERROR:  function pg_catalog.to_char(text, text) does not exist
DETAIL:  No function of that name accepts the given argument types.
HINT:  You might need to add explicit type casts.

And varchar/bpchar adds details about binary coercible casts:

SELECT CAST('hello' AS bpchar FORMAT 'test') ;
2026-03-30 22:14:12.081 UTC [750980] ERROR:  cannot cast type text to
character while using a format template at character 8
2026-03-30 22:14:12.081 UTC [750980] DETAIL:  binary coercible type
cast is not supported while using a format template
2026-03-30 22:14:12.081 UTC [750980] STATEMENT:  SELECT CAST('hello'
AS bpchar FORMAT 'test') ;
ERROR:  cannot cast type text to character while using a format template
LINE 1: SELECT CAST('hello' AS bpchar FORMAT 'test') ;


Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Tue, Mar 31, 2026 at 6:18 AM Zsolt Parragi  wrote:
>
> v6 is better, but I found a few more questions:
>
> +select pg_get_viewdef('tcast_v1', true);
> +                                       pg_get_viewdef
> +--------------------------------------------------------------------------------------------
> +  SELECT CAST( col1 AS date FORMAT 'YYYY-MM-DD'::text) AS to_date,
>                      +
> Is that space after "CAST(" intentional?
>
I have removed this white spce.

> + format = coerce_to_target_type(pstate, fmt,
> +    exprType(fmt), TEXTOID,
> +    exprTypmod(fmt),
> +    ccontext, cformat,
> +    exprLocation(fmt));
>
> Is exprTypmod(fmt) correct, shouldn't it use -1?
>
yes. it should be -1.

> This one also shows a not so userfriendly error:
>
> postgres=# SELECT CAST('hello' AS name FORMAT 'test') ;
>
> SELECT CAST('hello' AS bpchar FORMAT 'test') ;

now:
SELECT CAST('hello' AS name FORMAT 'test') ;
ERROR:  cannot cast type text to name using formatted template

SELECT CAST('hello' AS bpchar FORMAT 'test') ;
ERROR:  cannot cast type text to character while using a format template
LINE 1: SELECT CAST('hello' AS bpchar FORMAT 'test') ;
               ^
DETAIL:  binary coercible type cast is not supported while using a
format template

type Text to type name is not binary coercible, see outpout of:

select *, castfunc::regproc from pg_cast
where castsource = 'text'::regtype and casttarget = 'name'::regtype;



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

Re: implement CAST(expr AS type FORMAT 'template')

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


On Tue, Mar 31, 2026 at 3:48 AM jian he <jian.universality@gmail.com> wrote:
On Tue, Mar 31, 2026 at 6:18 AM Zsolt Parragi <zsolt.parragi@percona.com> wrote:
>
> v6 is better, but I found a few more questions:
>
> +select pg_get_viewdef('tcast_v1', true);
> +                                       pg_get_viewdef
> +--------------------------------------------------------------------------------------------
> +  SELECT CAST( col1 AS date FORMAT 'YYYY-MM-DD'::text) AS to_date,
>                      +
> Is that space after "CAST(" intentional?
>
I have removed this white spce.

> + format = coerce_to_target_type(pstate, fmt,
> +    exprType(fmt), TEXTOID,
> +    exprTypmod(fmt),
> +    ccontext, cformat,
> +    exprLocation(fmt));
>
> Is exprTypmod(fmt) correct, shouldn't it use -1?
>
yes. it should be -1.

> This one also shows a not so userfriendly error:
>
> postgres=# SELECT CAST('hello' AS name FORMAT 'test') ;
>
> SELECT CAST('hello' AS bpchar FORMAT 'test') ;

now:
SELECT CAST('hello' AS name FORMAT 'test') ;
ERROR:  cannot cast type text to name using formatted template

SELECT CAST('hello' AS bpchar FORMAT 'test') ;
ERROR:  cannot cast type text to character while using a format template
LINE 1: SELECT CAST('hello' AS bpchar FORMAT 'test') ;
               ^
DETAIL:  binary coercible type cast is not supported while using a
format template

type Text to type name is not binary coercible, see outpout of:

select *, castfunc::regproc from pg_cast
where castsource = 'text'::regtype and casttarget = 'name'::regtype;



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

Everything's passing, moving the tests out of citext, etc into cast.sql is good.

I think the next step it to bring each TODO and FIXME into the thread, and explain the factors that prevent you from being certain about what to do in those situations.

Re: implement CAST(expr AS type FORMAT 'template')

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Tue, Mar 31, 2026 at 1:48 PM Corey Huinker  wrote:
> Everything's passing, moving the tests out of citext, etc into cast.sql is good.
>
> I think the next step it to bring each TODO and FIXME into the thread, and explain the factors that prevent you from being certain about what to do in those situations.

IMHO, this patch as currently written is basically dead on arrival.
The v7 patch still works by constructing calls to
pg_catalog.{to_date,to_number,to_timestamp,to_char} based on the input
data type. But I think it's been clearly stated on this thread that we
need some kind of more generic infrastructure. Vik said it best: "we
need to find a way to make this generic so that custom types can
define formatting rules for themselves." I completely agree. The
extensible type system in PostgreSQL is one of the project's greatest
triumphs, and I do not think anyone is going to be enthusiastic about
committing a patch that purports to implement a flavor of casting but
is completely unextensible by out-of-core types and doesn't even cover
all the in-core types for which it might be interesting. Even if
someone is, -1 from me.

I suggest backing up to David G. Johnston's comment here: "How about
changing the specification for create type.  Right now input functions
must declare either 1 or 3 arguments.  Let’s also allow for 2 and
4-argument functions where the 2nd or 4th is where the format is
passed.  If a data type input function lacks one of those signatures
it is a runtime error if a format clause is attached to its cast
expression.  For output, we go from having zero input arguments to
zero or one, with the same resolution behavior." I'm not sure that
David's proposal here is really the best thing, but it's the kind of
thing that *could* be right, i.e. a generic infrastructure that can
work for any choice of data type.

The reason I somewhat hesitate to endorse that specific proposal is
that I'm not convinced that we should actually treat this as a form of
casting. Casts can be set to IMPLICIT or ASSIGNMENT or EXPLICIT, and
they can be WITHOUT FUNCTION or WITH INOUT, and none of that can be
relevant here. A CAST with FORMAT always needs to be implemented by a
function, is always explicit from a syntax point of view, and the code
to implement probably looks pretty different from the code needed for
a non-FORMAT cast. I am somewhat inclined to think we want something
that's like a cast function but actually a wholly separate mechanism,
e.g. a new pg_formatter catalog. I note that Jian He proposed putting
something in pg_type but I don't see how that can work, since there
are two types involved.

I don't accept the argument that we should start with this and extend
it later. The patch as proposed is just syntactic sugar. Said another
way, there is existing syntax that already delivers the functionality.
So I don't see why we would rush out support for a bit of new syntax;
anyone who wants to use this functionality can already do so. Getting
the infrastructure right is, IMHO, the interesting part of the
project, and I think that work needs to be done first.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: implement CAST(expr AS type FORMAT 'template')

От:
Haibo Yan <tristan.yim@gmail.com>
Дата:
Вложения:
On Thu, Jun 18, 2026 at 7:52 AM Robert Haas  wrote:
>
> On Tue, Mar 31, 2026 at 1:48 PM Corey Huinker  wrote:
> > Everything's passing, moving the tests out of citext, etc into cast.sql is good.
> >
> > I think the next step it to bring each TODO and FIXME into the thread, and explain the factors that prevent you from being certain about what to do in those situations.
>
> IMHO, this patch as currently written is basically dead on arrival.
> The v7 patch still works by constructing calls to
> pg_catalog.{to_date,to_number,to_timestamp,to_char} based on the input
> data type. But I think it's been clearly stated on this thread that we
> need some kind of more generic infrastructure. Vik said it best: "we
> need to find a way to make this generic so that custom types can
> define formatting rules for themselves." I completely agree. The
> extensible type system in PostgreSQL is one of the project's greatest
> triumphs, and I do not think anyone is going to be enthusiastic about
> committing a patch that purports to implement a flavor of casting but
> is completely unextensible by out-of-core types and doesn't even cover
> all the in-core types for which it might be interesting. Even if
> someone is, -1 from me.
>
> I suggest backing up to David G. Johnston's comment here: "How about
> changing the specification for create type.  Right now input functions
> must declare either 1 or 3 arguments.  Let’s also allow for 2 and
> 4-argument functions where the 2nd or 4th is where the format is
> passed.  If a data type input function lacks one of those signatures
> it is a runtime error if a format clause is attached to its cast
> expression.  For output, we go from having zero input arguments to
> zero or one, with the same resolution behavior." I'm not sure that
> David's proposal here is really the best thing, but it's the kind of
> thing that *could* be right, i.e. a generic infrastructure that can
> work for any choice of data type.
>
> The reason I somewhat hesitate to endorse that specific proposal is
> that I'm not convinced that we should actually treat this as a form of
> casting. Casts can be set to IMPLICIT or ASSIGNMENT or EXPLICIT, and
> they can be WITHOUT FUNCTION or WITH INOUT, and none of that can be
> relevant here. A CAST with FORMAT always needs to be implemented by a
> function, is always explicit from a syntax point of view, and the code
> to implement probably looks pretty different from the code needed for
> a non-FORMAT cast. I am somewhat inclined to think we want something
> that's like a cast function but actually a wholly separate mechanism,
> e.g. a new pg_formatter catalog. I note that Jian He proposed putting
> something in pg_type but I don't see how that can work, since there
> are two types involved.
>
> I don't accept the argument that we should start with this and extend
> it later. The patch as proposed is just syntactic sugar. Said another
> way, there is existing syntax that already delivers the functionality.
> So I don't see why we would rush out support for a bit of new syntax;
> anyone who wants to use this functionality can already do so. Getting
> the infrastructure right is, IMHO, the interesting part of the
> project, and I think that work needs to be done first.
>
> --
> Robert Haas
> EDB: http://www.enterprisedb.com
>
>

Robert pointed out earlier that hard-coding specific functions like
to_date and to_char in the parser would make the feature feel like a
set of special cases rather than a general mechanism.  I agree, and this
version moves to a catalog-driven design.

I added a new pg_formatter catalog.  A row in this catalog represents
one formatted conversion from a source type to a target type, and points
to a formatter function with this signature:

formatter(source_type, text) returns target_type

The second argument is the FORMAT expression coerced to text.

I kept this separate from pg_cast because formatted casts have different
semantics from ordinary casts.  Ordinary casts have concepts like implicit
casts, assignment casts, binary-compatible casts, and I/O casts.  A
formatted cast is different: it is always explicit, it has an extra format
expression, and it needs a function that receives both the source value and
the format string.  Putting this into pg_cast seemed likely to add special
cases there, while a separate catalog keeps the model simpler.

Another important point in this version is that built-in and user-defined
formatters use the same mechanism.  The parser and analyzer do not know
about to_date, to_char, or to_timestamp.  Built-in datetime/string
formatters are registered as catalog rows, and user-defined formatters are
registered the same way.  If no formatter exists for the exact source and
target type pair, the formatted cast fails.  It does not fall back to
ordinary cast resolution.

I split the work into four patches.

Patch 1 only adds parser support for the syntax:

CAST(expr AS type FORMAT format_expr)

It extends the raw TypeCast node with an optional format field and
updates the grammar and raw expression walker.  Parse analysis still
rejects formatted casts in this patch, so this is only the syntax and raw
parse-tree representation.

Patch 2 adds the catalog and DDL infrastructure.  It introduces
pg_formatter, syscache support, CREATE FORMATTER, DROP FORMATTER,
dependency handling, object-address support, and pg_dump support.  At this
point CAST ... FORMAT still does not execute; the patch only adds the
catalog object model.

Patch 3 is where formatted casts are resolved.  During parse analysis, the
source expression is transformed, the FORMAT expression is transformed and
coerced to text, and pg_formatter is searched by exact source and target
type.  I also treat unknown source literals as text, so cases like this
resolve naturally:

CAST('2026-06-28' AS date FORMAT 'YYYY-MM-DD')

I added a CoerceViaFormatter node rather than using a plain FuncExpr.
This preserves CAST(... FORMAT ...) syntax in ruleutils and pg_dump, and
allows the dependency walker to record a dependency on the pg_formatter
row itself.  Execution still uses the normal function-call machinery, so no
new executor opcode is needed.

Patch 4 adds an initial set of built-in formatter functions and bootstrap
pg_formatter rows for common datetime/string cases:

text/varchar/bpchar <-> date
text/varchar/bpchar <-> timestamp
text/varchar/bpchar <-> timestamptz

These built-ins are reached through the same catalog lookup path as
user-defined formatters.  They are not special-cased in parse analysis.  The
wrappers reuse PostgreSQL’s existing formatting code and are marked STRICT,
so NULL input or NULL FORMAT returns NULL.

This gives us SQL-standard-style CAST ... FORMAT support for the common
datetime/string cases, but the series intentionally does not claim complete
SQL-standard datetime-template conformance.  The built-ins reuse
PostgreSQL’s existing formatting template behavior.  Additional types such
as time, timetz, numeric, and interval, or stricter standard-template
coverage, can be added later as formatter functions without changing the
parser or the CoerceViaFormatter representation.

The main goal of this redesign is to make CAST ... FORMAT a real
catalog-driven facility rather than a parser rewrite to a few built-in
functions.  I think this addresses Robert’s concern better and gives us a
path for both built-in and extension-defined formatters.

I have attached the full patch series for review.  Comments are welcome.

Regards,
Haibo

Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Thu, Jun 18, 2026 at 10:52 PM Robert Haas  wrote:
>
> On Tue, Mar 31, 2026 at 1:48 PM Corey Huinker  wrote:
> > Everything's passing, moving the tests out of citext, etc into cast.sql is good.
> >
> > I think the next step it to bring each TODO and FIXME into the thread, and explain the factors that prevent you from being certain about what to do in those situations.
>
> IMHO, this patch as currently written is basically dead on arrival.
> The v7 patch still works by constructing calls to
> pg_catalog.{to_date,to_number,to_timestamp,to_char} based on the input
> data type. But I think it's been clearly stated on this thread that we
> need some kind of more generic infrastructure. Vik said it best: "we
> need to find a way to make this generic so that custom types can
> define formatting rules for themselves." I completely agree. The
> extensible type system in PostgreSQL is one of the project's greatest
> triumphs, and I do not think anyone is going to be enthusiastic about
> committing a patch that purports to implement a flavor of casting but
> is completely unextensible by out-of-core types and doesn't even cover
> all the in-core types for which it might be interesting. Even if
> someone is, -1 from me.
>
> I suggest backing up to David G. Johnston's comment here: "How about
> changing the specification for create type.  Right now input functions
> must declare either 1 or 3 arguments.  Let’s also allow for 2 and
> 4-argument functions where the 2nd or 4th is where the format is
> passed.  If a data type input function lacks one of those signatures
> it is a runtime error if a format clause is attached to its cast
> expression.  For output, we go from having zero input arguments to
> zero or one, with the same resolution behavior." I'm not sure that
> David's proposal here is really the best thing, but it's the kind of
> thing that *could* be right, i.e. a generic infrastructure that can
> work for any choice of data type.
>

I initially tried adding a 4th text argument to existing type input functions
(like date_in, array_in) to support format-driven casting from cstring to a
type's internal representation. This approach turned out to be a dead end due to
two irreconcilable constraints.

If the 4th argument defaults to NULL: pg_proc.proisstrict must be set to
false to prevent the function from short-circuiting and returning NULL whenever
no format is supplied. But eval_const_expressions relies on type input functions
being strict to safely constant-fold T_CoerceViaIO nodes — marking them all
non-strict would silently defeat a large class of optimizations.

If the 4th argument defaults to a non-NULL value: there is no sensible
sentinel, any chosen text value would be indistinguishable from a real format
string intentionally passed by the caller.

The fourth argument must have a DEFAULT value,
otherwise, we will have a duplicated function name for the data type
input function, which seems not ideal.
------------------------------------------------------------------
At first I thought the 4th argument on the input function was really
necessary. Consider:
CAST('{2022-21-01}' AS DATE[] FORMAT 'YYYY-DD-MM');
For this to work, we need converting each array element to date using
the specified
format — array_in would need to receive the format string somehow.

But given the analysis above, that path is closed. So the only remaining option
for making array format casting work is to duplicate a large portion of
array_in's logic into a dedicated array input formatting function:
array_typformatin.
------------------------------------------------------------------
This thread doesn't mention how CAST FORMAT deals with array types.
I imagine the mechanism is applies the format template to each array element.

For example:
CAST('{2022-01-01, 2022-21-01}' AS DATE[] FORMAT 'YYYY-DD-MM');

Apply the format template ('YYYY-DD-MM')  to ``2022-01-01`` and
``2022-21-01`` during processing date_in.
------------------------------------------------------------------
Similar to CREATE TYPE (typmodin/typmodout), the attached patch
extends the pg_type catalog,
add typformatin and typformatout to pg_type.

These two fields are the function OIDs for CAST FORMAT.

typformatin: the function converts a text value to the type's
internal representation given a format template.  It must have
signature (text, text) -> type.

typformatout allows values of the data type to be converted to text using a
format template. It must have the signature (type, text) -> text,
where the second
argument is the format template.

With this patch, CAST(expr AS type FORMAT 'template') works for any data type
that has a valid typformatin or typformatout support function registered.
However, the feature remains tightly scoped to text-based conversions: FORMAT is
only meaningful when the cast target or source is text data type, CAST FORMAT
between two non-text types such as int8 to int4 is not supported.




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

Re: implement CAST(expr AS type FORMAT 'template')

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Mon, Jun 29, 2026 at 1:20 AM Haibo Yan  wrote:
> I have attached the full patch series for review.  Comments are welcome.

This looks good!

I haven't done a detailed review, but I skimmed over all of the
patches and I like the direction. I think we should consider calling
it a "format cast" instead of a "formatter". It would avoid needing to
make "formatter" a parser keyword.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: implement CAST(expr AS type FORMAT 'template')

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
The latest patch fail make check in my testrun:

not ok 166   + collate.linux.utf8


+	if ((str == NULL || fmtisnull) && flinfo->fn_strict)
+		return (Datum) 0;		/* just return null result */

With the condition written like this a non strict formatter function
ignores nulls, and possibly crashes the server.


Shouldn't pg_dump also handle the new TYPEFORMAT_IN? Currently it's
lost during a dump-restore.


Re: implement CAST(expr AS type FORMAT 'template')

От:
Haibo Yan <tristan.yim@gmail.com>
Дата:
Вложения:
On Mon, Jun 29, 2026 at 11:14 AM Robert Haas  wrote:
>
> On Mon, Jun 29, 2026 at 1:20 AM Haibo Yan  wrote:
> > I have attached the full patch series for review.  Comments are welcome.
>
> This looks good!
>
> I haven't done a detailed review, but I skimmed over all of the
> patches and I like the direction. I think we should consider calling
> it a "format cast" instead of a "formatter". It would avoid needing to
> make "formatter" a parser keyword.
>
> --
> Robert Haas
> EDB: http://www.enterprisedb.com

Hi Robert,

Thanks for looking at the patches.
I liked your suggestion to call these “format casts” rather than
“formatters”, so I changed the series in that direction.  The DDL is
now:
------------------------------------------------------
CREATE FORMAT CAST (...)
DROP FORMAT CAST (...)
------------------------------------------------------
rather than CREATE/DROP FORMATTER, so the patch no longer adds
FORMATTER as a keyword.
I also renamed the related catalog and node names, so this now uses
pg_format_cast and CoerceViaFormatCast.  The
pg_dump/object-address/comment/extension code and the regression tests
have been updated to use the new terminology as well.
The rest of the design is the same as before: format casts are still
catalog-driven, and both built-in and user-defined cases go through
the same lookup path.

Attached is the updated v2 series.

Regards,
Haibo

Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
On Wed, Jul 1, 2026 at 1:39 AM Haibo Yan  wrote:
>
> Thanks for looking at the patches.
> I liked your suggestion to call these “format casts” rather than
> “formatters”, so I changed the series in that direction.  The DDL is
> now:
> ------------------------------------------------------
> CREATE FORMAT CAST (...)
> DROP FORMAT CAST (...)
> ------------------------------------------------------
> rather than CREATE/DROP FORMATTER, so the patch no longer adds
> FORMATTER as a keyword.
> I also renamed the related catalog and node names, so this now uses
> pg_format_cast and CoerceViaFormatCast.  The
> pg_dump/object-address/comment/extension code and the regression tests
> have been updated to use the new terminology as well.
> The rest of the design is the same as before: format casts are still
> catalog-driven, and both built-in and user-defined cases go through
> the same lookup path.
>

In an earlier thread [1], [2], I proposed introducing:

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

That drew some pushback over non-standard conformance.
Here, we are introducing

CREATE FORMAT CAST (source_type AS target_type)
    WITH FUNCTION function_name [ (argument_type [, ...]) ]

This syntax is quite close to CREATE CAST.
per https://www.postgresql.org/docs/devel/sql-createcast.html
CREATE FORMAT CAST would be an extension to the standard, though we
already have non-standard precedent: AS IMPLICIT.

Before proceeding, do we need to reach consensus on the syntax itself?

Does the following alternative syntax make sense for CAST FORMAT?

CREATE CAST (source_type AS target_type)
    WITH FUNCTION function_name [ (argument_type [, ...]) ]
    AS FORMAT
----------------------------------------------------------------------------------------
As I mentioned previously [3], there's an open question around this case:

CAST('{2022-01-01, 2022-21-01}' AS DATE[] FORMAT 'YYYY-DD-MM');

does this mean the format template ('YYYY-DD-MM') should be applied to each
element (2022-01-01, 2022-21-01) individually via the cast format function?

This matters because it affects check_format_cast_function's handling of
argument_type. According to create_format_cast.sgml, the format function should
take exactly two arguments, with the last one being text. If array types are to
be supported, then argument_type would need to become either (source_type,
format_text) or (source_type, oid, int, format_text).

Sure, we can support formatted casts for array types later, but we still need to
think through the array-type formatting design now, so that the cast format
function's argument types won't need to change later to accommodate arrays.

[1]: https://www.postgresql.org/message-id/5ae9578e-f25e-49c5-97ab-ad27bc2050b5%40eisentraut.org
[2]: https://www.postgresql.org/message-id/attachment/192833/v23-0023-error-safe-for-user-defined-CREATE-CAST.patch
[3]: https://www.postgresql.org/message-id/CACJufxGVuCM4XFGqaqiV-VOEiqMtCZ3%2BT-%2BSrG-y6kqdLo1ZqA%40mail.gmail.com



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


Re: implement CAST(expr AS type FORMAT 'template')

От:
Haibo Yan <tristan.yim@gmail.com>
Дата:
Hi Jian,

Thanks for looking at this.

On Wed, Jul 1, 2026 at 6:45 AM jian he  wrote:
>
> On Wed, Jul 1, 2026 at 1:39 AM Haibo Yan  wrote:
> >
> > Thanks for looking at the patches.
> > I liked your suggestion to call these “format casts” rather than
> > “formatters”, so I changed the series in that direction.  The DDL is
> > now:
> > ------------------------------------------------------
> > CREATE FORMAT CAST (...)
> > DROP FORMAT CAST (...)
> > ------------------------------------------------------
> > rather than CREATE/DROP FORMATTER, so the patch no longer adds
> > FORMATTER as a keyword.
> > I also renamed the related catalog and node names, so this now uses
> > pg_format_cast and CoerceViaFormatCast.  The
> > pg_dump/object-address/comment/extension code and the regression tests
> > have been updated to use the new terminology as well.
> > The rest of the design is the same as before: format casts are still
> > catalog-driven, and both built-in and user-defined cases go through
> > the same lookup path.
> >
>
> In an earlier thread [1], [2], I proposed introducing:
>
> CREATE CAST (source_type AS target_type)
>     WITH [SAFE] FUNCTION function_name [ (argument_type [, ...]) ]
>
> That drew some pushback over non-standard conformance.
> Here, we are introducing
>
> CREATE FORMAT CAST (source_type AS target_type)
>     WITH FUNCTION function_name [ (argument_type [, ...]) ]
>
> This syntax is quite close to CREATE CAST.
> per https://www.postgresql.org/docs/devel/sql-createcast.html
> CREATE FORMAT CAST would be an extension to the standard, though we
> already have non-standard precedent: AS IMPLICIT.
>
> Before proceeding, do we need to reach consensus on the syntax itself?

yes, I agree that we should get agreement on the DDL syntax before going
much further.

I see the analogy with the earlier SAFE discussion, but I think this case is a
little different.  This patch creates a separate object kind rather than adding
another option to ordinary CREATE CAST

>
> Does the following alternative syntax make sense for CAST FORMAT?

My reason for preferring CREATE FORMAT CAST is that a format cast is not
really an ordinary cast with one more attribute.  Ordinary casts live in
pg_cast and are tied to things like cast context and cast method.  A format
cast is only considered for

CAST(expr AS type FORMAT fmt)

and not for ordinary casts without a FORMAT clause, assignment casts, or
implicit casts.  It also always needs a function whose second argument is the
FORMAT expression, not the destination typmod argument used by ordinary cast
functions.
So I think

CREATE CAST (...) WITH FUNCTION ... AS FORMAT

would make this look more like a pg_cast entry than it really is.  My
preference is to keep format casts separate from ordinary casts, both in the
catalog and in the DDL syntax.  Of course, if others prefer a different
spelling, we should settle that in the thread.


>
> CREATE CAST (source_type AS target_type)
>     WITH FUNCTION function_name [ (argument_type [, ...]) ]
>     AS FORMAT
> ----------------------------------------------------------------------------------------
> As I mentioned previously [3], there's an open question around this case:
>
> CAST('{2022-01-01, 2022-21-01}' AS DATE[] FORMAT 'YYYY-DD-MM');
>
> does this mean the format template ('YYYY-DD-MM') should be applied to each
> element (2022-01-01, 2022-21-01) individually via the cast format function?
>
> This matters because it affects check_format_cast_function's handling of
> argument_type. According to create_format_cast.sgml, the format function should
> take exactly two arguments, with the last one being text. If array types are to
> be supported, then argument_type would need to become either (source_type,
> format_text) or (source_type, oid, int, format_text).

I don’t feel this patch should imply automatic element-wise formatting.
The current design is an exact source/target lookup in pg_format_cast.  So in
this case, after resolving the source expression, the lookup would be for a
format cast from the source type to date[] itself.  It would not automatically
fall back to a text -> date format cast and apply it to each array element.

That does not rule out element-wise array support later.  If we want that, one
possible design would be to mirror the existing array-coercion approach: look
up the scalar format cast for the element types and wrap it in an array-mapping
expression.  In that design, the scalar format-cast function signature would
still remain

function(source_element_type, text) returns target_element_type

and the array expression node would be responsible for iterating over the
array.

>
> Sure, we can support formatted casts for array types later, but we still need to
> think through the array-type formatting design now, so that the cast format
> function's argument types won't need to change later to accommodate arrays.

I think that should be a separate design decision.  The important point for
this patch is that it does not define automatic element-wise formatting, and I
don’t think we need to change the basic scalar function signature now in order
to leave room for such a design.

If people agree with this interpretation, I can add a sentence to the
documentation saying that format cast lookup is by exact source and target
type, and that the FORMAT clause is not automatically applied to array
elements.


>
> [1]: https://www.postgresql.org/message-id/5ae9578e-f25e-49c5-97ab-ad27bc2050b5%40eisentraut.org
> [2]: https://www.postgresql.org/message-id/attachment/192833/v23-0023-error-safe-for-user-defined-CREATE-CAST.patch
> [3]: https://www.postgresql.org/message-id/CACJufxGVuCM4XFGqaqiV-VOEiqMtCZ3%2BT-%2BSrG-y6kqdLo1ZqA%40mail.gmail.com
>
>
>
> --
> jian
> https://www.enterprisedb.com/

Regards,
Haibo


Re: implement CAST(expr AS type FORMAT 'template')

От:
"David G. Johnston" <david.g.johnston@gmail.com>
Дата:
On Wed, Jul 1, 2026 at 9:45 AM Haibo Yan <tristan.yim@gmail.com> wrote:
Hi Jian,

Thanks for looking at this.

On Wed, Jul 1, 2026 at 6:45 AM jian he <jian.universality@gmail.com> wrote:
>
> On Wed, Jul 1, 2026 at 1:39 AM Haibo Yan <tristan.yim@gmail.com> wrote:
> >
> > Thanks for looking at the patches.
> > I liked your suggestion to call these “format casts” rather than
> > “formatters”, so I changed the series in that direction.  The DDL is
> > now:
> > ------------------------------------------------------
> > CREATE FORMAT CAST (...)
> > DROP FORMAT CAST (...)
> > ------------------------------------------------------
> > rather than CREATE/DROP FORMATTER, so the patch no longer adds
> > FORMATTER as a keyword.
> > I also renamed the related catalog and node names, so this now uses
> > pg_format_cast and CoerceViaFormatCast.  The
> > pg_dump/object-address/comment/extension code and the regression tests
> > have been updated to use the new terminology as well.
> > The rest of the design is the same as before: format casts are still
> > catalog-driven, and both built-in and user-defined cases go through
> > the same lookup path.
> >
>
> In an earlier thread [1], [2], I proposed introducing:
>
> CREATE CAST (source_type AS target_type)
>     WITH [SAFE] FUNCTION function_name [ (argument_type [, ...]) ]
>
> That drew some pushback over non-standard conformance.
> Here, we are introducing
>
> CREATE FORMAT CAST (source_type AS target_type)
>     WITH FUNCTION function_name [ (argument_type [, ...]) ]
>
> This syntax is quite close to CREATE CAST.
> per https://www.postgresql.org/docs/devel/sql-createcast.html
> CREATE FORMAT CAST would be an extension to the standard, though we
> already have non-standard precedent: AS IMPLICIT.
>
> Before proceeding, do we need to reach consensus on the syntax itself?

yes, I agree that we should get agreement on the DDL syntax before going
much further.

I see the analogy with the earlier SAFE discussion, but I think this case is a
little different.  This patch creates a separate object kind rather than adding
another option to ordinary CREATE CAST

>
> Does the following alternative syntax make sense for CAST FORMAT?

My reason for preferring CREATE FORMAT CAST is that a format cast is not
really an ordinary cast with one more attribute.  Ordinary casts live in
pg_cast and are tied to things like cast context and cast method.  A format
cast is only considered for

CAST(expr AS type FORMAT fmt) 

and not for ordinary casts without a FORMAT clause, assignment casts, or
implicit casts.  It also always needs a function whose second argument is the
FORMAT expression, not the destination typmod argument used by ordinary cast
functions.
So I think

CREATE CAST (...) WITH FUNCTION ... AS FORMAT

would make this look more like a pg_cast entry than it really is.

I think the fact the standard put this inside the 'cast(...)' means it's quite reasonable to consider the aspect part of a cast definition as opposed to something wholly different.

When we issue "create table" both pg_class and pg_attribute are modified.  It seems quite reasonable that executing "create cast" causes both pg_cast and pg_cast_format to be populated.

With two separate commands a cast could exist on pg_cast_format that doesn't exist in pg_cast.  I'm unsure whether this is allowed or desired...but seems a bit unexpected to me at least.


>
> CREATE CAST (source_type AS target_type)
>     WITH FUNCTION function_name [ (argument_type [, ...]) ]
>     AS FORMAT
> ----------------------------------------------------------------------------------------
> As I mentioned previously [3], there's an open question around this case:
>
> CAST('{2022-01-01, 2022-21-01}' AS DATE[] FORMAT 'YYYY-DD-MM');
>
> does this mean the format template ('YYYY-DD-MM') should be applied to each
> element (2022-01-01, 2022-21-01) individually via the cast format function?

Yes, the internal array formatting structure used by PostgreSQL isn't (needn't be) user-configurable; the useful thing for the format to apply to is the value of the elements of the array.

IMO the only change the addition of a format clause should make when performing the cast is allowing a cast that would fail due to a syntax error to succeed.

postgres=# select cast(cast('{"2025-01-01","2026-02-02","2027-03-03"}'::text as
text[]) as date[]);
                date                
------------------------------------
 {2025-01-01,2026-02-02,2027-03-03}
(1 row)

postgres=# select cast(cast('{"2025T01-01","2026T02-02","2027T03-03"}'::text as
text[]) as date[]);
ERROR:  invalid input syntax for type date: "2025T01-01"

A format clause would make the second query not error with an appropriate format specification - in which case it then behaves identically to the first query.

If the SQL Standard somehow contradicts this intent I'd be curious to understand what it does intend.

David J.

Re: implement CAST(expr AS type FORMAT 'template')

От:
Haibo Yan <tristan.yim@gmail.com>
Дата:
Hi David,

Thanks, this is helpful.

On Wed, Jul 1, 2026 at 1:59 PM David G. Johnston
 wrote:
>
> On Wed, Jul 1, 2026 at 9:45 AM Haibo Yan  wrote:
>>
>> Hi Jian,
>>
>> Thanks for looking at this.
>>
>> On Wed, Jul 1, 2026 at 6:45 AM jian he  wrote:
>> >
>> > On Wed, Jul 1, 2026 at 1:39 AM Haibo Yan  wrote:
>> > >
>> > > Thanks for looking at the patches.
>> > > I liked your suggestion to call these “format casts” rather than
>> > > “formatters”, so I changed the series in that direction.  The DDL is
>> > > now:
>> > > ------------------------------------------------------
>> > > CREATE FORMAT CAST (...)
>> > > DROP FORMAT CAST (...)
>> > > ------------------------------------------------------
>> > > rather than CREATE/DROP FORMATTER, so the patch no longer adds
>> > > FORMATTER as a keyword.
>> > > I also renamed the related catalog and node names, so this now uses
>> > > pg_format_cast and CoerceViaFormatCast.  The
>> > > pg_dump/object-address/comment/extension code and the regression tests
>> > > have been updated to use the new terminology as well.
>> > > The rest of the design is the same as before: format casts are still
>> > > catalog-driven, and both built-in and user-defined cases go through
>> > > the same lookup path.
>> > >
>> >
>> > In an earlier thread [1], [2], I proposed introducing:
>> >
>> > CREATE CAST (source_type AS target_type)
>> >     WITH [SAFE] FUNCTION function_name [ (argument_type [, ...]) ]
>> >
>> > That drew some pushback over non-standard conformance.
>> > Here, we are introducing
>> >
>> > CREATE FORMAT CAST (source_type AS target_type)
>> >     WITH FUNCTION function_name [ (argument_type [, ...]) ]
>> >
>> > This syntax is quite close to CREATE CAST.
>> > per https://www.postgresql.org/docs/devel/sql-createcast.html
>> > CREATE FORMAT CAST would be an extension to the standard, though we
>> > already have non-standard precedent: AS IMPLICIT.
>> >
>> > Before proceeding, do we need to reach consensus on the syntax itself?
>>
>> yes, I agree that we should get agreement on the DDL syntax before going
>> much further.
>>
>> I see the analogy with the earlier SAFE discussion, but I think this case is a
>> little different.  This patch creates a separate object kind rather than adding
>> another option to ordinary CREATE CAST
>>
>> >
>> > Does the following alternative syntax make sense for CAST FORMAT?
>>
>> My reason for preferring CREATE FORMAT CAST is that a format cast is not
>> really an ordinary cast with one more attribute.  Ordinary casts live in
>> pg_cast and are tied to things like cast context and cast method.  A format
>> cast is only considered for
>>
>> CAST(expr AS type FORMAT fmt)
>>
>>
>> and not for ordinary casts without a FORMAT clause, assignment casts, or
>> implicit casts.  It also always needs a function whose second argument is the
>> FORMAT expression, not the destination typmod argument used by ordinary cast
>> functions.
>> So I think
>>
>> CREATE CAST (...) WITH FUNCTION ... AS FORMAT
>>
>> would make this look more like a pg_cast entry than it really is.
>
>
> I think the fact the standard put this inside the 'cast(...)' means it's quite reasonable to consider the aspect part of a cast definition as opposed to something wholly different.
>
> When we issue "create table" both pg_class and pg_attribute are modified.  It seems quite reasonable that executing "create cast" causes both pg_cast and pg_cast_format to be populated.
>
> With two separate commands a cast could exist on pg_cast_format that doesn't exist in pg_cast.  I'm unsure whether this is allowed or desired...but seems a bit unexpected to me at least.
>

I see what you mean.  I had been thinking of format casts as separate because
they are only considered for

CAST(expr AS type FORMAT fmt)

and not for ordinary casts without a FORMAT clause.  That is why the patch
currently uses a separate catalog and a separate CREATE FORMAT CAST command.

But your pg_class / pg_attribute analogy is a good point.  A separate
catalog does not necessarily imply a separate DDL command, and it may be
surprising if a format-cast entry can exist without any corresponding ordinary
cast relationship.

Maybe the question for the thread is whether a format cast should be modeled as
a separate object, or as additional information associated with an ordinary
cast.  The latter could still use a separate catalog internally, but be created
through some form of CREATE CAST.


>>
>> >
>> > CREATE CAST (source_type AS target_type)
>> >     WITH FUNCTION function_name [ (argument_type [, ...]) ]
>> >     AS FORMAT
>> > ----------------------------------------------------------------------------------------
>> > As I mentioned previously [3], there's an open question around this case:
>> >
>> > CAST('{2022-01-01, 2022-21-01}' AS DATE[] FORMAT 'YYYY-DD-MM');
>> >
>> > does this mean the format template ('YYYY-DD-MM') should be applied to each
>> > element (2022-01-01, 2022-21-01) individually via the cast format function?
>
>
> Yes, the internal array formatting structure used by PostgreSQL isn't (needn't be) user-configurable; the useful thing for the format to apply to is the value of the elements of the array.
>
> IMO the only change the addition of a format clause should make when performing the cast is allowing a cast that would fail due to a syntax error to succeed.
>
> postgres=# select cast(cast('{"2025-01-01","2026-02-02","2027-03-03"}'::text as
> text[]) as date[]);
>                 date
> ------------------------------------
>  {2025-01-01,2026-02-02,2027-03-03}
> (1 row)
>
> postgres=# select cast(cast('{"2025T01-01","2026T02-02","2027T03-03"}'::text as
> text[]) as date[]);
> ERROR:  invalid input syntax for type date: "2025T01-01"

If PostgreSQL would normally cast an array by applying the element cast to each
element, then it is natural to expect the FORMAT clause to affect that element
cast rather than the array container syntax.

CAST('{2025T01-01,2026T02-02}' AS date[] FORMAT 'YYYY"T"MM-DD')

could reasonably mean: parse the array structure as usual, and apply the
formatted text -> date conversion to each element.

The current patch does not implement that.  It does an exact source/target
lookup in pg_format_cast, so an array target would currently require a format
cast for the array type itself.  But I agree that this may not be the behavior
users would expect, especially given the existing array coercion behavior.

If we decide that element-wise array formatting is required, one possible
implementation would be to keep the scalar format-cast function signature as

function(source_element_type, text) returns target_element_type

and add a format-aware path in the array coercion logic.  The array expression
would iterate over elements and pass the same FORMAT expression to the scalar
format cast.  In that design, the array container itself would not need a
separate format-cast entry.

>
> A format clause would make the second query not error with an appropriate format specification - in which case it then behaves identically to the first query.

I agree that this is the important case for input parsing.  I think FORMAT is
also useful in the output direction, though.  For example,

CAST(date '2026-07-01' AS text FORMAT 'YYYY/MM/DD')

would succeed without FORMAT, but the FORMAT clause controls the textual
representation.

>
> If the SQL Standard somehow contradicts this intent I'd be curious to understand what it does intend.
>
> David J.
>

So I think we have two related design questions to settle:

whether format casts are separate objects or additional information
associated with ordinary casts;
whether element-wise array formatting should be part of the initial design.

Regards,
Haibo


Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
On Thu, Jul 2, 2026 at 8:01 AM Haibo Yan  wrote:
>
> CAST('{2025T01-01,2026T02-02}' AS date[] FORMAT 'YYYY"T"MM-DD')
>
> could reasonably mean: parse the array structure as usual, and apply the
> formatted text -> date conversion to each element.
>
> The current patch does not implement that.  It does an exact source/target
> lookup in pg_format_cast, so an array target would currently require a format
> cast for the array type itself.  But I agree that this may not be the behavior
> users would expect, especially given the existing array coercion behavior.
>
> If we decide that element-wise array formatting is required, one possible
> implementation would be to keep the scalar format-cast function signature as
>
> function(source_element_type, text) returns target_element_type
>
> and add a format-aware path in the array coercion logic.  The array expression
> would iterate over elements and pass the same FORMAT expression to the scalar
> format cast.  In that design, the array container itself would not need a
> separate format-cast entry.
>

In some cases, ArrayCoerceExpr might help, but not here.

CAST('{2025T01-01,2026T02-02}'::TEXT AS date[] FORMAT 'YYYY"T"MM-DD')

parse the array structure as usual, which array_in do all the heavy work.
arrray_in(cstring, oid, integer).
But once array_in is finished, we already get a date[] datum, then
FORMAT is no longer needed.
I also mentioned [1] that add a text argument to array_in is not possible.

I guess not supporting arrays in the initial patch should be fine,
since not all CASTs support CAST FORMAT.
That raises another question: for user-defined CREATE FORMAT CAST,
should we ban anyarray as the first argument type?
If we don't, will it conflict with array support once we implement it later?

[1]: https://www.postgresql.org/message-id/CACJufxGVuCM4XFGqaqiV-VOEiqMtCZ3%2BT-%2BSrG-y6kqdLo1ZqA%40mail.gmail.com


Re: implement CAST(expr AS type FORMAT 'template')

От:
"David G. Johnston" <david.g.johnston@gmail.com>
Дата:
On Wednesday, July 1, 2026, jian he <jian.universality@gmail.com> wrote:
I guess not supporting arrays in the initial patch should be fine,
since not all CASTs support CAST FORMAT.

Personally I’d require solving the entire problem before putting any of it in.  This doesn’t seem like a feature that needs two years to implement.  And it isn’t like we don’t have usable tools while we wait.  This is for standards conformance more than anything.

David J.

Re: implement CAST(expr AS type FORMAT 'template')

От:
Haibo Yan <tristan.yim@gmail.com>
Дата:
On Wed, Jul 1, 2026 at 8:23 PM jian he  wrote:
>
> On Thu, Jul 2, 2026 at 8:01 AM Haibo Yan  wrote:
> >
> > CAST('{2025T01-01,2026T02-02}' AS date[] FORMAT 'YYYY"T"MM-DD')
> >
> > could reasonably mean: parse the array structure as usual, and apply the
> > formatted text -> date conversion to each element.
> >
> > The current patch does not implement that.  It does an exact source/target
> > lookup in pg_format_cast, so an array target would currently require a format
> > cast for the array type itself.  But I agree that this may not be the behavior
> > users would expect, especially given the existing array coercion behavior.
> >
> > If we decide that element-wise array formatting is required, one possible
> > implementation would be to keep the scalar format-cast function signature as
> >
> > function(source_element_type, text) returns target_element_type
> >
> > and add a format-aware path in the array coercion logic.  The array expression
> > would iterate over elements and pass the same FORMAT expression to the scalar
> > format cast.  In that design, the array container itself would not need a
> > separate format-cast entry.
> >
>
> In some cases, ArrayCoerceExpr might help, but not here.
>
> CAST('{2025T01-01,2026T02-02}'::TEXT AS date[] FORMAT 'YYYY"T"MM-DD')
>
> parse the array structure as usual, which array_in do all the heavy work.
> arrray_in(cstring, oid, integer).
> But once array_in is finished, we already get a date[] datum, then
> FORMAT is no longer needed.
> I also mentioned [1] that add a text argument to array_in is not possible.

Thanks, I agree that ArrayCoerceExpr is not enough for that case.
the normal array input path would already have to parse the elements as dates
while constructing the date[] value, so the FORMAT clause cannot simply be
applied after array_in has returned.


>
> I guess not supporting arrays in the initial patch should be fine,
> since not all CASTs support CAST FORMAT.

I think that means array support needs a separate design.  For the initial
patch, it seems better not to support formatted casts involving array types at
all.


> That raises another question: for user-defined CREATE FORMAT CAST,
> should we ban anyarray as the first argument type?

yes, I think polymorphic pseudo-types should becrejected.  The current patch
already rejects pseudo-types, so anyarray should not be accepted.  But to
avoid future ambiguity, I think we should also reject concrete array source or
target types for now.

Otherwise, a future element-wise array design would have to choose between an
exact array-level format cast and an element-wise scalar format cast.  I don’t
think we want both meanings.  If array support is added later, my preference
would be for it to mean element-wise application of a scalar format cast, with
the normal array machinery still handling the array container syntax.


> If we don't, will it conflict with array support once we implement it later?

So the initial rule could simply be: no polymorphic pseudo-types, and no array
source or target types for `CREATE FORMAT CAST`.  If people agree, I can update
the patch and documentation that way.

>
> [1]: https://www.postgresql.org/message-id/CACJufxGVuCM4XFGqaqiV-VOEiqMtCZ3%2BT-%2BSrG-y6kqdLo1ZqA%40mail.gmail.com

Regards,
Haibo


Re: implement CAST(expr AS type FORMAT 'template')

От:
Peter Eisentraut <peter@eisentraut.org>
Дата:
On 18.06.26 16:51, Robert Haas wrote:
> The reason I somewhat hesitate to endorse that specific proposal is
> that I'm not convinced that we should actually treat this as a form of
> casting. Casts can be set to IMPLICIT or ASSIGNMENT or EXPLICIT, and
> they can be WITHOUT FUNCTION or WITH INOUT, and none of that can be
> relevant here. A CAST with FORMAT always needs to be implemented by a
> function, is always explicit from a syntax point of view, and the code
> to implement probably looks pretty different from the code needed for
> a non-FORMAT cast. I am somewhat inclined to think we want something
> that's like a cast function but actually a wholly separate mechanism,
> e.g. a new pg_formatter catalog. I note that Jian He proposed putting
> something in pg_type but I don't see how that can work, since there
> are two types involved.
> 
> I don't accept the argument that we should start with this and extend
> it later. The patch as proposed is just syntactic sugar. Said another
> way, there is existing syntax that already delivers the functionality.
> So I don't see why we would rush out support for a bit of new syntax;
> anyone who wants to use this functionality can already do so. Getting
> the infrastructure right is, IMHO, the interesting part of the
> project, and I think that work needs to be done first.

I don't really understand the purpose of this feature to begin with. 
You can already call the formatting functions directly.  Does this cast 
syntax offer anything on top of that?



Re: implement CAST(expr AS type FORMAT 'template')

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Wed, Jul 1, 2026 at 4:59 PM David G. Johnston
 wrote:
> I think the fact the standard put this inside the 'cast(...)' means it's quite reasonable to consider the aspect part of a cast definition as opposed to something wholly different.
>
> When we issue "create table" both pg_class and pg_attribute are modified.  It seems quite reasonable that executing "create cast" causes both pg_cast and pg_cast_format to be populated.

I don't see how this would work. The existence of a regular cast
doesn't mean there has to be a format cast, and the existence of a
format cast doesn't mean there has to be a regular cast. Expressions
that use a format cast need to depend on the pg_format_cast entry, and
expressions that use a regular cast need to depend on the pg_cast
entry.

I mean, I'm not saying something else is totally impossible. You could
for example create the pg_cast entry always and make it some kind of
dummy entry when there's only a format cast. Then all casts could
depend on the pg_cast entry. But then we'd still have to have ALTER
CAST commands that modify the format-cast part of the object and the
non-format cast part of the object separately. That seems extremely
unpleasant to sort out, especially since right now a cast can't be
modified after it's created, and changing that might have security
implications. But even apart from that it doesn't seems like it will
make for a very awkward user experience.

I agree with Peter that I'm not really sure why we want to implement
this in the first place; it doesn't seem to add any value over just
having functions. The above is just a discussion about what we should
do (or what I think we should do) if we do want to have it.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: implement CAST(expr AS type FORMAT 'template')

От:
"David G. Johnston" <david.g.johnston@gmail.com>
Дата:
On Thursday, July 2, 2026, Robert Haas <robertmhaas@gmail.com> wrote:
On Wed, Jul 1, 2026 at 4:59 PM David G. Johnston
<david.g.johnston@gmail.com> wrote:
> I think the fact the standard put this inside the 'cast(...)' means it's quite reasonable to consider the aspect part of a cast definition as opposed to something wholly different.
>
> When we issue "create table" both pg_class and pg_attribute are modified.  It seems quite reasonable that executing "create cast" causes both pg_cast and pg_cast_format to be populated.

I don't see how this would work. The existence of a regular cast
doesn't mean there has to be a format cast,

Agree
 

and the existence of a
format cast doesn't mean there has to be a regular cast.

Disagree
 
But then we'd still have to have ALTER
CAST commands that modify the format-cast part of the object and the
non-format cast part of the object separately. That seems extremely
unpleasant to sort out, especially since right now a cast can't be
modified after it's created, and changing that might have security
implications.

Then we don;t need the alter to be able to modify the non-format portion of the cast.  I do imagine that the formatter is an optional component of a cast.  So “alter cast … {attach|detach} formatter …”.  We don’t even need a create command component though seems nice to keep it for convenience.

I don’t have any qualms adding this so as long as fits into the existing system cleanly.  The array example does actually provide new ease-of-use for an admittedly possibly rare use case.

David J.

Re: implement CAST(expr AS type FORMAT 'template')

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Thu, Jul 2, 2026 at 4:51 PM David G. Johnston
 wrote:
>> and the existence of a
>> format cast doesn't mean there has to be a regular cast.
>
> Disagree

OK, but on what basis?

If I want 'whatever'::thistype::thattype to fail and CAST(thistype AS
thattype FORMAT 'bumble') to succeed, then I need there to be a format
cast but not a regular cast. Apparently, you'd like to arbitrarily
disallow that case, but I can't see any logical reason for such a
prohibition. Essentially we'd be forcing the user to create a regular
cast that they don't want in order to be able to create a format cast
that they do want. If there were some reason why we had to couple the
two things together that way, that would be one thing, but as far as I
can see, there isn't.

--
Robert Haas
EDB: http://www.enterprisedb.com


Re: implement CAST(expr AS type FORMAT 'template')

От:
"David G. Johnston" <david.g.johnston@gmail.com>
Дата:
On Thursday, July 2, 2026, Robert Haas <robertmhaas@gmail.com> wrote:
On Thu, Jul 2, 2026 at 4:51 PM David G. Johnston
<david.g.johnston@gmail.com> wrote:
>> and the existence of a
>> format cast doesn't mean there has to be a regular cast.
>
> Disagree

OK, but on what basis?

If I want 'whatever'::thistype::thattype to fail and CAST(thistype AS
thattype FORMAT 'bumble') to succeed, then I need there to be a format
cast but not a regular cast

There is no wanting the formatless-variant to fail.  There is recognition that sometime the formatless variant might fail with a syntax error and we have a way to pass a format to make the cast work. 

If there is no cast from thistype to thattype both will fail with cast not found errors.  Once a cast exists the first one could pass or fail depending on the content being casted.  If the content has an internal structure/syntax the failure mode would then be a syntax error.  Overcoming a syntax error is done by specifying a format.  But a format does you no good if there isn’t some cast pathway already available to use it.  IOW a format should never be required - some default exists, like for dates today, that allows the non-format cast to work.  We just need some way to pass in a format to that cast function if one is specified.

For me the presence of the word cast in the syntax drives this way of thinking about the problem/design.  I’d rather just stick with our polymorphic to_char functions if we want some way of outputting text with a format at without having to call doing so a cast.

David J.

Re: implement CAST(expr AS type FORMAT 'template')

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Thu, Jul 2, 2026 at 5:52 PM David G. Johnston
 wrote:
> There is no wanting the formatless-variant to fail.  There is recognition that sometime the formatless variant might fail with a syntax error and we have a way to pass a format to make the cast work.
 >
> If there is no cast from thistype to thattype both will fail with cast not found errors.  Once a cast exists the first one could pass or fail depending on the content being casted.  If the content has an internal structure/syntax the failure mode would then be a syntax error.  Overcoming a syntax error is done by specifying a format.  But a format does you no good if there isn’t some cast pathway already available to use it.  IOW a format should never be required - some default exists, like for dates today, that allows the non-format cast to work.  We just need some way to pass in a format to that cast function if one is specified.
>
> For me the presence of the word cast in the syntax drives this way of thinking about the problem/design.  I’d rather just stick with our polymorphic to_char functions if we want some way of outputting text with a format at without having to call doing so a cast.

I don't really know how to have a productive conversation about this
at this point. I agree that we might be better off just sticking with
our polymorphic to_char functions. But if we want to implement
CAST(... FORMAT ...) I do not understand how what you've written above
amounts to a coherent design proposal; it just doesn't make any sense
to me. If you spell it out with specific syntax, specific catalog
changes, and specific ways that things would work, then maybe I would
have an opinion, but right now all I can really say is that I disagree
strongly with the idea of trying to treat CAST(a AS b) and CAST(a AS b
FORMAT c) as two variants of the same thing just because they both
have CAST in the name. It matters whether they actually *do* the same
thing -- whether they could reasonably be implemented by the same code
-- and I think they can't.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: implement CAST(expr AS type FORMAT 'template')

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Fri, Jul 3, 2026 at 12:09 AM David G. Johnston
 wrote:
> I'm not sure how to make the design less problematic: format is optional, and for casts that need a format to succeed they provide a default.

But that's not how casts work today. some_date::text shares neither
code nor behavior with to_char(some_date, 'some_built_in_constant').
It's completely separate. We're not going to rethink the basic design
of casts for the sake of CAST(...FORMAT...).

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
On Thu, Jul 2, 2026 at 11:13 PM Peter Eisentraut  wrote:
>
> On 18.06.26 16:51, Robert Haas wrote:
> > The reason I somewhat hesitate to endorse that specific proposal is
> > that I'm not convinced that we should actually treat this as a form of
> > casting. Casts can be set to IMPLICIT or ASSIGNMENT or EXPLICIT, and
> > they can be WITHOUT FUNCTION or WITH INOUT, and none of that can be
> > relevant here. A CAST with FORMAT always needs to be implemented by a
> > function, is always explicit from a syntax point of view, and the code
> > to implement probably looks pretty different from the code needed for
> > a non-FORMAT cast. I am somewhat inclined to think we want something
> > that's like a cast function but actually a wholly separate mechanism,
> > e.g. a new pg_formatter catalog. I note that Jian He proposed putting
> > something in pg_type but I don't see how that can work, since there
> > are two types involved.
> >
> > I don't accept the argument that we should start with this and extend
> > it later. The patch as proposed is just syntactic sugar. Said another
> > way, there is existing syntax that already delivers the functionality.
> > So I don't see why we would rush out support for a bit of new syntax;
> > anyone who wants to use this functionality can already do so. Getting
> > the infrastructure right is, IMHO, the interesting part of the
> > project, and I think that work needs to be done first.
>
> I don't really understand the purpose of this feature to begin with.
> You can already call the formatting functions directly.  Does this cast
> syntax offer anything on top of that?
>

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

After this implemented, we can begin fully supporting:

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


Re: implement CAST(expr AS type FORMAT 'template')

От:
Haibo Yan <tristan.yim@gmail.com>
Дата:
On Thu, Jul 2, 2026 at 8:14 AM Peter Eisentraut  wrote:
>
> On 18.06.26 16:51, Robert Haas wrote:
> > The reason I somewhat hesitate to endorse that specific proposal is
> > that I'm not convinced that we should actually treat this as a form of
> > casting. Casts can be set to IMPLICIT or ASSIGNMENT or EXPLICIT, and
> > they can be WITHOUT FUNCTION or WITH INOUT, and none of that can be
> > relevant here. A CAST with FORMAT always needs to be implemented by a
> > function, is always explicit from a syntax point of view, and the code
> > to implement probably looks pretty different from the code needed for
> > a non-FORMAT cast. I am somewhat inclined to think we want something
> > that's like a cast function but actually a wholly separate mechanism,
> > e.g. a new pg_formatter catalog. I note that Jian He proposed putting
> > something in pg_type but I don't see how that can work, since there
> > are two types involved.
> >
> > I don't accept the argument that we should start with this and extend
> > it later. The patch as proposed is just syntactic sugar. Said another
> > way, there is existing syntax that already delivers the functionality.
> > So I don't see why we would rush out support for a bit of new syntax;
> > anyone who wants to use this functionality can already do so. Getting
> > the infrastructure right is, IMHO, the interesting part of the
> > project, and I think that work needs to be done first.
>
> I don't really understand the purpose of this feature to begin with.
> You can already call the formatting functions directly.  Does this cast
> syntax offer anything on top of that?
>

I agree that the feature would be hard to justify if it only covered
to_date() and to_char() under another spelling.

The cases where I think a generic mechanism could be useful are
broader than that.  For example:

    text <-> date/time        using datetime templates
    text <-> numeric          using number templates
    text <-> bytea            using hex/base64/escape
    text/bytea <-> extension types
                          using external representations such as
                          WKT/WKB/GeoJSON for geometry types

The first two are close to the existing formatting functions.  The bytea
case is currently handled by encode()/decode(), but it has the same general
shape: a conversion between a typed value and a textual representation,
controlled by a format argument.

For extension types, the case may be stronger.  PostGIS, for example, has
several external representations for geometry values: WKT, WKB, EWKT, GeoJSON,
and so on.  A catalog-driven format-cast mechanism would let an extension
register those conversions without the parser knowing any of the function
names.

Other types might also have useful representation variants, such as UUIDs or
network/address types, but the point is that this is not limited to the current
date/time functions.

So I agree that this should not be sold as just syntax sugar for the existing
date/time functions.  If it is worth doing, the value is the generic
infrastructure for FORMAT-aware conversions, including extension types, and not
just the initial built-in datetime cases.

Regards,
Haibo


Re: implement CAST(expr AS type FORMAT 'template')

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Mon, Jul 6, 2026 at 1:14 PM Haibo Yan  wrote:
> The cases where I think a generic mechanism could be useful are
> broader than that.  For example:
>
>     text <-> date/time        using datetime templates
>     text <-> numeric          using number templates
>     text <-> bytea            using hex/base64/escape
>     text/bytea <-> extension types
>                           using external representations such as
>                           WKT/WKB/GeoJSON for geometry types
>
> The first two are close to the existing formatting functions.  The bytea
> case is currently handled by encode()/decode(), but it has the same general
> shape: a conversion between a typed value and a textual representation,
> controlled by a format argument.

Sure, but in each case, the conversion function in question could just
be called directly.

It's also noteworthy that in each of these examples, one of the two
types is text, or maybe bytea, which, again, really makes you wonder
why this is designed as a cast-like mechanism. I guess you could have
CAST(now() to 'integer' FORMAT 'YYYY') but that seems fairly silly, so
I really don't understand why this is designed to take two arbitrary
types.

Aside from standards-compliance, the only value I can see in a feature
like this is if it's helpful to be able to name the type rather than
naming the conversion function. For instance, imagine that I could use
the same format string for conversions between a bunch of different
types. Then potentially it's handy to be able to write CAST(something
AS text FORMAT 'the string I always use') and you don't need to think
about which source type you've got at this particular call site. But
there are multiple problems with that idea. First, it seems unlikely
that the format string would be generic in that way. And second, we
already support function overloading, so you could just pick some
function name (like to_char!) and overload it to do the same thing.
Picking a function name also has the advantage of not privileging one
particular way of doing a conversion between two types over all
others, whereas this FORMAT CAST proposal requires you to decide on
one canonical method of formatting type X as type Y.

(Regular casts have this problem, too, to an extent.)

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: implement CAST(expr AS type FORMAT 'template')

От:
Haibo Yan <tristan.yim@gmail.com>
Дата:
On Mon, Jul 6, 2026 at 1:27 PM Robert Haas  wrote:
>
> On Mon, Jul 6, 2026 at 4:15 PM Haibo Yan  wrote:
> > The examples I listed are mostly conversions between a typed value and a
> > textual or binary representation, not arbitrary conversions between unrelated
> > types.  So I agree that the current pg_format_cast design may be too broad if
> > it allows arbitrary source/target pairs.
>
> Well, I don't think the issue here is really about pg_format_cast. If
> the syntax supports arbitrary pairs of types, the catalog
> representation should do. But there's also the question of whether we
> want to support the syntax.
>
> > Maybe the better boundary is that a formatted conversion should be between a
> > data type and an external representation type, probably text or bytea.
> >
> > That would allow cases such as text -> date, numeric -> text, and
> > bytea -> some_type, and also the existing-style text <-> bytea encoding
> > case.  But it should not become a generic text -> text or bytea -> bytea
> > transformation mechanism, nor a second cast system for arbitrary type pairs.
>
> But if this is in the SQL standard -- is it? -- then that ship has
> already sailed. We're just left to wonder why they did it like that...
>
> --
> Robert Haas
> EDB: http://www.enterprisedb.com

Hi all,

I looked more closely at the standard and at the concerns raised here.

I now think my v2 patch is too broad.  It tries to make CAST(... FORMAT ...)
a generic user-defined format-cast mechanism, but SQL feature T839 is much
narrower: formatted casts between datetime types and character strings.

So I think the next version should move back closer to Jian’s original scope:
support T839 first, rather than introduce pg_format_cast and
CREATE FORMAT CAST.  I still think we should avoid ad-hoc parser rewrites to
specific function names, but the feature scope should be the standard
datetime/string cases, not arbitrary source/target pairs.

I also think it would be useful to retitle this thread around the standard
feature, for example:

    Support SQL feature T839: formatted casts between datetime and
character strings

That seems to describe the real target better than a generic format-cast
facility.

Regards,
Haibo


Re: implement CAST(expr AS type FORMAT 'template')

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Mon, Jul 6, 2026 at 11:56 PM Haibo Yan  wrote:
> I now think my v2 patch is too broad.  It tries to make CAST(... FORMAT ...)
> a generic user-defined format-cast mechanism, but SQL feature T839 is much
> narrower: formatted casts between datetime types and character strings.
>
> So I think the next version should move back closer to Jian’s original scope:
> support T839 first, rather than introduce pg_format_cast and
> CREATE FORMAT CAST.  I still think we should avoid ad-hoc parser rewrites to
> specific function names, but the feature scope should be the standard
> datetime/string cases, not arbitrary source/target pairs.
>
> I also think it would be useful to retitle this thread around the standard
> feature, for example:
>
>     Support SQL feature T839: formatted casts between datetime and
> character strings
>
> That seems to describe the real target better than a generic format-cast
> facility.

My current point of view is that your patch does exactly the right
thing but it's not clear whether we want it. I mean, if we eventually
want to support this feature with arbitrary types, there is no reason
not to do so from the start. Or at least, none that I can see. But
that does not address the question of whether we want the feature in
the first place, which is debatable.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: implement CAST(expr AS type FORMAT 'template')

От:
Peter Eisentraut <peter@eisentraut.org>
Дата:
On 04.07.26 03:09, jian he wrote:
>> I don't really understand the purpose of this feature to begin with.
>> You can already call the formatting functions directly.  Does this cast
>> syntax offer anything on top of that?
>>
> 
> https://www.postgresql.org/message-id/762ae707-7fdc-43d8-a77a-3a10d12ce21d%40postgresfriends.org
> 
> After this implemented, we can begin fully supporting:
> 
>  ::=
>      CAST 
>           AS 
>          [ FORMAT  ]
>          [  ON CONVERSION ERROR ]
>          

The ON CONVERSION ERROR feature is independent of the FORMAT feature, 
isn't it?



Re: implement CAST(expr AS type FORMAT 'template')

От:
Peter Eisentraut <peter@eisentraut.org>
Дата:
On 06.07.26 19:14, Haibo Yan wrote:
> The cases where I think a generic mechanism could be useful are
> broader than that.  For example:
> 
>      text <-> date/time        using datetime templates
>      text <-> numeric          using number templates
>      text <-> bytea            using hex/base64/escape
>      text/bytea <-> extension types
>                            using external representations such as
>                            WKT/WKB/GeoJSON for geometry types
One problem I see is that this would dictate that there is only one 
possible format language for each of these conversions.


Re: implement CAST(expr AS type FORMAT 'template')

От:
Haibo Yan <tristan.yim@gmail.com>
Дата:
On Thu, Jul 9, 2026 at 12:20 AM Peter Eisentraut  wrote:
>
> On 06.07.26 19:14, Haibo Yan wrote:
> > The cases where I think a generic mechanism could be useful are
> > broader than that.  For example:
> >
> >      text <-> date/time        using datetime templates
> >      text <-> numeric          using number templates
> >      text <-> bytea            using hex/base64/escape
> >      text/bytea <-> extension types
> >                            using external representations such as
> >                            WKT/WKB/GeoJSON for geometry types
> One problem I see is that this would dictate that there is only one
> possible format language for each of these conversions.

There are other possible PostgreSQL-extension use cases beyond the standard
datetime/string case, for example bytea encodings, geometry external
representations, UUID display variants, and so on.  But your point is that
these do not necessarily share a single natural FORMAT language for each
source/target pair.

For some of those cases, named functions are probably clearer, especially when
the alternatives are different representation families rather than different
templates within one family.

That seems to argue against making the first version a generic format-cast
facility for arbitrary type pairs.  The safer scope is probably the standard
T839 case first, where the FORMAT clause has a well-defined datetime template
meaning.  We can leave broader PostgreSQL-extension use cases for a later
discussion, if someone can show a model that does not force unrelated
representations through one canonical format function.

Regards,
Haibo


Re: implement CAST(expr AS type FORMAT 'template')

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Thu, Jul 9, 2026 at 3:18 PM Peter Eisentraut  wrote:
>
> On 04.07.26 03:09, jian he wrote:
> >> I don't really understand the purpose of this feature to begin with.
> >> You can already call the formatting functions directly.  Does this cast
> >> syntax offer anything on top of that?
> >>
> >
> > https://www.postgresql.org/message-id/762ae707-7fdc-43d8-a77a-3a10d12ce21d%40postgresfriends.org
> >
> > After this implemented, we can begin fully supporting:
> >
> >  ::=
> >      CAST 
> >           AS 
> >          [ FORMAT  ]
> >          [  ON CONVERSION ERROR ]
> >          
>
> The ON CONVERSION ERROR feature is independent of the FORMAT feature,
> isn't it?
>

Earlier in this thread, the concern was raised that this isn't "generic" enough:
CAST ... FORMAT is just letting the parser produce a FuncExpr, which makes the
whole patch more like a syntax sugar.

In response, people suggested making it more generic. So far we've tried: using
the data type's input/output functions, using the data type's
typformatin/typformatout functions, and introducing a new pg_formatter catalog.
But we haven't agreed on a concrete definition of what a sufficiently generic
and genuinely future-proof approach would look like.

What I'm saying is: even without that generic mechanism settled, having CAST ...
FORMAT producing a FuncExpr still has value on its own. See below.

The attached v12-0001 to v12-0003 is the same as in [1].
v12-0004 is added to demo that CAST(expr AS type FORMAT fmt) is useful
for more than just being syntactic sugar for the existing to_*
functions.
Note: v12-0004 is in a rough but functional state.
With v12-0004, we can now do:

src8=# select cast('2012-13-12' as date format 'YYYY-MM-DD' default
null on conversion error);
 date
------

(1 row)

src8=# select cast('2012-13-12' as date format 'YYYY-MM-DD' );
ERROR:  date/time field value out of range: "2012-13-12"

With this example, I hope I've convinced you that it's still worthwhile to have
the parser build a FuncExpr for CAST ... FORMAT, even though that same FuncExpr
could otherwise be produced by calling the to_* function directly.

[1]: https://www.postgresql.org/message-id/CACJufxGPp23XfP_V9zk7cSDJ6DCZEz4Jo3BUPtPfueNAe%3DC2Hg%40mail.gmail.com




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

Re: implement CAST(expr AS type FORMAT 'template')

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Wed, Jul 15, 2026 at 11:41 AM jian he  wrote:
> We can document that this approach provides an error-safe way to
> evaluate these to_* functions.
> (After we refactored these to_* function to be error safe).

That's true. Of course, we could also just have variants of those
functions that return NULL instead of signaling an error, or whatever
we want the behavior to be.

I don't know what the right thing to do is here. I'm not deeply
opposed to this feature, but I'm not deeply in favor of it either.
There's no big problem with it, but also no particular reason to do
it.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


FAQ