Skip to content

Commit 4923316

Browse files
committed
pretty print case statements
1 parent 5aeb83c commit 4923316

File tree

2 files changed

+42
-7
lines changed

2 files changed

+42
-7
lines changed

src/ast/mod.rs

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,10 @@ use serde::{Deserialize, Serialize};
4040
#[cfg(feature = "visitor")]
4141
use sqlparser_derive::{Visit, VisitMut};
4242

43-
use crate::tokenizer::{Span, Token};
43+
use crate::{
44+
display_utils::SpaceOrNewline,
45+
tokenizer::{Span, Token},
46+
};
4447
use crate::{
4548
display_utils::{Indent, NewLine},
4649
keywords::Keyword,
@@ -631,7 +634,12 @@ pub struct CaseWhen {
631634

632635
impl fmt::Display for CaseWhen {
633636
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
634-
write!(f, "WHEN {} THEN {}", self.condition, self.result)
637+
f.write_str("WHEN ")?;
638+
self.condition.fmt(f)?;
639+
f.write_str(" THEN")?;
640+
SpaceOrNewline.fmt(f)?;
641+
Indent(&self.result).fmt(f)?;
642+
Ok(())
635643
}
636644
}
637645

@@ -1671,17 +1679,23 @@ impl fmt::Display for Expr {
16711679
conditions,
16721680
else_result,
16731681
} => {
1674-
write!(f, "CASE")?;
1682+
f.write_str("CASE")?;
16751683
if let Some(operand) = operand {
1676-
write!(f, " {operand}")?;
1684+
f.write_str(" ")?;
1685+
operand.fmt(f)?;
16771686
}
16781687
for when in conditions {
1679-
write!(f, " {when}")?;
1688+
SpaceOrNewline.fmt(f)?;
1689+
Indent(when).fmt(f)?;
16801690
}
16811691
if let Some(else_result) = else_result {
1682-
write!(f, " ELSE {else_result}")?;
1692+
SpaceOrNewline.fmt(f)?;
1693+
Indent("ELSE").fmt(f)?;
1694+
SpaceOrNewline.fmt(f)?;
1695+
Indent(Indent(else_result)).fmt(f)?;
16831696
}
1684-
write!(f, " END")
1697+
SpaceOrNewline.fmt(f)?;
1698+
f.write_str("END")
16851699
}
16861700
Expr::Exists { subquery, negated } => write!(
16871701
f,

tests/pretty_print.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,24 @@ FROM
112112
cte"#
113113
);
114114
}
115+
116+
#[test]
117+
fn test_pretty_print_case_when() {
118+
let sql = "SELECT CASE WHEN x > 0 THEN 'positive' WHEN x < 0 THEN 'negative' ELSE 'zero' END FROM my_table";
119+
let ast = Parser::parse_sql(&GenericDialect {}, sql).unwrap();
120+
let pretty = format!("{:#}", ast[0]);
121+
assert_eq!(
122+
pretty,
123+
r#"SELECT
124+
CASE
125+
WHEN x > 0 THEN
126+
'positive'
127+
WHEN x < 0 THEN
128+
'negative'
129+
ELSE
130+
'zero'
131+
END
132+
FROM
133+
my_table"#
134+
);
135+
}

0 commit comments

Comments
 (0)