From 3c3fb2160c4ff51520c9cb12b8a48c61b44cfb3e Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Fri, 29 Aug 2008 17:27:50 +0000
Subject: [PATCH] Fix bug in original implementation of xmlserialize(): if user
 specifies a target type that isn't acceptable, the code failed to raise the
 proper error.  The result instead was to return a NULL expression tree, which
 in a quick test led to a 'cache lookup failed for type 0' error later.

Patch 8.3 only --- I fixed this in HEAD as part of recent locations patch.
---
 src/backend/parser/parse_expr.c | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index d43d38c494..e174325c5e 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $PostgreSQL: pgsql/src/backend/parser/parse_expr.c,v 1.226 2008/01/01 19:45:50 momjian Exp $
+ *	  $PostgreSQL: pgsql/src/backend/parser/parse_expr.c,v 1.226.2.1 2008/08/29 17:27:50 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -1539,9 +1539,10 @@ transformXmlExpr(ParseState *pstate, XmlExpr *x)
 static Node *
 transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
 {
+	Node	   *result;
+	XmlExpr    *xexpr;
 	Oid			targetType;
 	int32		targetTypmod;
-	XmlExpr    *xexpr;
 
 	xexpr = makeNode(XmlExpr);
 	xexpr->op = IS_XMLSERIALIZE;
@@ -1563,8 +1564,15 @@ transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
 	 * from text.  This way, user-defined text-like data types automatically
 	 * fit in.
 	 */
-	return (Node *) coerce_to_target_type(pstate, (Node *) xexpr, TEXTOID, targetType, targetTypmod,
-									COERCION_IMPLICIT, COERCE_IMPLICIT_CAST);
+	result = coerce_to_target_type(pstate, (Node *) xexpr,
+								   TEXTOID, targetType, targetTypmod,
+								   COERCION_IMPLICIT, COERCE_IMPLICIT_CAST);
+	if (result == NULL)
+		ereport(ERROR,
+				(errcode(ERRCODE_CANNOT_COERCE),
+				 errmsg("cannot cast XMLSERIALIZE result to %s",
+						format_type_be(targetType))));
+	return result;
 }
 
 static Node *
-- 
2.40.0