Skip to content

Commit

Permalink
fix(optimizer): remove redundant casts (#2945)
Browse files Browse the repository at this point in the history
  • Loading branch information
barakalon authored Feb 9, 2024
1 parent 76d6634 commit d07ddf9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
3 changes: 1 addition & 2 deletions sqlglot/optimizer/canonicalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,8 @@ def coerce_type(node: exp.Expression) -> exp.Expression:
def remove_redundant_casts(expression: exp.Expression) -> exp.Expression:
if (
isinstance(expression, exp.Cast)
and expression.to.type
and expression.this.type
and expression.to.type.this == expression.this.type.this
and expression.to.this == expression.this.type.this
):
return expression.this
return expression
Expand Down
12 changes: 12 additions & 0 deletions tests/fixtures/optimizer/canonicalize.sql
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,15 @@ DATE_TRUNC('DAY', CAST('2023-01-01' AS DATE));

DATEDIFF('2023-01-01', '2023-01-02', DAY);
DATEDIFF(CAST('2023-01-01' AS DATETIME), CAST('2023-01-02' AS DATETIME), DAY);

--------------------------------------
-- Remove redundant casts
--------------------------------------
CAST(CAST('2023-01-01' AS DATE) AS DATE);
CAST('2023-01-01' AS DATE);

CAST(DATE_TRUNC('YEAR', CAST('2023-01-01' AS DATE)) AS DATE);
DATE_TRUNC('YEAR', CAST('2023-01-01' AS DATE));

DATE(DATE_TRUNC('YEAR', CAST("x" AS DATE)));
DATE_TRUNC('YEAR', CAST("x" AS DATE));

0 comments on commit d07ddf9

Please sign in to comment.