From 57d5fddfdcae1136e9978d140a61584b4de0ad12 Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Sat, 22 Nov 2025 00:08:00 +0800
Subject: [PATCH v19 01/23] error safe for casting bytea to other types per
 pg_cast

select castsource::regtype, casttarget::regtype, castfunc, castcontext,castmethod, pp.prosrc, pp.proname
from pg_cast pc join pg_proc pp on pp.oid = pc.castfunc and pc.castfunc > 0 and castsource::regtype ='bytea'::regtype
order by castsource::regtype;

 castsource | casttarget | castfunc | castcontext | castmethod |   prosrc   | proname
------------+------------+----------+-------------+------------+------------+---------
 bytea      | smallint   |     6370 | e           | f          | bytea_int2 | int2
 bytea      | integer    |     6371 | e           | f          | bytea_int4 | int4
 bytea      | bigint     |     6372 | e           | f          | bytea_int8 | int8
(3 rows)

discussion: https://postgr.es/m/CADkLM=fv1JfY4Ufa-jcwwNbjQixNViskQ8jZu3Tz_p656i_4hQ@mail.gmail.com
---
 src/backend/utils/adt/bytea.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/backend/utils/adt/bytea.c b/src/backend/utils/adt/bytea.c
index fd7662d41ee..a02b054b873 100644
--- a/src/backend/utils/adt/bytea.c
+++ b/src/backend/utils/adt/bytea.c
@@ -1255,7 +1255,7 @@ bytea_int2(PG_FUNCTION_ARGS)
 
 	/* Check that the byte array is not too long */
 	if (len > sizeof(result))
-		ereport(ERROR,
+		ereturn(fcinfo->context, (Datum) 0,
 				errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 				errmsg("smallint out of range"));
 
@@ -1280,7 +1280,7 @@ bytea_int4(PG_FUNCTION_ARGS)
 
 	/* Check that the byte array is not too long */
 	if (len > sizeof(result))
-		ereport(ERROR,
+		ereturn(fcinfo->context, (Datum) 0,
 				errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 				errmsg("integer out of range"));
 
@@ -1305,7 +1305,7 @@ bytea_int8(PG_FUNCTION_ARGS)
 
 	/* Check that the byte array is not too long */
 	if (len > sizeof(result))
-		ereport(ERROR,
+		ereturn(fcinfo->context, (Datum) 0,
 				errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 				errmsg("bigint out of range"));
 
-- 
2.34.1

