Skip to content

Commit

Permalink
Unparse inner join with no conditions as a cross join (apache#13460)
Browse files Browse the repository at this point in the history
* Unparse inner join with no conditions as a cross join

* Add explicit cross join

* Fix mysql test
  • Loading branch information
phillipleblanc authored Nov 19, 2024
1 parent adcf90f commit 1a09adf
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
11 changes: 10 additions & 1 deletion datafusion/sql/src/unparser/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -876,7 +876,16 @@ impl Unparser<'_> {
constraint: ast::JoinConstraint,
) -> Result<ast::JoinOperator> {
Ok(match join_type {
JoinType::Inner => ast::JoinOperator::Inner(constraint),
JoinType::Inner => match &constraint {
ast::JoinConstraint::On(_)
| ast::JoinConstraint::Using(_)
| ast::JoinConstraint::Natural => ast::JoinOperator::Inner(constraint),
ast::JoinConstraint::None => {
// Inner joins with no conditions or filters are not valid SQL in most systems,
// return a CROSS JOIN instead
ast::JoinOperator::CrossJoin
}
},
JoinType::Left => ast::JoinOperator::LeftOuter(constraint),
JoinType::Right => ast::JoinOperator::RightOuter(constraint),
JoinType::Full => ast::JoinOperator::FullOuter(constraint),
Expand Down
16 changes: 15 additions & 1 deletion datafusion/sql/tests/cases/plan_to_sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ fn roundtrip_statement_with_dialect() -> Result<()> {
TestStatementWithDialect {
sql: "select min(ta.j1_id) as j1_min, max(tb.j1_max) from j1 ta, (select distinct max(ta.j1_id) as j1_max from j1 ta order by max(ta.j1_id)) tb order by min(ta.j1_id) limit 10;",
expected:
"SELECT `j1_min`, `max(tb.j1_max)` FROM (SELECT min(`ta`.`j1_id`) AS `j1_min`, max(`tb`.`j1_max`), min(`ta`.`j1_id`) FROM `j1` AS `ta` JOIN (SELECT `j1_max` FROM (SELECT DISTINCT max(`ta`.`j1_id`) AS `j1_max` FROM `j1` AS `ta`) AS `derived_distinct`) AS `tb` ORDER BY min(`ta`.`j1_id`) ASC) AS `derived_sort` LIMIT 10",
"SELECT `j1_min`, `max(tb.j1_max)` FROM (SELECT min(`ta`.`j1_id`) AS `j1_min`, max(`tb`.`j1_max`), min(`ta`.`j1_id`) FROM `j1` AS `ta` CROSS JOIN (SELECT `j1_max` FROM (SELECT DISTINCT max(`ta`.`j1_id`) AS `j1_max` FROM `j1` AS `ta`) AS `derived_distinct`) AS `tb` ORDER BY min(`ta`.`j1_id`) ASC) AS `derived_sort` LIMIT 10",
parser_dialect: Box::new(MySqlDialect {}),
unparser_dialect: Box::new(UnparserMySqlDialect {}),
},
Expand Down Expand Up @@ -1253,3 +1253,17 @@ fn test_unnest_to_sql() {
r#"SELECT UNNEST([1, 2, 2, 5, NULL]) AS u1"#,
);
}

#[test]
fn test_join_with_no_conditions() {
sql_round_trip(
GenericDialect {},
"SELECT * FROM j1 JOIN j2",
"SELECT * FROM j1 CROSS JOIN j2",
);
sql_round_trip(
GenericDialect {},
"SELECT * FROM j1 CROSS JOIN j2",
"SELECT * FROM j1 CROSS JOIN j2",
);
}

0 comments on commit 1a09adf

Please sign in to comment.