From 00234cc0fd26f0b8944f9fb03785633ee58c5e85 Mon Sep 17 00:00:00 2001 From: santhreal <64453045+santhreal@users.noreply.github.com> Date: Thu, 16 Jul 2026 07:16:13 -0700 Subject: [PATCH] Fix ValueError aligning a CASE with no END keyword _process_case appends a (None, [end_token]) entry to align the END, but a malformed CASE such as 'case,end' groups as an IdentifierList with no standalone END keyword, so token_next_by returns None. The appended (None, [None]) then reaches insert_before(None), which raises ValueError: None is not in list. Skip the end alignment when there is no END token. --- sqlparse/filters/aligned_indent.py | 6 +++++- tests/test_format.py | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py index 6ac99d62..055b9815 100644 --- a/sqlparse/filters/aligned_indent.py +++ b/sqlparse/filters/aligned_indent.py @@ -70,7 +70,11 @@ def _process_case(self, tlist): cases = tlist.get_cases(skip_ws=True) # align the end as well end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[1] - cases.append((None, [end_token])) + # A malformed CASE (e.g. "case,end", which groups as an IdentifierList) + # has no standalone END keyword; skip the end alignment rather than + # appending a (None, [None]) entry that later crashes insert_before. + if end_token is not None: + cases.append((None, [end_token])) condition_width = [len(' '.join(map(str, cond))) if cond else 0 for cond, _ in cases] diff --git a/tests/test_format.py b/tests/test_format.py index 0cdbcf88..0f1770c6 100644 --- a/tests/test_format.py +++ b/tests/test_format.py @@ -784,3 +784,14 @@ def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 strip_whitespace=True) expected = '(where foo = bar) from' assert formatted == expected + + +def test_aligned_indent_case_without_end(): + # A malformed CASE with no standalone END keyword (e.g. "case,end", which + # groups as an IdentifierList) must not crash the aligned-indent filter. + assert sqlparse.format('case,end', reindent_aligned=True) == 'case,end' + # A well-formed CASE is still aligned across its branches. + formatted = sqlparse.format( + 'select case when 1 then 2 else 3 end from t', reindent_aligned=True) + assert 'when 1 then 2' in formatted + assert 'else 3' in formatted