From 0c4902f3f7aafa8c2e63a375ec307c210842f543 Mon Sep 17 00:00:00 2001 From: Andi Albrecht Date: Mon, 15 Jul 2024 11:32:49 +0200 Subject: [PATCH] Descend into subgroups when removing whitespace (fixes #782). --- CHANGELOG | 2 ++ sqlparse/filters/others.py | 4 ++++ tests/test_format.py | 13 ++++++++++--- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 150f3b3c..34e59b35 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -17,6 +17,8 @@ Bug Fixes * Fix error when splitting statements that contain multiple CASE clauses within a BEGIN block (issue784). +* Fix whitespace removal with nested expressions (issue782). + Release 0.5.0 (Apr 13, 2024) ---------------------------- diff --git a/sqlparse/filters/others.py b/sqlparse/filters/others.py index da7c0e79..3388a782 100644 --- a/sqlparse/filters/others.py +++ b/sqlparse/filters/others.py @@ -91,6 +91,10 @@ def _stripws_parenthesis(self, tlist): tlist.tokens.pop(1) while tlist.tokens[-2].is_whitespace: tlist.tokens.pop(-2) + if tlist.tokens[-2].is_group: + # save to remove the last whitespace + while tlist.tokens[-2].tokens[-1].is_whitespace: + tlist.tokens[-2].tokens.pop(-1) self._stripws_default(tlist) def process(self, stmt, depth=0): diff --git a/tests/test_format.py b/tests/test_format.py index 4cbfcbe0..df94630c 100644 --- a/tests/test_format.py +++ b/tests/test_format.py @@ -100,7 +100,7 @@ def test_strip_comments_preserves_linebreak(self): sql = 'select * -- a comment\n\nfrom foo' res = sqlparse.format(sql, strip_comments=True) assert res == 'select *\n\nfrom foo' - + def test_strip_comments_preserves_whitespace(self): sql = 'SELECT 1/*bar*/ AS foo' # see issue772 res = sqlparse.format(sql, strip_comments=True) @@ -734,8 +734,8 @@ def test_format_json_ops(): # issue542 "select foo->'bar', foo->'bar';", reindent=True) expected = "select foo->'bar',\n foo->'bar';" assert formatted == expected - - + + @pytest.mark.parametrize('sql, expected_normal, expected_compact', [ ('case when foo then 1 else bar end', 'case\n when foo then 1\n else bar\nend', @@ -745,3 +745,10 @@ def test_compact(sql, expected_normal, expected_compact): # issue783 formatted_compact = sqlparse.format(sql, reindent=True, compact=True) assert formatted_normal == expected_normal assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected