| From: | Neil Chen <carpenter(dot)nail(dot)cz(at)gmail(dot)com> |
|---|---|
| To: | Postgres hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org> |
| Subject: | [PATCH] Handle SQL NULL results from casts in JSON generation |
| Date: | 2026-11-20 03:36:29 |
| Message-ID: | CAA3qoJkQmpzv3tkqh=b9u6B6G-+3ZCRTgCXy+ussRQ-bWDqCHA@mail.gmail.com |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-hackers |
Hi,
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".
I'd expect both to return [null], just like the explicit-cast query
above. The constructors already handle a SQL NULL argument this way,
and both paths use the same cast function [1].
OidFunctionCall1() treats a NULL result as an error. The patch calls
the cast with FunctionCallInvoke(), checks fcinfo->isnull, and writes
a JSON null for that result. The EXECUTE check and hook still run.
COPY TO (FORMAT json) hits the same error and can leave an unfinished
array with FORCE_ARRAY. COPY already writes JSON null for SQL NULL
fields [2].
With the patch, to_json('unset'::json_cast_flag) IS NULL is false.
Adding ::json to the argument makes the same test true. Should
to_json() and to_jsonb() return SQL NULL for this top-level case?
The patch extends the enum cast test in sqljson.sql. make check
passed on patched master (243 tests).
Thanks,
[1]
https://www.postgresql.org/docs/19/functions-json.html#FUNCTIONS-JSON-CREATION-TABLE
[2] https://www.postgresql.org/docs/19/sql-copy.html#SQL-COPY-PARAMS-FORMAT
--
Ze Chen (Neil)
HighGo Software Co., Ltd.
https://www.highgo.com/
| Attachment | Content-Type | Size |
|---|---|---|
| v1-0001-Handle-SQL-NULL-results-from-casts-in-JSON-generation.patch | text/x-patch | 8.5 KB |
| From | Date | Subject | |
|---|---|---|---|
| Next Message | shveta malik | 2026-11-20 03:39:38 | Re: Proposal: Conflict log history table for Logical Replication |
| Previous Message | David Rowley | 2026-11-20 03:33:28 | Re: Hash aggregate collisions cause excessive spilling |