From 2ab6fb58e81c7a0fe583299b2e967a9ca6eaa6f5 Mon Sep 17 00:00:00 2001
From: chenze <chenz@highgo.com>
Date: Fri, 20 Nov 2026 10:47:10 +0800
Subject: [PATCH v1] Handle SQL NULL results from casts in JSON generation

JSON and JSONB generation use OidFunctionCall1() to invoke casts to
json. That interface raises an error if the cast function returns SQL
NULL, even though an explicit cast can return it successfully.

Use FunctionCallInvoke() to detect a NULL result and emit JSON null.
Keep the existing EXECUTE privilege check and execution hook in the
common cast invocation helper.

Extend the existing enum cast test in sqljson.sql to cover nullable
cast results in both JSON and JSONB constructors.
---
 src/backend/utils/adt/json.c          | 18 +++++++---------
 src/backend/utils/adt/jsonb.c         | 17 +++++++--------
 src/backend/utils/adt/jsonfuncs.c     | 30 +++++++++++++++++++++++++++
 src/include/utils/jsonfuncs.h         |  1 +
 src/test/regress/expected/sqljson.out | 10 ++++++++-
 src/test/regress/sql/sqljson.sql      |  7 ++++++-
 6 files changed, 60 insertions(+), 23 deletions(-)

diff --git a/src/backend/utils/adt/json.c b/src/backend/utils/adt/json.c
index 1e273160b25..df525ace53e 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);
diff --git a/src/backend/utils/adt/jsonb.c b/src/backend/utils/adt/jsonb.c
index 8a22d177414..653d91c89ca 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:
 				{
diff --git a/src/backend/utils/adt/jsonfuncs.c b/src/backend/utils/adt/jsonfuncs.c
index 25f14f92370..b3be3fb4cc1 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 the caller serializes as a JSON null.
+ */
+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..b6d81728502 100644
--- a/src/test/regress/expected/sqljson.out
+++ b/src/test/regress/expected/sqljson.out
@@ -602,11 +602,19 @@ 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 WHEN $1 <> 'neutral' THEN 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)
+
 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..6165712a86d 100644
--- a/src/test/regress/sql/sqljson.sql
+++ b/src/test/regress/sql/sqljson.sql
@@ -167,10 +167,15 @@ 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 WHEN $1 <> 'neutral' THEN 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;
+
 DROP CAST (mood AS json);
 DROP FUNCTION mood_to_json;
 DROP TYPE mood;

base-commit: a20d50a00edc40ff11b08b1e3e3be6e4f9da51f6
-- 
2.51.0

