Skip to content

Commit

Permalink
Fix(optimizer): handle subquery predicate substitution correctly in d…
Browse files Browse the repository at this point in the history
…e morgan's rule (#4240)
  • Loading branch information
georgesittas authored Oct 14, 2024
1 parent 5741180 commit daa6e78
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
14 changes: 11 additions & 3 deletions sqlglot/optimizer/simplify.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,11 @@ def rewrite_between(expression: exp.Expression) -> exp.Expression:
exp.NEQ: exp.EQ,
}

COMPLEMENT_SUBQUERY_PREDICATES = {
exp.All: exp.Any,
exp.Any: exp.All,
}


def simplify_not(expression):
"""
Expand All @@ -218,9 +223,12 @@ def simplify_not(expression):
if is_null(this):
return exp.null()
if this.__class__ in COMPLEMENT_COMPARISONS:
return COMPLEMENT_COMPARISONS[this.__class__](
this=this.this, expression=this.expression
)
right = this.expression
complement_subquery_predicate = COMPLEMENT_SUBQUERY_PREDICATES.get(right.__class__)
if complement_subquery_predicate:
right = complement_subquery_predicate(this=right.this)

return COMPLEMENT_COMPARISONS[this.__class__](this=this.this, expression=right)
if isinstance(this, exp.Paren):
condition = this.unnest()
if isinstance(condition, exp.And):
Expand Down
3 changes: 3 additions & 0 deletions tests/fixtures/optimizer/simplify.sql
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ TRUE;
COALESCE(x, y) <> ALL (SELECT z FROM w);
COALESCE(x, y) <> ALL (SELECT z FROM w);

SELECT NOT (2 <> ALL (SELECT 2 UNION ALL SELECT 3));
SELECT 2 = ANY(SELECT 2 UNION ALL SELECT 3);

--------------------------------------
-- Absorption
--------------------------------------
Expand Down

0 comments on commit daa6e78

Please sign in to comment.