Skip to content

Commit

Permalink
Feat: add math associativity simplification
Browse files Browse the repository at this point in the history
  • Loading branch information
tobymao committed May 13, 2023
1 parent 4601831 commit 31a82cc
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
20 changes: 12 additions & 8 deletions sqlglot/optimizer/simplify.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,14 +388,18 @@ def _simplify_binary(expression, a, b):


def simplify_parens(expression):
if (
isinstance(expression, exp.Paren)
and not isinstance(expression.this, exp.Select)
and (
not isinstance(expression.parent, (exp.Condition, exp.Binary))
or isinstance(expression.this, exp.Predicate)
or not isinstance(expression.this, exp.Binary)
)
if not isinstance(expression, exp.Paren):
return expression

this = expression.this
parent = expression.parent

if not isinstance(this, exp.Select) and (
not isinstance(parent, (exp.Condition, exp.Binary))
or isinstance(this, exp.Predicate)
or not isinstance(this, exp.Binary)
or (isinstance(this, exp.Add) and isinstance(parent, exp.Add))
or (isinstance(this, exp.Mul) and isinstance(parent, exp.Mul))
):
return expression.this
return expression
Expand Down
17 changes: 16 additions & 1 deletion tests/fixtures/optimizer/simplify.sql
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,21 @@ A AND B AND C AND D;
(((((A) AND B)) AND C)) AND D;
A AND B AND C AND D;

(x + 1) + 2;
x + 3;

x + (1 + 2);
x + 3;

(x * 2) * 4 + (1 + 3) + 5;
x * 8 + 9;

(x - 1) - 2;
(x - 1) - 2;

x - (3 - 2);
x - 1;

--------------------------------------
-- Comparison and Pruning
--------------------------------------
Expand Down Expand Up @@ -574,4 +589,4 @@ x > 3;
TRUE;

x = 2018 OR x <> 2018;
x <> 2018 OR x = 2018;
x <> 2018 OR x = 2018;

0 comments on commit 31a82cc

Please sign in to comment.