From b1858411c2d865cda1ff07bd005eb5380e2b4d03 Mon Sep 17 00:00:00 2001
From: Neil Chen <carpenter.nail.cz@gmail.com>
Date: Wed, 2 Dec 2026 14:19:51 +0800
Subject: [PATCH v3] Handle SQL NULL results from casts in JSON generation

A cast to json can return SQL NULL for a non-null input. The JSON
conversion code calls such casts via OidFunctionCall1(), which errors
on a null result. This affects constructors and COPY TO (FORMAT json),
which can leave an unfinished array when FORCE_ARRAY is used.

Invoke the cast with FunctionCallInvoke() and inspect its null flag,
while retaining the EXECUTE privilege check and execution hook. Write
JSON null when serializing an array element or object value, just as
for a SQL NULL input. Have to_json() and to_jsonb() instead return SQL
NULL for a top-level cast result, consistent with an explicit cast to
json and distinct from a JSON null. Keep the stack-depth check before
invoking the cast in both top-level functions.

Extend the existing enum cast test to cover array construction and the
distinction between SQL NULL and JSON null in top-level conversions.

Author: Neil Chen <carpenter.nail.cz@gmail.com>
Reviewed-by: Yuefei Shi <shiyuefei1004@gmail.com>
---
 src/backend/utils/adt/json.c          | 31 +++++++++++++++++----------
 src/backend/utils/adt/jsonb.c         | 30 +++++++++++++++++---------
 src/backend/utils/adt/jsonfuncs.c     | 30 ++++++++++++++++++++++++++
 src/include/utils/jsonfuncs.h         |  1 +
 src/test/regress/expected/sqljson.out | 24 ++++++++++++++++++++-
 src/test/regress/sql/sqljson.sql      | 16 +++++++++++++-
 6 files changed, 109 insertions(+), 23 deletions(-)

diff --git a/src/backend/utils/adt/json.c b/src/backend/utils/adt/json.c
index 1e273160b25..dc5b03e86ae 100644
--- a/src/backend/utils/adt/json.c
+++ b/src/backend/utils/adt/json.c
@@ -14,7 +14,6 @@
 #include "postgres.h"
 
 #include "access/htup_details.h"
-#include "catalog/objectaccess.h"
 #include "catalog/pg_proc.h"
 #include "catalog/pg_type.h"
 #include "common/hashfn.h"
@@ -22,7 +21,6 @@
 #include "libpq/pqformat.h"
 #include "miscadmin.h"
 #include "port/simd.h"
-#include "utils/acl.h"
 #include "utils/array.h"
 #include "utils/builtins.h"
 #include "utils/date.h"
@@ -184,7 +182,6 @@ datum_to_json_internal(Datum val, bool is_null, StringInfo result,
 {
 	char	   *outputstr;
 	text	   *jsontext;
-	AclResult	aclresult;
 
 	check_stack_depth();
 
@@ -283,14 +280,13 @@ datum_to_json_internal(Datum val, bool is_null, StringInfo result,
 			pfree(outputstr);
 			break;
 		case JSONTYPE_CAST:
-			/* outfuncoid refers to a cast function, not an output function */
-			aclresult = object_aclcheck(ProcedureRelationId, outfuncoid,
-										GetUserId(), ACL_EXECUTE);
-			if (aclresult != ACLCHECK_OK)
-				aclcheck_error(aclresult, OBJECT_FUNCTION,
-							   get_func_name(outfuncoid));
-			InvokeFunctionExecuteHook(outfuncoid);
-			jsontext = DatumGetTextPP(OidFunctionCall1(outfuncoid, val));
+			val = json_invoke_cast(outfuncoid, val, &is_null);
+			if (is_null)
+			{
+				appendBinaryStringInfo(result, "null", strlen("null"));
+				break;
+			}
+			jsontext = DatumGetTextPP(val);
 			appendBinaryStringInfo(result, VARDATA_ANY(jsontext),
 								   VARSIZE_ANY_EXHDR(jsontext));
 			pfree(jsontext);
@@ -761,6 +757,19 @@ to_json(PG_FUNCTION_ARGS)
 	json_categorize_type(val_type, false,
 						 &tcategory, &outfuncoid);
 
+	/* Preserve a top-level cast's SQL NULL result. */
+	if (tcategory == JSONTYPE_CAST)
+	{
+		bool		isnull;
+
+		check_stack_depth();
+		val = json_invoke_cast(outfuncoid, val, &isnull);
+		if (isnull)
+			PG_RETURN_NULL();
+
+		PG_RETURN_DATUM(val);
+	}
+
 	PG_RETURN_DATUM(datum_to_json(val, tcategory, outfuncoid));
 }
 
diff --git a/src/backend/utils/adt/jsonb.c b/src/backend/utils/adt/jsonb.c
index 8a22d177414..1b5a32f3b40 100644
--- a/src/backend/utils/adt/jsonb.c
+++ b/src/backend/utils/adt/jsonb.c
@@ -13,13 +13,11 @@
 #include "postgres.h"
 
 #include "access/htup_details.h"
-#include "catalog/objectaccess.h"
 #include "catalog/pg_proc.h"
 #include "catalog/pg_type.h"
 #include "funcapi.h"
 #include "libpq/pqformat.h"
 #include "miscadmin.h"
-#include "utils/acl.h"
 #include "utils/builtins.h"
 #include "utils/fmgroids.h"
 #include "utils/json.h"
@@ -639,7 +637,6 @@ datum_to_jsonb_internal(Datum val, bool is_null, JsonbInState *result,
 	bool		numeric_to_string;
 	JsonbValue	jb;
 	bool		scalar_jsonb = false;
-	AclResult	aclresult;
 
 	check_stack_depth();
 
@@ -774,13 +771,13 @@ datum_to_jsonb_internal(Datum val, bool is_null, JsonbInState *result,
 				break;
 			case JSONTYPE_CAST:
 				/* cast to JSON, and then process as JSON */
-				aclresult = object_aclcheck(ProcedureRelationId, outfuncoid,
-											GetUserId(), ACL_EXECUTE);
-				if (aclresult != ACLCHECK_OK)
-					aclcheck_error(aclresult, OBJECT_FUNCTION,
-								   get_func_name(outfuncoid));
-				InvokeFunctionExecuteHook(outfuncoid);
-				val = OidFunctionCall1(outfuncoid, val);
+				val = json_invoke_cast(outfuncoid, val, &is_null);
+				if (is_null)
+				{
+					/* Let the scalar insertion code below emit JSON null. */
+					jb.type = jbvNull;
+					break;
+				}
 				pg_fallthrough;
 			case JSONTYPE_JSON:
 				{
@@ -1146,6 +1143,19 @@ to_jsonb(PG_FUNCTION_ARGS)
 	json_categorize_type(val_type, true,
 						 &tcategory, &outfuncoid);
 
+	/* Preserve a top-level cast's SQL NULL result. */
+	if (tcategory == JSONTYPE_CAST)
+	{
+		bool		isnull;
+
+		check_stack_depth();
+		val = json_invoke_cast(outfuncoid, val, &isnull);
+		if (isnull)
+			PG_RETURN_NULL();
+
+		PG_RETURN_DATUM(datum_to_jsonb(val, JSONTYPE_JSON, F_JSON_OUT));
+	}
+
 	PG_RETURN_DATUM(datum_to_jsonb(val, tcategory, outfuncoid));
 }
 
diff --git a/src/backend/utils/adt/jsonfuncs.c b/src/backend/utils/adt/jsonfuncs.c
index 25f14f92370..28b5200d504 100644
--- a/src/backend/utils/adt/jsonfuncs.c
+++ b/src/backend/utils/adt/jsonfuncs.c
@@ -17,6 +17,8 @@
 #include <limits.h>
 
 #include "access/htup_details.h"
+#include "catalog/objectaccess.h"
+#include "catalog/pg_proc.h"
 #include "catalog/pg_type.h"
 #include "common/int.h"
 #include "common/jsonapi.h"
@@ -28,6 +30,7 @@
 #include "miscadmin.h"
 #include "nodes/miscnodes.h"
 #include "parser/parse_coerce.h"
+#include "utils/acl.h"
 #include "utils/array.h"
 #include "utils/builtins.h"
 #include "utils/fmgroids.h"
@@ -5989,6 +5992,33 @@ json_get_first_token(text *json, bool throw_error)
 	return JSON_TOKEN_INVALID;	/* invalid json */
 }
 
+/*
+ * Invoke a type-to-JSON cast for a non-null input.  The cast itself may
+ * return SQL NULL, which is reported via isnull.
+ */
+Datum
+json_invoke_cast(Oid castfunc, Datum val, bool *isnull)
+{
+	LOCAL_FCINFO(fcinfo, 1);
+	FmgrInfo	flinfo;
+	AclResult	aclresult;
+	Datum		result;
+
+	aclresult = object_aclcheck(ProcedureRelationId, castfunc,
+								GetUserId(), ACL_EXECUTE);
+	if (aclresult != ACLCHECK_OK)
+		aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(castfunc));
+	InvokeFunctionExecuteHook(castfunc);
+
+	fmgr_info(castfunc, &flinfo);
+	InitFunctionCallInfoData(*fcinfo, &flinfo, 1, InvalidOid, NULL, NULL);
+	fcinfo->args[0].value = val;
+	fcinfo->args[0].isnull = false;
+	result = FunctionCallInvoke(fcinfo);
+	*isnull = fcinfo->isnull;
+	return result;
+}
+
 /*
  * Determine how we want to print values of a given type in datum_to_json(b).
  *
diff --git a/src/include/utils/jsonfuncs.h b/src/include/utils/jsonfuncs.h
index 636f0f55840..63e6f41a13f 100644
--- a/src/include/utils/jsonfuncs.h
+++ b/src/include/utils/jsonfuncs.h
@@ -83,6 +83,7 @@ typedef enum
 
 extern void json_categorize_type(Oid typoid, bool is_jsonb,
 								 JsonTypeCategory *tcategory, Oid *outfuncoid);
+extern Datum json_invoke_cast(Oid castfunc, Datum val, bool *isnull);
 extern Datum datum_to_json(Datum val, JsonTypeCategory tcategory,
 						   Oid outfuncoid);
 extern Datum datum_to_jsonb(Datum val, JsonTypeCategory tcategory,
diff --git a/src/test/regress/expected/sqljson.out b/src/test/regress/expected/sqljson.out
index 1085475541b..e497fc51a99 100644
--- a/src/test/regress/expected/sqljson.out
+++ b/src/test/regress/expected/sqljson.out
@@ -602,11 +602,33 @@ DROP FUNCTION json_object_inline_test(text);
 -- datum_to_jsonb_internal() didn't catch keys that are casts instead of a simple scalar
 CREATE TYPE mood AS ENUM ('happy', 'sad', 'neutral');
 CREATE FUNCTION mood_to_json(mood) RETURNS json AS $$
-  SELECT to_json($1::text);
+  SELECT CASE $1
+           WHEN 'neutral' THEN NULL::json
+           WHEN 'sad' THEN 'null'::json
+           ELSE to_json($1::text)
+         END;
 $$ LANGUAGE sql IMMUTABLE;
 CREATE CAST (mood AS json) WITH FUNCTION mood_to_json(mood) AS IMPLICIT;
 SELECT JSON_OBJECT('happy'::mood: '123'::jsonb);
 ERROR:  key value must be scalar, not array, composite, or json
+-- A cast can return SQL NULL for a non-null input.
+SELECT json_build_array('happy'::mood, 'neutral'::mood) AS j,
+       jsonb_build_array('happy'::mood, 'neutral'::mood) AS jb;
+        j        |       jb        
+-----------------+-----------------
+ ["happy", null] | ["happy", null]
+(1 row)
+
+-- Top-level conversions distinguish SQL NULL from JSON null.
+SELECT m, to_json(m) IS NULL AS j, to_jsonb(m) IS NULL AS jb
+FROM (VALUES ('neutral'::mood), ('sad')) AS v(m)
+ORDER BY m;
+    m    | j | jb 
+---------+---+----
+ sad     | f | f
+ neutral | t | t
+(2 rows)
+
 DROP CAST (mood AS json);
 DROP FUNCTION mood_to_json;
 DROP TYPE mood;
diff --git a/src/test/regress/sql/sqljson.sql b/src/test/regress/sql/sqljson.sql
index 43106fdda96..a50d2003bb7 100644
--- a/src/test/regress/sql/sqljson.sql
+++ b/src/test/regress/sql/sqljson.sql
@@ -167,10 +167,24 @@ DROP FUNCTION json_object_inline_test(text);
 -- datum_to_jsonb_internal() didn't catch keys that are casts instead of a simple scalar
 CREATE TYPE mood AS ENUM ('happy', 'sad', 'neutral');
 CREATE FUNCTION mood_to_json(mood) RETURNS json AS $$
-  SELECT to_json($1::text);
+  SELECT CASE $1
+           WHEN 'neutral' THEN NULL::json
+           WHEN 'sad' THEN 'null'::json
+           ELSE to_json($1::text)
+         END;
 $$ LANGUAGE sql IMMUTABLE;
 CREATE CAST (mood AS json) WITH FUNCTION mood_to_json(mood) AS IMPLICIT;
 SELECT JSON_OBJECT('happy'::mood: '123'::jsonb);
+
+-- A cast can return SQL NULL for a non-null input.
+SELECT json_build_array('happy'::mood, 'neutral'::mood) AS j,
+       jsonb_build_array('happy'::mood, 'neutral'::mood) AS jb;
+
+-- Top-level conversions distinguish SQL NULL from JSON null.
+SELECT m, to_json(m) IS NULL AS j, to_jsonb(m) IS NULL AS jb
+FROM (VALUES ('neutral'::mood), ('sad')) AS v(m)
+ORDER BY m;
+
 DROP CAST (mood AS json);
 DROP FUNCTION mood_to_json;
 DROP TYPE mood;

base-commit: fbbb2e05600828b5a38a9a7a701a9339a270b697
-- 
2.51.0

