Skip to content

Commit 87c94fe

Browse files
committed
Fix(redshift)!: turn off multi-arg coalesce simplification (#4877)
1 parent 92e479e commit 87c94fe

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

sqlglot/optimizer/simplify.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def _simplify(expression, root=True):
117117
node = flatten(node)
118118
node = simplify_connectors(node, root)
119119
node = remove_complements(node, root)
120-
node = simplify_coalesce(node)
120+
node = simplify_coalesce(node, dialect)
121121
node.parent = expression.parent
122122
node = simplify_literals(node, root)
123123
node = simplify_equality(node)
@@ -775,7 +775,7 @@ def _is_constant(expression: exp.Expression) -> bool:
775775
return isinstance(expression, exp.CONSTANTS) or _is_date_literal(expression)
776776

777777

778-
def simplify_coalesce(expression):
778+
def simplify_coalesce(expression: exp.Expression, dialect: DialectType) -> exp.Expression:
779779
# COALESCE(x) -> x
780780
if (
781781
isinstance(expression, exp.Coalesce)
@@ -785,6 +785,12 @@ def simplify_coalesce(expression):
785785
):
786786
return expression.this
787787

788+
# We can't convert `COALESCE(x, 1) = 2` into `NOT x IS NULL AND x = 2` for redshift,
789+
# because they are not always equivalent. For example, if `x` is `NULL` and it comes
790+
# from a table, then the result is `NULL`, despite `FALSE AND NULL` evaluating to `FALSE`
791+
if dialect == "redshift":
792+
return expression
793+
788794
if not isinstance(expression, COMPARISONS):
789795
return expression
790796

tests/fixtures/optimizer/simplify.sql

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -843,6 +843,10 @@ x;
843843
COALESCE(x, 1) = 2;
844844
NOT x IS NULL AND x = 2;
845845

846+
# dialect: redshift
847+
COALESCE(x, 1) = 2;
848+
COALESCE(x, 1) = 2;
849+
846850
2 = COALESCE(x, 1);
847851
NOT x IS NULL AND x = 2;
848852

0 commit comments

Comments
 (0)