larust_convert/models/
schema.rs1use std::collections::HashMap;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum SqlType {
37 IntegerPrimaryKey,
38 Integer,
39 Text,
40 Unknown,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct SqlColumn {
48 pub name: String,
49 pub sql_type: SqlType,
50 pub not_null: bool,
51}
52
53pub fn accumulate_schema<'a>(
58 sql_contents: impl IntoIterator<Item = &'a str>,
59) -> HashMap<String, Vec<SqlColumn>> {
60 let mut tables: HashMap<String, Vec<SqlColumn>> = HashMap::new();
61 for content in sql_contents {
62 apply_statements(content, &mut tables);
63 }
64 tables
65}
66
67fn apply_statements(content: &str, tables: &mut HashMap<String, Vec<SqlColumn>>) {
68 for statement in content.split(';') {
69 let statement = statement.trim();
70 if statement.is_empty() {
71 continue;
72 }
73 if let Some(rest) = statement.strip_prefix("CREATE TABLE ") {
74 apply_create_table(rest, tables);
75 } else if let Some(rest) = statement.strip_prefix("ALTER TABLE ") {
76 apply_alter_table(rest, tables);
77 }
78 }
79}
80
81fn apply_create_table(rest: &str, tables: &mut HashMap<String, Vec<SqlColumn>>) {
82 let Some(paren_start) = rest.find('(') else {
83 return;
84 };
85 let Some(paren_end) = rest.rfind(')') else {
86 return;
87 };
88 if paren_end <= paren_start {
89 return;
90 }
91 let table_name = rest[..paren_start].trim().to_string();
92 let body = &rest[paren_start + 1..paren_end];
93 let columns = body
94 .split(",\n")
95 .filter_map(|entry| parse_column_entry(entry.trim()));
96 tables.entry(table_name).or_default().extend(columns);
97}
98
99fn apply_alter_table(rest: &str, tables: &mut HashMap<String, Vec<SqlColumn>>) {
100 const MARKER: &str = " ADD COLUMN ";
101 let Some(marker_pos) = rest.find(MARKER) else {
102 return;
103 };
104 let table_name = rest[..marker_pos].trim().to_string();
105 let column_def = rest[marker_pos + MARKER.len()..].trim();
106 if let Some(column) = parse_column_entry(column_def) {
107 tables.entry(table_name).or_default().push(column);
108 }
109}
110
111fn parse_column_entry(entry: &str) -> Option<SqlColumn> {
116 let entry = entry.trim();
117 if entry.is_empty() || entry.starts_with("PRIMARY KEY") {
118 return None;
119 }
120 let mut parts = entry.splitn(2, ' ');
121 let name = parts.next()?.to_string();
122 let rest = parts.next().unwrap_or("").trim();
123 let not_null = entry.contains(" NOT NULL");
124 let sql_type = if rest.starts_with("INTEGER PRIMARY KEY AUTOINCREMENT")
131 || rest.starts_with("INTEGER PRIMARY KEY AUTO_INCREMENT")
132 || rest.starts_with("SERIAL PRIMARY KEY")
133 {
134 SqlType::IntegerPrimaryKey
135 } else if rest.starts_with("INTEGER") {
136 SqlType::Integer
137 } else if rest.starts_with("TEXT") || rest.starts_with("VARCHAR") {
138 SqlType::Text
144 } else {
145 SqlType::Unknown
146 };
147 Some(SqlColumn {
148 name,
149 sql_type,
150 not_null,
151 })
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157
158 #[test]
159 fn accumulates_columns_from_a_single_create_table() {
160 let sql = "CREATE TABLE posts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n user_id INTEGER NOT NULL REFERENCES users(id),\n title TEXT NOT NULL\n);\n";
161 let tables = accumulate_schema([sql]);
162 let posts = tables.get("posts").unwrap();
163 assert_eq!(posts.len(), 3);
164 assert_eq!(posts[0].sql_type, SqlType::IntegerPrimaryKey);
165 assert_eq!(posts[1].name, "user_id");
166 assert!(posts[1].not_null);
167 assert_eq!(posts[2].sql_type, SqlType::Text);
168 }
169
170 #[test]
171 fn accumulates_a_later_alter_table_add_column_onto_the_same_table() {
172 let create = "CREATE TABLE posts (\n id INTEGER PRIMARY KEY AUTOINCREMENT\n);\n";
173 let alter = "ALTER TABLE posts ADD COLUMN content TEXT NOT NULL DEFAULT '';\n";
174 let tables = accumulate_schema([create, alter]);
175 let posts = tables.get("posts").unwrap();
176 assert_eq!(posts.len(), 2);
177 assert_eq!(posts[1].name, "content");
178 assert_eq!(posts[1].sql_type, SqlType::Text);
179 assert!(posts[1].not_null);
180 }
181
182 #[test]
183 fn a_pivot_tables_composite_primary_key_line_is_not_read_as_a_column() {
184 let sql = "CREATE TABLE post_tag (\n post_id INTEGER NOT NULL REFERENCES posts(id),\n tag_id INTEGER NOT NULL REFERENCES tags(id),\n PRIMARY KEY (post_id, tag_id)\n);\n";
185 let tables = accumulate_schema([sql]);
186 let post_tag = tables.get("post_tag").unwrap();
187 assert_eq!(post_tag.len(), 2);
188 assert!(post_tag.iter().all(|c| c.name != "PRIMARY"));
189 }
190
191 #[test]
192 fn a_nullable_column_has_no_not_null_flag() {
193 let sql = "CREATE TABLE posts (\n published_count INTEGER\n);\n";
194 let tables = accumulate_schema([sql]);
195 assert!(!tables.get("posts").unwrap()[0].not_null);
196 }
197
198 #[test]
199 fn an_unrecognized_column_type_is_flagged_unknown_not_guessed_at() {
200 let sql = "CREATE TABLE posts (\n metadata BLOB\n);\n";
201 let tables = accumulate_schema([sql]);
202 assert_eq!(tables.get("posts").unwrap()[0].sql_type, SqlType::Unknown);
203 }
204
205 #[test]
206 fn mysqls_auto_increment_id_column_is_still_recognized_as_the_primary_key() {
207 let sql = "CREATE TABLE posts (\n id INTEGER PRIMARY KEY AUTO_INCREMENT\n);\n";
208 let tables = accumulate_schema([sql]);
209 assert_eq!(
210 tables.get("posts").unwrap()[0].sql_type,
211 SqlType::IntegerPrimaryKey
212 );
213 }
214
215 #[test]
216 fn postgres_serial_id_column_is_recognized_as_the_primary_key_not_unknown() {
217 let sql = "CREATE TABLE posts (\n id SERIAL PRIMARY KEY\n);\n";
218 let tables = accumulate_schema([sql]);
219 assert_eq!(
220 tables.get("posts").unwrap()[0].sql_type,
221 SqlType::IntegerPrimaryKey
222 );
223 }
224
225 #[test]
226 fn mysqls_varchar_string_column_maps_to_the_same_text_type_as_everywhere_else() {
227 let sql = "CREATE TABLE users (\n email VARCHAR(255) NOT NULL UNIQUE\n);\n";
228 let tables = accumulate_schema([sql]);
229 let column = &tables.get("users").unwrap()[0];
230 assert_eq!(column.sql_type, SqlType::Text);
231 assert!(column.not_null);
232 }
233}