From 52938b864e7d53ecf1b7f1d38009b1f0fa690657 Mon Sep 17 00:00:00 2001 From: lovasoa Date: Fri, 16 May 2025 22:08:05 +0200 Subject: [PATCH] pretty-print CREATE TABLE statements update the createtable display impl --- src/ast/dml.rs | 15 ++++++++++----- src/display_utils.rs | 2 +- tests/pretty_print.rs | 1 - 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/ast/dml.rs b/src/ast/dml.rs index e4081a637..da82a4ede 100644 --- a/src/ast/dml.rs +++ b/src/ast/dml.rs @@ -29,7 +29,7 @@ use serde::{Deserialize, Serialize}; #[cfg(feature = "visitor")] use sqlparser_derive::{Visit, VisitMut}; -use crate::display_utils::{indented_list, Indent, SpaceOrNewline}; +use crate::display_utils::{indented_list, DisplayCommaSeparated, Indent, NewLine, SpaceOrNewline}; pub use super::ddl::{ColumnDef, TableConstraint}; @@ -267,14 +267,19 @@ impl Display for CreateTable { write!(f, " ON CLUSTER {}", on_cluster)?; } if !self.columns.is_empty() || !self.constraints.is_empty() { - write!(f, " ({}", display_comma_separated(&self.columns))?; + f.write_str(" (")?; + NewLine.fmt(f)?; + Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?; if !self.columns.is_empty() && !self.constraints.is_empty() { - write!(f, ", ")?; + f.write_str(",")?; + SpaceOrNewline.fmt(f)?; } - write!(f, "{})", display_comma_separated(&self.constraints))?; + Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?; + NewLine.fmt(f)?; + f.write_str(")")?; } else if self.query.is_none() && self.like.is_none() && self.clone.is_none() { // PostgreSQL allows `CREATE TABLE t ();`, but requires empty parens - write!(f, " ()")?; + f.write_str(" ()")?; } // Hive table comment should be after column definitions, please refer to: diff --git a/src/display_utils.rs b/src/display_utils.rs index 849aea941..e594a34ef 100644 --- a/src/display_utils.rs +++ b/src/display_utils.rs @@ -68,7 +68,7 @@ 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(crate) struct DisplayCommaSeparated<'a, T: fmt::Display>(&'a [T]); +pub(crate) struct DisplayCommaSeparated<'a, T: fmt::Display>(pub(crate) &'a [T]); impl fmt::Display for DisplayCommaSeparated<'_, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { diff --git a/tests/pretty_print.rs b/tests/pretty_print.rs index b4adbe352..d6794218b 100644 --- a/tests/pretty_print.rs +++ b/tests/pretty_print.rs @@ -249,7 +249,6 @@ DELETE } #[test] -#[ignore = "https://github.com/apache/datafusion-sqlparser-rs/issues/1850"] fn test_pretty_print_create_table() { assert_eq!( prettify("CREATE TABLE my_table (id INT PRIMARY KEY, name VARCHAR(255) NOT NULL, CONSTRAINT fk_other FOREIGN KEY (id) REFERENCES other_table(id))"),