Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions crates/polars-sql/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2724,12 +2724,18 @@ impl SQLContext {
table_with_joins,
alias,
} => {
let lf =
self.execute_isolated(|ctx| ctx.execute_from_statement(table_with_joins))?;
match alias {
Some(a) => Ok((a.name.value.clone(), lf)),
None => Ok(("".to_string(), lf)),
}
// Only an alias makes the parenthesized join a scope of its own; bare parens
// just group, so their relation aliases stay visible to the enclosing query.
let lf = match alias {
Some(_) => {
self.execute_isolated(|ctx| ctx.execute_from_statement(table_with_joins))?
},
None => self.execute_from_statement(table_with_joins)?,
};
let name = alias
.as_ref()
.map_or_else(String::new, |a| a.name.value.clone());
Ok((name, lf))
},
// Support bare table, optionally with an alias, for now
_ => polars_bail!(SQLInterface: "not yet implemented: {}", relation),
Expand Down
35 changes: 35 additions & 0 deletions py-polars/tests/unit/sql/test_joins.py
Original file line number Diff line number Diff line change
Expand Up @@ -1037,6 +1037,41 @@ def test_nested_joins_17381() -> None:
assert set(res["id"]) == {"one", "two"}


def test_parenthesized_join_relation_29153() -> None:
# ref: https://github.com/pola-rs/polars/issues/29153
# bare parens around a join don't introduce a new scope, so the
# relation aliases they declare remain visible to the SELECT
frames = {
"lft": pl.DataFrame({"a": [1, 2, 3], "bob": [4, 5, 6]}),
"rgt": pl.DataFrame({"a": [1, 2, 3], "co": [4, 5, 7]}),
"other": pl.DataFrame({"co": [4, 5, 7], "z": ["x", "y", "z"]}),
}
for from_clause in (
"(lft AS lhs LEFT JOIN rgt AS rhs ON lhs.bob = rhs.co)",
"lft AS lhs LEFT JOIN rgt AS rhs ON lhs.bob = rhs.co",
):
assert_sql_matches(
frames=frames,
query=f"""
SELECT lhs.a, lhs.bob, rhs.a AS a_right
FROM {from_clause}
ORDER BY lhs.a
""",
compare_with="sqlite",
)

assert_sql_matches(
frames=frames,
query="""
SELECT lhs.a, rhs.co, t.z
FROM (lft AS lhs INNER JOIN rgt AS rhs ON lhs.bob = rhs.co)
INNER JOIN other AS t ON rhs.co = t.co
ORDER BY lhs.a
""",
compare_with="sqlite",
)


def test_unnamed_nested_join_relation() -> None:
df = pl.DataFrame({"a": 1})

Expand Down
Loading