From 7d576f1991adc3f7c96acd8bd9d2e94b402d2b20 Mon Sep 17 00:00:00 2001
From: chenze <chenz@highgo.com>
Date: Fri, 20 Nov 2026 13:36:11 +0800
Subject: [PATCH v2] Handle SQL NULL results from casts in JSON generation

OidFunctionCall1() errors out when a cast to json returns SQL NULL.
Use FunctionCallInvoke() and inspect the result's null flag, keeping
the existing EXECUTE privilege check and execution hook.

When writing an array element or object field, serialize this result
as JSON null, like a SQL NULL argument to the constructor. Preserve
SQL NULL from to_json() and to_jsonb() for a top-level cast result so
callers can distinguish it from a JSON null.

Extend the enum cast test in sqljson.sql to cover both cases.
---
 src/backend/utils/adt/json.c          | 30 +++++++++++++++++----------
 src/backend/utils/adt/jsonb.c         | 29 +++++++++++++++++---------
 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, 107 insertions(+), 23 deletions(-)

diff --git a/src/backend/utils/adt/json.c b/src/backend/utils/adt/json.c
index 1e273160b25..3c78838c3e7 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,18 @@ 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;
+
+		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..cd550544fc2 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,18 @@ 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;
+
+		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: d94964f14f39936d69c6b8d3fc5020f0fdae1617
-- 
2.51.0

