diff --git a/pkg/format/body.go b/pkg/format/body.go index 181517a..88bb116 100644 --- a/pkg/format/body.go +++ b/pkg/format/body.go @@ -379,6 +379,7 @@ func formatBodyStatements(text string, st config.Style) string { stmt []bline parenDepth int blockDepth int // 0=col-0 (BEGIN/END/EXCEPTION), 1=body, 2=nested… + caseDepth int // depth of open CASE…END expressions (WHEN…THEN is not a block opener) inException bool pendingBlanks int depthInc bool // increment blockDepth after next flush @@ -529,18 +530,41 @@ func formatBodyStatements(text string, st config.Style) string { } if parenDepth == 0 && tok.Kind == lexer.Ident { lastD0Kw = lowerASCII(tok.Text) + switch lastD0Kw { + case "case": + caseDepth++ + case "end": + if caseDepth > 0 { + caseDepth-- + } + } } } if parenDepth == 0 && len(stmt) > 0 { switch lastD0Kw { - case "then", "loop", "begin": + case "then": + // A THEN ending a CASE…WHEN branch is not a PL/pgSQL block + // opener; only one matching END closes the whole CASE, so + // treating each WHEN…THEN as a block open would permanently + // inflate blockDepth. + if caseDepth == 0 { + fw0 := lowerASCII(firstBodyKeyword(stmt[0].text)) + if fw0 != "elsif" && fw0 != "elseif" { + depthInc = true + } + flush() + } + case "loop", "begin": fw0 := lowerASCII(firstBodyKeyword(stmt[0].text)) if fw0 != "elsif" && fw0 != "elseif" { depthInc = true } flush() case "else", "exception": + if caseDepth > 0 { + break + } flush() } }