Skip to content

Commit

Permalink
fix: only some joins can be simplified to CROSS (#2025)
Browse files Browse the repository at this point in the history
  • Loading branch information
barakalon authored Aug 10, 2023
1 parent 325b26e commit ad75c6f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
12 changes: 12 additions & 0 deletions sqlglot/optimizer/simplify.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,17 @@ def simplify_coalesce(expression):
)


# CROSS joins result in an empty table if the right table is empty.
# So we can only simplify certain types of joins to CROSS.
# Or in other words, LEFT JOIN x ON TRUE != CROSS JOIN x
JOINS = {
("", ""),
("", "INNER"),
("RIGHT", ""),
("RIGHT", "OUTER"),
}


def remove_where_true(expression):
for where in expression.find_all(exp.Where):
if always_true(where.this):
Expand All @@ -504,6 +515,7 @@ def remove_where_true(expression):
always_true(join.args.get("on"))
and not join.args.get("using")
and not join.args.get("method")
and (join.side, join.kind) in JOINS
):
join.set("on", None)
join.set("side", None)
Expand Down
11 changes: 10 additions & 1 deletion tests/fixtures/optimizer/simplify.sql
Original file line number Diff line number Diff line change
Expand Up @@ -240,9 +240,18 @@ A AND B AND C;
SELECT x WHERE TRUE;
SELECT x;

SELECT x FROM y LEFT JOIN z ON TRUE;
SELECT x FROM y JOIN z ON TRUE;
SELECT x FROM y CROSS JOIN z;

SELECT x FROM y RIGHT JOIN z ON TRUE;
SELECT x FROM y CROSS JOIN z;

SELECT x FROM y LEFT JOIN z ON TRUE;
SELECT x FROM y LEFT JOIN z ON TRUE;

SELECT x FROM y FULL OUTER JOIN z ON TRUE;
SELECT x FROM y FULL OUTER JOIN z ON TRUE;

SELECT x FROM y JOIN z USING (x);
SELECT x FROM y JOIN z USING (x);

Expand Down

0 comments on commit ad75c6f

Please sign in to comment.