From 228c7cf747d650702c7a5829c750a8f74cffae3d Mon Sep 17 00:00:00 2001 From: alexander-beedie Date: Sat, 19 Oct 2024 22:14:39 +0400 Subject: [PATCH] fix: Use of `HAVING` outside of `GROUP BY` should raise a suitable SQLSyntaxError --- crates/polars-sql/src/context.rs | 5 +++++ py-polars/tests/unit/sql/test_group_by.py | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/crates/polars-sql/src/context.rs b/crates/polars-sql/src/context.rs index 342a5e0883d2..1a060545439c 100644 --- a/crates/polars-sql/src/context.rs +++ b/crates/polars-sql/src/context.rs @@ -709,6 +709,11 @@ impl SQLContext { }; lf = if group_by_keys.is_empty() { + // The 'having' clause is only valid inside 'group by' + if select_stmt.having.is_some() { + polars_bail!(SQLSyntax: "HAVING clause not valid outside of GROUP BY; found:\n{:?}", select_stmt.having); + }; + // Final/selected cols, accounting for 'SELECT *' modifiers let mut retained_cols = Vec::with_capacity(projections.len()); let have_order_by = query.order_by.is_some(); diff --git a/py-polars/tests/unit/sql/test_group_by.py b/py-polars/tests/unit/sql/test_group_by.py index 08e4b236c833..71fa1572831c 100644 --- a/py-polars/tests/unit/sql/test_group_by.py +++ b/py-polars/tests/unit/sql/test_group_by.py @@ -238,3 +238,9 @@ def test_group_by_errors() -> None: match=r"'a' should participate in the GROUP BY clause or an aggregate function", ): df.sql("SELECT a, SUM(b) FROM self GROUP BY b") + + with pytest.raises( + SQLSyntaxError, + match=r"HAVING clause not valid outside of GROUP BY", + ): + df.sql("SELECT a, COUNT(a) AS n FROM self HAVING n > 1")