Skip to content

Commit a496f78

Browse files
authored
pretty-print CREATE TABLE statements (#1854)
1 parent 525ed81 commit a496f78

File tree

3 files changed

+11
-7
lines changed

3 files changed

+11
-7
lines changed

src/ast/dml.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use serde::{Deserialize, Serialize};
2929
#[cfg(feature = "visitor")]
3030
use sqlparser_derive::{Visit, VisitMut};
3131

32-
use crate::display_utils::{indented_list, Indent, SpaceOrNewline};
32+
use crate::display_utils::{indented_list, DisplayCommaSeparated, Indent, NewLine, SpaceOrNewline};
3333

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

@@ -267,14 +267,19 @@ impl Display for CreateTable {
267267
write!(f, " ON CLUSTER {}", on_cluster)?;
268268
}
269269
if !self.columns.is_empty() || !self.constraints.is_empty() {
270-
write!(f, " ({}", display_comma_separated(&self.columns))?;
270+
f.write_str(" (")?;
271+
NewLine.fmt(f)?;
272+
Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
271273
if !self.columns.is_empty() && !self.constraints.is_empty() {
272-
write!(f, ", ")?;
274+
f.write_str(",")?;
275+
SpaceOrNewline.fmt(f)?;
273276
}
274-
write!(f, "{})", display_comma_separated(&self.constraints))?;
277+
Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
278+
NewLine.fmt(f)?;
279+
f.write_str(")")?;
275280
} else if self.query.is_none() && self.like.is_none() && self.clone.is_none() {
276281
// PostgreSQL allows `CREATE TABLE t ();`, but requires empty parens
277-
write!(f, " ()")?;
282+
f.write_str(" ()")?;
278283
}
279284

280285
// Hive table comment should be after column definitions, please refer to:

src/display_utils.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ impl Display for SpaceOrNewline {
6868

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

7373
impl<T: fmt::Display> fmt::Display for DisplayCommaSeparated<'_, T> {
7474
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {

tests/pretty_print.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,6 @@ DELETE
249249
}
250250

251251
#[test]
252-
#[ignore = "https://github.com/apache/datafusion-sqlparser-rs/issues/1850"]
253252
fn test_pretty_print_create_table() {
254253
assert_eq!(
255254
prettify("CREATE TABLE my_table (id INT PRIMARY KEY, name VARCHAR(255) NOT NULL, CONSTRAINT fk_other FOREIGN KEY (id) REFERENCES other_table(id))"),

0 commit comments

Comments
 (0)