From d7304244e26b92d533f7e44f0afbcf1ff2f46286 Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Fri, 12 Nov 2010 15:14:51 -0500
Subject: [PATCH] Fix old oversight in const-simplification of COALESCE()
 expressions.

Once we have found a non-null constant argument, there is no need to
examine additional arguments of the COALESCE.  The previous coding got it
right only if the constant was in the first argument position; otherwise
it tried to simplify following arguments too, leading to unexpected
behavior like this:

regression=# select coalesce(f1, 42, 1/0) from int4_tbl;
ERROR:  division by zero

It's a minor corner case, but a bug is a bug, so back-patch all the way.
---
 src/backend/optimizer/util/clauses.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c
index e948bccc1a2..de2e66b0f16 100644
--- a/src/backend/optimizer/util/clauses.c
+++ b/src/backend/optimizer/util/clauses.c
@@ -2746,7 +2746,9 @@ eval_const_expressions_mutator(Node *node,
 			/*
 			 * We can remove null constants from the list. For a non-null
 			 * constant, if it has not been preceded by any other
-			 * non-null-constant expressions then that is the result.
+			 * non-null-constant expressions then it is the result.  Otherwise,
+			 * it's the next argument, but we can drop following arguments
+			 * since they will never be reached.
 			 */
 			if (IsA(e, Const))
 			{
@@ -2754,6 +2756,8 @@ eval_const_expressions_mutator(Node *node,
 					continue;	/* drop null constant */
 				if (newargs == NIL)
 					return e;	/* first expr */
+				newargs = lappend(newargs, e);
+				break;
 			}
 			newargs = lappend(newargs, e);
 		}
-- 
GitLab