From 23b64bd71795c7012afe1e3d7b35857614aed2f2 Mon Sep 17 00:00:00 2001 From: santhreal <64453045+santhreal@users.noreply.github.com> Date: Fri, 17 Jul 2026 22:43:37 -0700 Subject: [PATCH] fix: guard short parenthesis groups in StripWhitespaceFilter format("(::)", reindent=True) crashed with IndexError because the Parenthesis node held a single Identifier and tokens[1] did not exist. Only strip inner whitespace when open/body/close slots are present. --- sqlparse/filters/others.py | 10 ++++++---- tests/test_format.py | 3 +++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/sqlparse/filters/others.py b/sqlparse/filters/others.py index 95bc436c..4c4b635f 100644 --- a/sqlparse/filters/others.py +++ b/sqlparse/filters/others.py @@ -112,13 +112,15 @@ def _stripws_identifierlist(self, tlist): return self._stripws_default(tlist) def _stripws_parenthesis(self, tlist): - while tlist.tokens[1].is_whitespace: + # Short groups (e.g. "(::)") lack open/body/close slots for inner ws pops. + while len(tlist.tokens) > 2 and tlist.tokens[1].is_whitespace: tlist.tokens.pop(1) - while tlist.tokens[-2].is_whitespace: + while len(tlist.tokens) > 2 and tlist.tokens[-2].is_whitespace: tlist.tokens.pop(-2) - if tlist.tokens[-2].is_group: + if len(tlist.tokens) > 2 and tlist.tokens[-2].is_group: # save to remove the last whitespace - while tlist.tokens[-2].tokens[-1].is_whitespace: + while (tlist.tokens[-2].tokens + and tlist.tokens[-2].tokens[-1].is_whitespace): tlist.tokens[-2].tokens.pop(-1) self._stripws_default(tlist) diff --git a/tests/test_format.py b/tests/test_format.py index 0cdbcf88..1575063b 100644 --- a/tests/test_format.py +++ b/tests/test_format.py @@ -432,6 +432,9 @@ def test_parenthesis(self): assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + # Cast-like "(::)" is one Identifier inside Parenthesis; must not IndexError + assert f('(::)') == '(::)' + assert f('()') == '()' def test_where(self): f = lambda sql: sqlparse.format(sql, reindent=True)