Re: Why does to_json take "anyelement" rather than "any"? - Mailing list pgsql-hackers

From Tom Lane
Subject Re: Why does to_json take "anyelement" rather than "any"?
Date
Msg-id 1535550.1604627937@sss.pgh.pa.us
Whole thread Raw
In response to Re: Why does to_json take "anyelement" rather than "any"?  (Nikhil Benesch <nikhil.benesch@gmail.com>)
Responses Re: Why does to_json take "anyelement" rather than "any"?  (Nikhil Benesch <nikhil.benesch@gmail.com>)
List pgsql-hackers
Nikhil Benesch <nikhil.benesch@gmail.com> writes:
> On 11/5/20 7:38 PM, David G. Johnston wrote:
>> My understanding is that "any" is defined to accept that behavior - allowing any pseudo-type and unknown.  The
"anyelement"polymorphic pseudo-type is defined such that only concrete known types are allowed to match - and then the
rulesof polymorphism apply when performing a lookup.  My uninformed conclusion is that since to_json only defines a
singleparameter that changing it from "anyelement" to "any" would be reasonable and the hack describe probably "just
works"(though I'd test it on a wide-range of built-in types first if I was actually going to use the hack). 
>>
>> You only get to use "any" for a C-language function but that is indeed the case here.

> That exactly matches my understanding as well. I'll put together a patch.

"any" is a dinosaur IMO.  It's definitely lower-level than anyelement;
for example the function has to be prepared to deal with raw "unknown"
literals.  So I feel like the proposed solution here is a bit of a hack.

What I'm wondering about as I think about this is why we don't allow
unknown literals to be resolved as text when matching to anyelement.
Maybe that was intentional, or maybe just overly conservative; or maybe
there is a good reason for it.  I don't recall, but it would be worth
excavating in the list archives to see if it was discussed when the
polymorphic types were being designed.

A relevant data point is that we *do* allow the case with the more
recently added "anycompatible" polymorphics:

regression=# create function foo(anycompatible) returns anycompatible as 'select $1' language sql;
CREATE FUNCTION
regression=# select foo('bar');
 foo
-----
 bar
(1 row)

regression=# select pg_typeof(foo('bar'));
 pg_typeof
-----------
 text
(1 row)

So even if we decide that changing the rules for "anyelement" is
too scary, I think switching to_json to anycompatible would be
preferable to switching it to "any".

            regards, tom lane



pgsql-hackers by date:

Previous
From: Nikhil Benesch
Date:
Subject: Re: Why does to_json take "anyelement" rather than "any"?
Next
From: "kuroda.hayato@fujitsu.com"
Date:
Subject: RE: pgbench: option delaying queries till connections establishment?