Skip to content

pretty print improvements #1851

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,14 @@ keywords, the following should hold true for all SQL:

```rust
// Parse SQL
let sql = "SELECT 'hello'";
let ast = Parser::parse_sql(&GenericDialect, sql).unwrap();

// The original SQL text can be generated from the AST
assert_eq!(ast[0].to_string(), sql);

// The SQL can also be pretty-printed with newlines and indentation
assert_eq!(format!("{:#}", ast[0]), "SELECT\n 'hello'");
```

There are still some cases in this crate where different SQL with seemingly
Expand Down
57 changes: 39 additions & 18 deletions src/ast/dml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ use serde::{Deserialize, Serialize};
#[cfg(feature = "visitor")]
use sqlparser_derive::{Visit, VisitMut};

use crate::display_utils::{indented_list, Indent, SpaceOrNewline};

pub use super::ddl::{ColumnDef, TableConstraint};

use super::{
Expand Down Expand Up @@ -579,28 +581,32 @@ impl Display for Insert {
)?;
}
if !self.columns.is_empty() {
write!(f, "({}) ", display_comma_separated(&self.columns))?;
write!(f, "({})", display_comma_separated(&self.columns))?;
SpaceOrNewline.fmt(f)?;
}
if let Some(ref parts) = self.partitioned {
if !parts.is_empty() {
write!(f, "PARTITION ({}) ", display_comma_separated(parts))?;
write!(f, "PARTITION ({})", display_comma_separated(parts))?;
SpaceOrNewline.fmt(f)?;
}
}
if !self.after_columns.is_empty() {
write!(f, "({}) ", display_comma_separated(&self.after_columns))?;
write!(f, "({})", display_comma_separated(&self.after_columns))?;
SpaceOrNewline.fmt(f)?;
}

if let Some(settings) = &self.settings {
write!(f, "SETTINGS {} ", display_comma_separated(settings))?;
write!(f, "SETTINGS {}", display_comma_separated(settings))?;
SpaceOrNewline.fmt(f)?;
}

if let Some(source) = &self.source {
write!(f, "{source}")?;
source.fmt(f)?;
} else if !self.assignments.is_empty() {
write!(f, "SET ")?;
write!(f, "{}", display_comma_separated(&self.assignments))?;
write!(f, "SET")?;
indented_list(f, &self.assignments)?;
} else if let Some(format_clause) = &self.format_clause {
write!(f, "{format_clause}")?;
format_clause.fmt(f)?;
} else if self.columns.is_empty() {
write!(f, "DEFAULT VALUES")?;
}
Expand All @@ -620,7 +626,9 @@ impl Display for Insert {
}

if let Some(returning) = &self.returning {
write!(f, " RETURNING {}", display_comma_separated(returning))?;
SpaceOrNewline.fmt(f)?;
f.write_str("RETURNING")?;
indented_list(f, returning)?;
}
Ok(())
}
Expand Down Expand Up @@ -649,32 +657,45 @@ pub struct Delete {

impl Display for Delete {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "DELETE ")?;
f.write_str("DELETE")?;
if !self.tables.is_empty() {
write!(f, "{} ", display_comma_separated(&self.tables))?;
indented_list(f, &self.tables)?;
}
match &self.from {
FromTable::WithFromKeyword(from) => {
write!(f, "FROM {}", display_comma_separated(from))?;
f.write_str(" FROM")?;
indented_list(f, from)?;
}
FromTable::WithoutKeyword(from) => {
write!(f, "{}", display_comma_separated(from))?;
indented_list(f, from)?;
}
}
if let Some(using) = &self.using {
write!(f, " USING {}", display_comma_separated(using))?;
SpaceOrNewline.fmt(f)?;
f.write_str("USING")?;
indented_list(f, using)?;
}
if let Some(selection) = &self.selection {
write!(f, " WHERE {selection}")?;
SpaceOrNewline.fmt(f)?;
f.write_str("WHERE")?;
SpaceOrNewline.fmt(f)?;
Indent(selection).fmt(f)?;
}
if let Some(returning) = &self.returning {
write!(f, " RETURNING {}", display_comma_separated(returning))?;
SpaceOrNewline.fmt(f)?;
f.write_str("RETURNING")?;
indented_list(f, returning)?;
}
if !self.order_by.is_empty() {
write!(f, " ORDER BY {}", display_comma_separated(&self.order_by))?;
SpaceOrNewline.fmt(f)?;
f.write_str("ORDER BY")?;
indented_list(f, &self.order_by)?;
}
if let Some(limit) = &self.limit {
write!(f, " LIMIT {limit}")?;
SpaceOrNewline.fmt(f)?;
f.write_str("LIMIT")?;
SpaceOrNewline.fmt(f)?;
Indent(limit).fmt(f)?;
}
Ok(())
}
Expand Down
36 changes: 24 additions & 12 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ use serde::{Deserialize, Serialize};
use sqlparser_derive::{Visit, VisitMut};

use crate::{
display_utils::SpaceOrNewline,
display_utils::{indented_list, SpaceOrNewline},
tokenizer::{Span, Token},
};
use crate::{
Expand Down Expand Up @@ -4543,7 +4543,7 @@ impl fmt::Display for Statement {
}
Ok(())
}
Statement::Insert(insert) => write!(f, "{insert}"),
Statement::Insert(insert) => insert.fmt(f),
Statement::Install {
extension_name: name,
} => write!(f, "INSTALL {name}"),
Expand Down Expand Up @@ -4606,30 +4606,42 @@ impl fmt::Display for Statement {
returning,
or,
} => {
write!(f, "UPDATE ")?;
f.write_str("UPDATE ")?;
if let Some(or) = or {
write!(f, "{or} ")?;
or.fmt(f)?;
f.write_str(" ")?;
}
write!(f, "{table}")?;
table.fmt(f)?;
if let Some(UpdateTableFromKind::BeforeSet(from)) = from {
write!(f, " FROM {}", display_comma_separated(from))?;
SpaceOrNewline.fmt(f)?;
f.write_str("FROM")?;
indented_list(f, from)?;
}
if !assignments.is_empty() {
write!(f, " SET {}", display_comma_separated(assignments))?;
SpaceOrNewline.fmt(f)?;
f.write_str("SET")?;
indented_list(f, assignments)?;
}
if let Some(UpdateTableFromKind::AfterSet(from)) = from {
write!(f, " FROM {}", display_comma_separated(from))?;
SpaceOrNewline.fmt(f)?;
f.write_str("FROM")?;
indented_list(f, from)?;
}
if let Some(selection) = selection {
write!(f, " WHERE {selection}")?;
SpaceOrNewline.fmt(f)?;
f.write_str("WHERE")?;
SpaceOrNewline.fmt(f)?;
Indent(selection).fmt(f)?;
}
if let Some(returning) = returning {
write!(f, " RETURNING {}", display_comma_separated(returning))?;
SpaceOrNewline.fmt(f)?;
f.write_str("RETURNING")?;
indented_list(f, returning)?;
}
Ok(())
}
Statement::Delete(delete) => write!(f, "{delete}"),
Statement::Open(open) => write!(f, "{open}"),
Statement::Delete(delete) => delete.fmt(f),
Statement::Open(open) => open.fmt(f),
Statement::Close { cursor } => {
write!(f, "CLOSE {cursor}")?;

Expand Down
26 changes: 19 additions & 7 deletions src/ast/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2883,14 +2883,26 @@ pub struct Values {

impl fmt::Display for Values {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "VALUES ")?;
let prefix = if self.explicit_row { "ROW" } else { "" };
let mut delim = "";
for row in &self.rows {
write!(f, "{delim}")?;
delim = ", ";
write!(f, "{prefix}({})", display_comma_separated(row))?;
struct DisplayRow<'a> {
exprs: &'a [Expr],
explicit_row: bool,
}
impl fmt::Display for DisplayRow<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let comma_separated = display_comma_separated(self.exprs);
if self.explicit_row {
write!(f, "ROW({})", comma_separated)
} else {
write!(f, "({})", comma_separated)
}
}
}
let row_display_iter = self.rows.iter().map(|row| DisplayRow {
exprs: row,
explicit_row: self.explicit_row,
});
f.write_str("VALUES")?;
indented_list(f, row_display_iter)?;
Ok(())
}
}
Expand Down
63 changes: 28 additions & 35 deletions src/display_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,10 @@ where
T: Write,
{
fn write_str(&mut self, s: &str) -> fmt::Result {
let mut first = true;
for line in s.split('\n') {
if !first {
write!(self.0, "\n{INDENT}")?;
}
self.0.write_str(line)?;
first = false;
self.0.write_str(s)?;
// Our NewLine and SpaceOrNewline utils always print individual newlines as a single-character string.
if s == "\n" {
self.0.write_str(INDENT)?;
}
Ok(())
}
Expand Down Expand Up @@ -71,12 +68,17 @@ impl Display for SpaceOrNewline {

/// A value that displays a comma-separated list of values.
/// When pretty-printed (using {:#}), it displays each value on a new line.
pub struct DisplayCommaSeparated<'a, T: fmt::Display>(&'a [T]);
pub(crate) struct DisplayCommaSeparated<I, T: fmt::Display>(I)
where
I: IntoIterator<Item = T> + Clone;

impl<T: fmt::Display> fmt::Display for DisplayCommaSeparated<'_, T> {
impl<I, T: fmt::Display> fmt::Display for DisplayCommaSeparated<I, T>
where
I: IntoIterator<Item = T> + Clone,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
for t in self.0 {
for t in self.0.clone() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

was the clone needed here, we seem to only call fmt on t?

Copy link
Contributor Author

@lovasoa lovasoa May 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we are never actually cloning anything expensive here, but we need to add the Clone generic bound in order to be able to use the IntoIterator trait.

This .clone() concretely always clones

  • either just a reference (to a slice)
  • or an iterator object (but not the underlying structure being iterated on)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@iffyio , I can roll it back to the non-generic version, and just implement comma separation manually in the Values Display impl, if you want.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I think it might be better to make it explicit, with the new impl seems like it wouldn't be obvious if we were to go on to later clone something expensive accidentally

if !first {
f.write_char(',')?;
SpaceOrNewline.fmt(f)?;
Expand All @@ -89,45 +91,36 @@ impl<T: fmt::Display> fmt::Display for DisplayCommaSeparated<'_, T> {
}

/// Displays a whitespace, followed by a comma-separated list that is indented when pretty-printed.
pub(crate) fn indented_list<T: fmt::Display>(f: &mut fmt::Formatter, slice: &[T]) -> fmt::Result {
pub(crate) fn indented_list<I, T: fmt::Display>(f: &mut fmt::Formatter, iter: I) -> fmt::Result
where
I: IntoIterator<Item = T> + Clone,
{
SpaceOrNewline.fmt(f)?;
Indent(DisplayCommaSeparated(slice)).fmt(f)
Indent(DisplayCommaSeparated(iter)).fmt(f)
}

#[cfg(test)]
mod tests {
use super::*;

struct DisplayCharByChar<T: Display>(T);
#[test]
fn test_indent() {
struct TwoLines;

impl<T: Display> Display for DisplayCharByChar<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for c in self.0.to_string().chars() {
write!(f, "{}", c)?;
impl Display for TwoLines {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("line 1")?;
SpaceOrNewline.fmt(f)?;
f.write_str("line 2")
}
Ok(())
}
}

#[test]
fn test_indent() {
let original = "line 1\nline 2";
let indent = Indent(original);
let indent = Indent(TwoLines);
assert_eq!(
indent.to_string(),
original,
TwoLines.to_string(),
"Only the alternate form should be indented"
);
let expected = " line 1\n line 2";
assert_eq!(format!("{:#}", indent), expected);
let display_char_by_char = DisplayCharByChar(original);
assert_eq!(format!("{:#}", Indent(display_char_by_char)), expected);
}

#[test]
fn test_space_or_newline() {
let space_or_newline = SpaceOrNewline;
assert_eq!(format!("{}", space_or_newline), " ");
assert_eq!(format!("{:#}", space_or_newline), "\n");
assert_eq!(format!("{:#}", indent), " line 1\n line 2");
}
}
Loading