Skip to content

Commit 1fa3ee0

Browse files
committed
implement fmt::Display instead of ToString
1 parent cdba436 commit 1fa3ee0

File tree

8 files changed

+605
-550
lines changed

8 files changed

+605
-550
lines changed

src/ast/data_type.rs

Lines changed: 38 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
// limitations under the License.
1212

1313
use super::ObjectName;
14+
use std::fmt;
1415

1516
/// SQL data types
1617
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -65,47 +66,53 @@ pub enum DataType {
6566
Array(Box<DataType>),
6667
}
6768

68-
impl ToString for DataType {
69-
fn to_string(&self) -> String {
69+
impl fmt::Display for DataType {
70+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7071
match self {
71-
DataType::Char(size) => format_type_with_optional_length("char", size),
72-
DataType::Varchar(size) => format_type_with_optional_length("character varying", size),
73-
DataType::Uuid => "uuid".to_string(),
74-
DataType::Clob(size) => format!("clob({})", size),
75-
DataType::Binary(size) => format!("binary({})", size),
76-
DataType::Varbinary(size) => format!("varbinary({})", size),
77-
DataType::Blob(size) => format!("blob({})", size),
72+
DataType::Char(size) => format_type_with_optional_length(f, "char", size),
73+
DataType::Varchar(size) => {
74+
format_type_with_optional_length(f, "character varying", size)
75+
}
76+
DataType::Uuid => write!(f, "uuid"),
77+
DataType::Clob(size) => write!(f, "clob({})", size),
78+
DataType::Binary(size) => write!(f, "binary({})", size),
79+
DataType::Varbinary(size) => write!(f, "varbinary({})", size),
80+
DataType::Blob(size) => write!(f, "blob({})", size),
7881
DataType::Decimal(precision, scale) => {
7982
if let Some(scale) = scale {
80-
format!("numeric({},{})", precision.unwrap(), scale)
83+
write!(f, "numeric({},{})", precision.unwrap(), scale)
8184
} else {
82-
format_type_with_optional_length("numeric", precision)
85+
format_type_with_optional_length(f, "numeric", precision)
8386
}
8487
}
85-
DataType::Float(size) => format_type_with_optional_length("float", size),
86-
DataType::SmallInt => "smallint".to_string(),
87-
DataType::Int => "int".to_string(),
88-
DataType::BigInt => "bigint".to_string(),
89-
DataType::Real => "real".to_string(),
90-
DataType::Double => "double".to_string(),
91-
DataType::Boolean => "boolean".to_string(),
92-
DataType::Date => "date".to_string(),
93-
DataType::Time => "time".to_string(),
94-
DataType::Timestamp => "timestamp".to_string(),
95-
DataType::Interval => "interval".to_string(),
96-
DataType::Regclass => "regclass".to_string(),
97-
DataType::Text => "text".to_string(),
98-
DataType::Bytea => "bytea".to_string(),
99-
DataType::Array(ty) => format!("{}[]", ty.to_string()),
100-
DataType::Custom(ty) => ty.to_string(),
88+
DataType::Float(size) => format_type_with_optional_length(f, "float", size),
89+
DataType::SmallInt => write!(f, "smallint"),
90+
DataType::Int => write!(f, "int"),
91+
DataType::BigInt => write!(f, "bigint"),
92+
DataType::Real => write!(f, "real"),
93+
DataType::Double => write!(f, "double"),
94+
DataType::Boolean => write!(f, "boolean"),
95+
DataType::Date => write!(f, "date"),
96+
DataType::Time => write!(f, "time"),
97+
DataType::Timestamp => write!(f, "timestamp"),
98+
DataType::Interval => write!(f, "interval"),
99+
DataType::Regclass => write!(f, "regclass"),
100+
DataType::Text => write!(f, "text"),
101+
DataType::Bytea => write!(f, "bytea"),
102+
DataType::Array(ty) => write!(f, "{}[]", ty),
103+
DataType::Custom(ty) => write!(f, "{}", ty),
101104
}
102105
}
103106
}
104107

105-
fn format_type_with_optional_length(sql_type: &str, len: &Option<u64>) -> String {
106-
let mut s = sql_type.to_string();
108+
fn format_type_with_optional_length(
109+
f: &mut fmt::Formatter,
110+
sql_type: &'static str,
111+
len: &Option<u64>,
112+
) -> fmt::Result {
113+
write!(f, "{}", sql_type)?;
107114
if let Some(len) = len {
108-
s += &format!("({})", len);
115+
write!(f, "({})", len)?;
109116
}
110-
s
117+
Ok(())
111118
}

src/ast/ddl.rs

Lines changed: 53 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! AST types specific to CREATE/ALTER variants of `SQLStatement`
22
//! (commonly referred to as Data Definition Language, or DDL)
3-
use super::{DataType, Expr, Ident, ObjectName};
3+
use super::{display_comma_separated, DataType, Expr, Ident, ObjectName};
4+
use std::fmt;
45

56
/// An `ALTER TABLE` (`SQLStatement::SQLAlterTable`) operation
67
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -11,11 +12,11 @@ pub enum AlterTableOperation {
1112
DropConstraint { name: Ident },
1213
}
1314

14-
impl ToString for AlterTableOperation {
15-
fn to_string(&self) -> String {
15+
impl fmt::Display for AlterTableOperation {
16+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1617
match self {
17-
AlterTableOperation::AddConstraint(c) => format!("ADD {}", c.to_string()),
18-
AlterTableOperation::DropConstraint { name } => format!("DROP CONSTRAINT {}", name),
18+
AlterTableOperation::AddConstraint(c) => write!(f, "ADD {}", c),
19+
AlterTableOperation::DropConstraint { name } => write!(f, "DROP CONSTRAINT {}", name),
1920
}
2021
}
2122
}
@@ -46,36 +47,36 @@ pub enum TableConstraint {
4647
},
4748
}
4849

49-
impl ToString for TableConstraint {
50-
fn to_string(&self) -> String {
50+
impl fmt::Display for TableConstraint {
51+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5152
match self {
5253
TableConstraint::Unique {
5354
name,
5455
columns,
5556
is_primary,
56-
} => format!(
57+
} => write!(
58+
f,
5759
"{}{} ({})",
58-
format_constraint_name(name),
60+
display_constraint_name(name),
5961
if *is_primary { "PRIMARY KEY" } else { "UNIQUE" },
60-
columns.join(", ")
62+
display_comma_separated(columns)
6163
),
6264
TableConstraint::ForeignKey {
6365
name,
6466
columns,
6567
foreign_table,
6668
referred_columns,
67-
} => format!(
69+
} => write!(
70+
f,
6871
"{}FOREIGN KEY ({}) REFERENCES {}({})",
69-
format_constraint_name(name),
70-
columns.join(", "),
71-
foreign_table.to_string(),
72-
referred_columns.join(", ")
73-
),
74-
TableConstraint::Check { name, expr } => format!(
75-
"{}CHECK ({})",
76-
format_constraint_name(name),
77-
expr.to_string()
72+
display_constraint_name(name),
73+
display_comma_separated(columns),
74+
foreign_table,
75+
display_comma_separated(referred_columns)
7876
),
77+
TableConstraint::Check { name, expr } => {
78+
write!(f, "{}CHECK ({})", display_constraint_name(name), expr)
79+
}
7980
}
8081
}
8182
}
@@ -89,18 +90,13 @@ pub struct ColumnDef {
8990
pub options: Vec<ColumnOptionDef>,
9091
}
9192

92-
impl ToString for ColumnDef {
93-
fn to_string(&self) -> String {
94-
format!(
95-
"{} {}{}",
96-
self.name,
97-
self.data_type.to_string(),
98-
self.options
99-
.iter()
100-
.map(|c| format!(" {}", c.to_string()))
101-
.collect::<Vec<_>>()
102-
.join("")
103-
)
93+
impl fmt::Display for ColumnDef {
94+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
95+
write!(f, "{} {}", self.name, self.data_type)?;
96+
for option in &self.options {
97+
write!(f, " {}", option)?;
98+
}
99+
Ok(())
104100
}
105101
}
106102

@@ -126,13 +122,9 @@ pub struct ColumnOptionDef {
126122
pub option: ColumnOption,
127123
}
128124

129-
impl ToString for ColumnOptionDef {
130-
fn to_string(&self) -> String {
131-
format!(
132-
"{}{}",
133-
format_constraint_name(&self.name),
134-
self.option.to_string()
135-
)
125+
impl fmt::Display for ColumnOptionDef {
126+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
127+
write!(f, "{}{}", display_constraint_name(&self.name), self.option)
136128
}
137129
}
138130

@@ -160,35 +152,39 @@ pub enum ColumnOption {
160152
Check(Expr),
161153
}
162154

163-
impl ToString for ColumnOption {
164-
fn to_string(&self) -> String {
155+
impl fmt::Display for ColumnOption {
156+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165157
use ColumnOption::*;
166158
match self {
167-
Null => "NULL".to_string(),
168-
NotNull => "NOT NULL".to_string(),
169-
Default(expr) => format!("DEFAULT {}", expr.to_string()),
159+
Null => write!(f, "NULL"),
160+
NotNull => write!(f, "NOT NULL"),
161+
Default(expr) => write!(f, "DEFAULT {}", expr),
170162
Unique { is_primary } => {
171-
if *is_primary {
172-
"PRIMARY KEY".to_string()
173-
} else {
174-
"UNIQUE".to_string()
175-
}
163+
write!(f, "{}", if *is_primary { "PRIMARY KEY" } else { "UNIQUE" })
176164
}
177165
ForeignKey {
178166
foreign_table,
179167
referred_columns,
180-
} => format!(
168+
} => write!(
169+
f,
181170
"REFERENCES {} ({})",
182-
foreign_table.to_string(),
183-
referred_columns.join(", ")
171+
foreign_table,
172+
display_comma_separated(referred_columns)
184173
),
185-
Check(expr) => format!("CHECK ({})", expr.to_string(),),
174+
Check(expr) => write!(f, "CHECK ({})", expr),
186175
}
187176
}
188177
}
189178

190-
fn format_constraint_name(name: &Option<Ident>) -> String {
191-
name.as_ref()
192-
.map(|name| format!("CONSTRAINT {} ", name))
193-
.unwrap_or_default()
179+
fn display_constraint_name<'a>(name: &'a Option<Ident>) -> impl fmt::Display + 'a {
180+
struct ConstraintName<'a>(&'a Option<Ident>);
181+
impl<'a> fmt::Display for ConstraintName<'a> {
182+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
183+
if let Some(name) = self.0 {
184+
write!(f, "CONSTRAINT {} ", name)?;
185+
}
186+
Ok(())
187+
}
188+
}
189+
ConstraintName(name)
194190
}

0 commit comments

Comments
 (0)