diff --git a/CHANGELOG b/CHANGELOG index 44d5938e7..1dea7f54b 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,7 +1,10 @@ Development Version ------------------- -Nothing yet. +Bug Fixes + +* ``strip_whitespace=True`` no longer raises ``IndexError`` on a parenthesis + group holding fewer tokens than expected, e.g. "( AS )" (#885). Release 0.6.0 (Aug 13, 2026) diff --git a/sqlparse/filters/others.py b/sqlparse/filters/others.py index 95bc436c7..18ed33e4f 100644 --- a/sqlparse/filters/others.py +++ b/sqlparse/filters/others.py @@ -112,14 +112,20 @@ def _stripws_identifierlist(self, tlist): return self._stripws_default(tlist) def _stripws_parenthesis(self, tlist): + # A malformed group may hold fewer tokens than the "(" ... ")" layout + # assumed below, e.g. "( AS )" parses to a single nested group (#885). + if len(tlist.tokens) < 3: + self._stripws_default(tlist) + return while tlist.tokens[1].is_whitespace: tlist.tokens.pop(1) while tlist.tokens[-2].is_whitespace: tlist.tokens.pop(-2) - if tlist.tokens[-2].is_group: + inner = tlist.tokens[-2] + if inner.is_group: # save to remove the last whitespace - while tlist.tokens[-2].tokens[-1].is_whitespace: - tlist.tokens[-2].tokens.pop(-1) + while inner.tokens and inner.tokens[-1].is_whitespace: + inner.tokens.pop(-1) self._stripws_default(tlist) def process(self, stmt, depth=0): diff --git a/tests/test_regressions.py b/tests/test_regressions.py index aca7f7b37..ccfe14aba 100644 --- a/tests/test_regressions.py +++ b/tests/test_regressions.py @@ -285,6 +285,18 @@ def test_issue213_leadingws(): assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" +def test_issue885_stripws_malformed_parenthesis(): + # "( AS )" parses to a Parenthesis group holding a single nested group; + # strip_whitespace used to raise IndexError on it. + assert sqlparse.format("( AS )", strip_whitespace=True) == "( AS )" + + +def test_issue885_stripws_short_parenthesis_groups(): + # Parenthesis groups with fewer than three tokens must not raise. + for case in ["()", "( )", "(a)"]: + sqlparse.format(case, strip_whitespace=True) + + def test_issue227_gettype_cte(): select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') assert select_stmt[0].get_type() == 'SELECT'