Re: [PATCH] Handle SQL NULL results from casts in JSON generation

From: Andreas Karlsson <andreas(at)proxel(dot)se>
To: Neil Chen <carpenter(dot)nail(dot)cz(at)gmail(dot)com>, Postgres hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: [PATCH] Handle SQL NULL results from casts in JSON generation
Date: 2026-12-03 04:56:30
Message-ID: a6029885-50f1-43cb-a2e5-14596f071942@proxel.se
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On 11/20/26 4:36 AM, Neil Chen wrote:
> I hit an error on 19.0 and master (a20d50a00ed) with a cast to json
> that returns SQL NULL for a non-NULL input.
>
> CREATE TYPE json_cast_flag AS ENUM ('unset');
>
> CREATE FUNCTION json_cast_flag_to_json(json_cast_flag) RETURNS json
> LANGUAGE sql AS $$ SELECT NULL::json $$;
>
> CREATE CAST (json_cast_flag AS json)
> WITH FUNCTION json_cast_flag_to_json(json_cast_flag);
>
> SELECT json_build_array(NULL); -- [null]
> SELECT ('unset'::json_cast_flag::json) IS NULL; -- t
> SELECT json_build_array('unset'::json_cast_flag::json); -- [null]
>
> SELECT json_build_array('unset'::json_cast_flag); -- error
> SELECT jsonb_build_array('unset'::json_cast_flag); -- error
>
> The last two queries fail with "function returned NULL".

Hi,

Does it actually make sense for a cast to return NULL? I personally
would prefer the error message and if PostgreSQL had been designed from
scratch that casts are not even allowed to return NULL. So now I am
curious: what is your use case for a cast which returns NULL? If you
want to return a JSON null the proper way to do that is the below, but I
do not see any use case for returning an SQL NULL.

CREATE FUNCTION json_cast_flag_to_json(json_cast_flag) RETURNS json
LANGUAGE sql AS $$ SELECT 'null'::json $$;

--
Andreas Karlsson
Percona

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Hüseyin Demir 2026-12-03 05:13:12 Re: [PATCH] Report changes discarded for relations not in the subscription
Previous Message Narayanan Venkateswaran 2026-12-03 04:54:51 Re: Fix LogStandbySnapshot() race during logical decoding activation