From: | Mohamed Wael Khobalatte <mkhobalatte(at)grubhub(dot)com> |
---|---|
To: | Nikhil Benesch <nikhil(dot)benesch(at)gmail(dot)com> |
Cc: | pgsql-hackers(at)lists(dot)postgresql(dot)org |
Subject: | Re: Why does to_json take "anyelement" rather than "any"? |
Date: | 2020-11-05 22:42:47 |
Message-ID: | CABZeWdwoR9UGJuLEMg7HxfboYUH_MX+yWq6e6DicW+WCKj7bpg@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-hackers |
On Tue, Nov 3, 2020 at 11:54 AM Nikhil Benesch <nikhil(dot)benesch(at)gmail(dot)com>
wrote:
> to_json is declared as taking "anyelement" as input, which means
> you can't pass it something of unknown type:
>
> postgres=# SELECT to_json('foo');
> ERROR: could not determine polymorphic type because input has type
> unknown
>
> But this works fine with the very similar json_build_array function:
>
> postgres=# SELECT json_build_array('foo');
> json_build_array
> ------------------
> ["foo"]
> (1 row)
>
> The difference is that json_build_array takes type "any" as input, while
> to_json takes "anyelement" as input.
>
> Is there some reason to_json couldn't be switched to take "any" as input?
> Hacking this together seems to mostly just work:
>
> postgres=# CREATE FUNCTION my_to_json ("any") RETURNS json LANGUAGE
> 'internal' AS 'to_json';
> postgres=# SELECT my_to_json('foo');
> my_to_json
> ------------
> "foo"
> (1 row)
>
> Is there something I'm missing?
>
> Nikhil
>
>
Hm, good question. I am also curious as to why this happens.
`json_build_array` ends up casting unknowns to text (from reading the
code), which seems like a reasonable (although not completely tight)
assumption. Not sure why `to_json` can't just do the same. You can always
cast to text yourself, of course, but I am not familiar with the type
hierarchy enough to tell why `to_json` can't deduce that as text whereas
the other function can.
From | Date | Subject | |
---|---|---|---|
Next Message | Thomas Munro | 2020-11-05 23:31:52 | Re: [Patch] Optimize dropping of relation buffers using dlist |
Previous Message | David Rowley | 2020-11-05 22:12:33 | Re: Hybrid Hash/Nested Loop joins and caching results from subplans |