From 9565a08b51eb88d6bfc411b35ac45d41965bc2c7 Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Sat, 22 Nov 2025 00:13:45 +0800
Subject: [PATCH v16 05/23] error safe for casting character varying 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 = 'character varying'::regtype)
order by castsource::regtype;

    castsource     |    casttarget     | castfunc | castcontext | castmethod |    prosrc     | proname
-------------------+-------------------+----------+-------------+------------+---------------+----------
 character varying | regclass          |     1079 | i           | f          | text_regclass | regclass
 character varying | "char"            |      944 | a           | f          | text_char     | char
 character varying | name              |     1400 | i           | f          | text_name     | name
 character varying | xml               |     2896 | e           | f          | texttoxml     | xml
 character varying | character varying |      669 | i           | f          | varchar       | varchar
(5 rows)

texttoxml, text_regclass was refactored as error safe in prior patch.
text_char, text_name is already error safe.
so here we only need handle function "varchar".

discussion: https://postgr.es/m/CADkLM=fv1JfY4Ufa-jcwwNbjQixNViskQ8jZu3Tz_p656i_4hQ@mail.gmail.com
---
 src/backend/utils/adt/varchar.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/backend/utils/adt/varchar.c b/src/backend/utils/adt/varchar.c
index 8618c7a1b13..e853e0d7dbb 100644
--- a/src/backend/utils/adt/varchar.c
+++ b/src/backend/utils/adt/varchar.c
@@ -634,7 +634,7 @@ varchar(PG_FUNCTION_ARGS)
 	{
 		for (i = maxmblen; i < len; i++)
 			if (s_data[i] != ' ')
-				ereport(ERROR,
+				ereturn(fcinfo->context, (Datum) 0,
 						(errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
 						 errmsg("value too long for type character varying(%d)",
 								maxlen)));
-- 
2.34.1

