Re: pgsql: Add more SQL/JSON constructor functions

From: Peter Eisentraut <peter(at)eisentraut(dot)org>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>, Amit Langote <amitlangote09(at)gmail(dot)com>
Cc: Alvaro Herrera <alvherre(at)alvh(dot)no-ip(dot)org>, pgsql-hackers(at)lists(dot)postgresql(dot)org
Subject: Re: pgsql: Add more SQL/JSON constructor functions
Date: 2024-06-02 21:17:06
Message-ID: 50a780ab-f1a4-4c5f-b9a1-88a174cf12af@eisentraut.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On 29.05.24 18:44, Tom Lane wrote:
> Amit Langote <amitlangote09(at)gmail(dot)com> writes:
>> On Mon, May 27, 2024 at 7:10 PM Alvaro Herrera <alvherre(at)alvh(dot)no-ip(dot)org> wrote:
>>> On 2024-May-27, Alvaro Herrera wrote:
>>> I just noticed this behavior, which looks like a bug to me:
>>>
>>> select json_serialize('{"a":1, "a":2}' returning varchar(5));
>>> json_serialize
>>> ────────────────
>>> {"a":
>>>
>>> I think this function should throw an error if the destination type
>>> doesn't have room for the output json. Otherwise, what good is the
>>> serialization function?
>
>> This behavior comes from using COERCE_EXPLICIT_CAST when creating the
>> coercion expression to convert json_*() functions' argument to the
>> RETURNING type.
>
> Yeah, I too think this is a cast, and truncation is the spec-defined
> behavior for casting to varchar with a specific length limit. I see
> little reason that this should work differently from
>
> select json_serialize('{"a":1, "a":2}' returning text)::varchar(5);
> json_serialize
> ----------------
> {"a":
> (1 row)

The SQL standard says essentially that the output of json_serialize() is
some string that when parsed back in gives you an equivalent JSON value
as the input. That doesn't seem compatible with truncating the output.

If you want output truncation, you can of course use an actual cast.
But it makes sense that the RETURNING clause is separate from that.

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Peter Eisentraut 2024-06-02 21:22:07 Re: Switch background worker on/off in runtime.
Previous Message Ranier Vilela 2024-06-02 21:14:33 Re: Avoid an odd undefined behavior with memcmp (src/bin/pg_rewind/pg_rewind.c)