Re: Why does to_json take "anyelement" rather than "any"?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Nikhil Benesch <nikhil(dot)benesch(at)gmail(dot)com>
Cc: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>, Mohamed Wael Khobalatte <mkhobalatte(at)grubhub(dot)com>, PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: Why does to_json take "anyelement" rather than "any"?
Date: 2020-11-06 01:58:57
Message-ID: 1535550.1604627937@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Nikhil Benesch <nikhil(dot)benesch(at)gmail(dot)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 rules of polymorphism apply when performing a lookup.  My uninformed conclusion is that since to_json only defines a single parameter 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

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message kuroda.hayato@fujitsu.com 2020-11-06 02:15:10 RE: pgbench: option delaying queries till connections establishment?
Previous Message Nikhil Benesch 2020-11-06 01:45:37 Re: Why does to_json take "anyelement" rather than "any"?