feat(format): case_collapse uses line_width via Doc-IR

This commit is contained in:
Hein
2026-10-06 14:48:28 +02:00
parent 553609e988
commit ab9fe8893b
4 changed files with 25 additions and 13 deletions
+5 -7
View File
@@ -861,10 +861,6 @@ func alignSetItems(texts []string) []string {
return out
}
// caseCollapseWidth is the inline-length threshold under which case_collapse
// keeps a CASE expression on one line even when case_when_wrap is set.
const caseCollapseWidth = 60
// dmlIsCaseStart reports whether t is a CASE keyword token.
func dmlIsCaseStart(t cst.Tok) bool {
return t.Tok.Kind == lexer.Ident && lowerASCII(t.Tok.Text) == "case"
@@ -1001,10 +997,12 @@ func dmlFormatCase(toks []cst.Tok, st config.Style) string {
if !st.CaseWhenWrap {
return inline
}
if st.CaseCollapse && len(inline) <= caseCollapseWidth {
return inline
wrapped := dmlCaseWrapped(caseKw, operand, whens, elseKw, elseText, haveElse, endKw, st)
if st.CaseCollapse {
// Collapse when the one-line form fits in line_width.
return Render(Group(IfBreak(Text(wrapped), Text(inline))), st.LineWidth, st.Indent, st.Newline)
}
return dmlCaseWrapped(caseKw, operand, whens, elseKw, elseText, haveElse, endKw, st)
return wrapped
}
// dmlCaseInline renders a CASE expression on a single line.
+15
View File
@@ -632,3 +632,18 @@ func TestWhereWhenLong(t *testing.T) {
t.Errorf("broken when_long should equal always:\n%s\n---\n%s", long, want)
}
}
func TestDMLCaseCollapseUsesLineWidth(t *testing.T) {
st := config.Default()
st.CaseWhenWrap = true
st.CaseCollapse = true
src := "select case when a = 1 then 'one' when a = 2 then 'two' else 'other' end from t;"
st.LineWidth = 120
if got := File(parser.Parse(src), st); strings.Contains(got, "\n WHEN") {
t.Errorf("fits in 120, should collapse:\n%s", got)
}
st.LineWidth = 30
if got := File(parser.Parse(src), st); !strings.Contains(got, "\n WHEN") {
t.Errorf("exceeds 30, should wrap:\n%s", got)
}
}