1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
use {
crate::ast::{ColumnDef, ColumnOption, ColumnOptionDef, Expr, Statement, ToSql},
serde::{Deserialize, Serialize},
std::{fmt::Debug, iter},
strum_macros::Display,
};
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Display)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum SchemaIndexOrd {
Asc,
Desc,
Both,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct SchemaIndex {
pub name: String,
pub expr: Expr,
pub order: SchemaIndexOrd,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Schema {
pub table_name: String,
pub column_defs: Vec<ColumnDef>,
pub indexes: Vec<SchemaIndex>,
}
impl Schema {
pub fn to_ddl(self) -> String {
let Schema {
table_name,
column_defs: columns,
indexes,
..
} = self;
let create_table = Statement::CreateTable {
if_not_exists: false,
name: table_name.clone(),
columns,
source: None,
}
.to_sql();
let create_indexes = indexes.iter().map(|SchemaIndex { name, expr, .. }| {
let expr = expr.to_sql();
let table_name = &table_name;
format!("CREATE INDEX {name} ON {table_name} ({expr});")
});
iter::once(create_table)
.chain(create_indexes)
.collect::<Vec<_>>()
.join("\n")
}
}
pub trait ColumnDefExt {
fn is_nullable(&self) -> bool;
fn get_default(&self) -> Option<&Expr>;
}
impl ColumnDefExt for ColumnDef {
fn is_nullable(&self) -> bool {
self.options
.iter()
.any(|ColumnOptionDef { option, .. }| option == &ColumnOption::Null)
}
fn get_default(&self) -> Option<&Expr> {
self.options
.iter()
.find_map(|ColumnOptionDef { option, .. }| match option {
ColumnOption::Default(expr) => Some(expr),
_ => None,
})
}
}
#[cfg(test)]
mod tests {
use crate::{
ast::{
AstLiteral, ColumnDef,
ColumnOption::{self, Unique},
ColumnOptionDef, Expr,
},
data::{Schema, SchemaIndex, SchemaIndexOrd},
prelude::DataType,
};
#[test]
fn table_basic() {
let schema = Schema {
table_name: "User".to_owned(),
column_defs: vec![
ColumnDef {
name: "id".to_owned(),
data_type: DataType::Int,
options: Vec::new(),
},
ColumnDef {
name: "name".to_owned(),
data_type: DataType::Text,
options: vec![
ColumnOptionDef {
name: None,
option: ColumnOption::Null,
},
ColumnOptionDef {
name: None,
option: ColumnOption::Default(Expr::Literal(AstLiteral::QuotedString(
"glue".to_owned(),
))),
},
],
},
],
indexes: Vec::new(),
};
assert_eq!(
schema.to_ddl(),
"CREATE TABLE User (id INT, name TEXT NULL DEFAULT 'glue');"
)
}
#[test]
fn table_primary() {
let schema = Schema {
table_name: "User".to_owned(),
column_defs: vec![ColumnDef {
name: "id".to_owned(),
data_type: DataType::Int,
options: vec![ColumnOptionDef {
name: None,
option: Unique { is_primary: true },
}],
}],
indexes: Vec::new(),
};
assert_eq!(schema.to_ddl(), "CREATE TABLE User (id INT PRIMARY KEY);");
}
#[test]
fn table_with_index() {
let schema = Schema {
table_name: "User".to_owned(),
column_defs: vec![
ColumnDef {
name: "id".to_owned(),
data_type: DataType::Int,
options: Vec::new(),
},
ColumnDef {
name: "name".to_owned(),
data_type: DataType::Text,
options: Vec::new(),
},
],
indexes: vec![
SchemaIndex {
name: "User_id".to_owned(),
expr: Expr::Identifier("id".to_owned()),
order: SchemaIndexOrd::Both,
},
SchemaIndex {
name: "User_name".to_owned(),
expr: Expr::Identifier("name".to_owned()),
order: SchemaIndexOrd::Both,
},
],
};
assert_eq!(
schema.to_ddl(),
"CREATE TABLE User (id INT, name TEXT);
CREATE INDEX User_id ON User (id);
CREATE INDEX User_name ON User (name);"
);
}
}