use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SqlType {
IntegerPrimaryKey,
Integer,
Text,
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SqlColumn {
pub name: String,
pub sql_type: SqlType,
pub not_null: bool,
}
pub fn accumulate_schema<'a>(
sql_contents: impl IntoIterator<Item = &'a str>,
) -> HashMap<String, Vec<SqlColumn>> {
let mut tables: HashMap<String, Vec<SqlColumn>> = HashMap::new();
for content in sql_contents {
apply_statements(content, &mut tables);
}
tables
}
fn apply_statements(content: &str, tables: &mut HashMap<String, Vec<SqlColumn>>) {
for statement in content.split(';') {
let statement = statement.trim();
if statement.is_empty() {
continue;
}
if let Some(rest) = statement.strip_prefix("CREATE TABLE ") {
apply_create_table(rest, tables);
} else if let Some(rest) = statement.strip_prefix("ALTER TABLE ") {
apply_alter_table(rest, tables);
}
}
}
fn apply_create_table(rest: &str, tables: &mut HashMap<String, Vec<SqlColumn>>) {
let Some(paren_start) = rest.find('(') else {
return;
};
let Some(paren_end) = rest.rfind(')') else {
return;
};
if paren_end <= paren_start {
return;
}
let table_name = rest[..paren_start].trim().to_string();
let body = &rest[paren_start + 1..paren_end];
let columns = body
.split(",\n")
.filter_map(|entry| parse_column_entry(entry.trim()));
tables.entry(table_name).or_default().extend(columns);
}
fn apply_alter_table(rest: &str, tables: &mut HashMap<String, Vec<SqlColumn>>) {
const MARKER: &str = " ADD COLUMN ";
let Some(marker_pos) = rest.find(MARKER) else {
return;
};
let table_name = rest[..marker_pos].trim().to_string();
let column_def = rest[marker_pos + MARKER.len()..].trim();
if let Some(column) = parse_column_entry(column_def) {
tables.entry(table_name).or_default().push(column);
}
}
fn parse_column_entry(entry: &str) -> Option<SqlColumn> {
let entry = entry.trim();
if entry.is_empty() || entry.starts_with("PRIMARY KEY") {
return None;
}
let mut parts = entry.splitn(2, ' ');
let name = parts.next()?.to_string();
let rest = parts.next().unwrap_or("").trim();
let not_null = entry.contains(" NOT NULL");
let sql_type = if rest.starts_with("INTEGER PRIMARY KEY AUTOINCREMENT")
|| rest.starts_with("INTEGER PRIMARY KEY AUTO_INCREMENT")
|| rest.starts_with("SERIAL PRIMARY KEY")
{
SqlType::IntegerPrimaryKey
} else if rest.starts_with("INTEGER") {
SqlType::Integer
} else if rest.starts_with("TEXT") || rest.starts_with("VARCHAR") {
SqlType::Text
} else {
SqlType::Unknown
};
Some(SqlColumn {
name,
sql_type,
not_null,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accumulates_columns_from_a_single_create_table() {
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";
let tables = accumulate_schema([sql]);
let posts = tables.get("posts").unwrap();
assert_eq!(posts.len(), 3);
assert_eq!(posts[0].sql_type, SqlType::IntegerPrimaryKey);
assert_eq!(posts[1].name, "user_id");
assert!(posts[1].not_null);
assert_eq!(posts[2].sql_type, SqlType::Text);
}
#[test]
fn accumulates_a_later_alter_table_add_column_onto_the_same_table() {
let create = "CREATE TABLE posts (\n id INTEGER PRIMARY KEY AUTOINCREMENT\n);\n";
let alter = "ALTER TABLE posts ADD COLUMN content TEXT NOT NULL DEFAULT '';\n";
let tables = accumulate_schema([create, alter]);
let posts = tables.get("posts").unwrap();
assert_eq!(posts.len(), 2);
assert_eq!(posts[1].name, "content");
assert_eq!(posts[1].sql_type, SqlType::Text);
assert!(posts[1].not_null);
}
#[test]
fn a_pivot_tables_composite_primary_key_line_is_not_read_as_a_column() {
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";
let tables = accumulate_schema([sql]);
let post_tag = tables.get("post_tag").unwrap();
assert_eq!(post_tag.len(), 2);
assert!(post_tag.iter().all(|c| c.name != "PRIMARY"));
}
#[test]
fn a_nullable_column_has_no_not_null_flag() {
let sql = "CREATE TABLE posts (\n published_count INTEGER\n);\n";
let tables = accumulate_schema([sql]);
assert!(!tables.get("posts").unwrap()[0].not_null);
}
#[test]
fn an_unrecognized_column_type_is_flagged_unknown_not_guessed_at() {
let sql = "CREATE TABLE posts (\n metadata BLOB\n);\n";
let tables = accumulate_schema([sql]);
assert_eq!(tables.get("posts").unwrap()[0].sql_type, SqlType::Unknown);
}
#[test]
fn mysqls_auto_increment_id_column_is_still_recognized_as_the_primary_key() {
let sql = "CREATE TABLE posts (\n id INTEGER PRIMARY KEY AUTO_INCREMENT\n);\n";
let tables = accumulate_schema([sql]);
assert_eq!(
tables.get("posts").unwrap()[0].sql_type,
SqlType::IntegerPrimaryKey
);
}
#[test]
fn postgres_serial_id_column_is_recognized_as_the_primary_key_not_unknown() {
let sql = "CREATE TABLE posts (\n id SERIAL PRIMARY KEY\n);\n";
let tables = accumulate_schema([sql]);
assert_eq!(
tables.get("posts").unwrap()[0].sql_type,
SqlType::IntegerPrimaryKey
);
}
#[test]
fn mysqls_varchar_string_column_maps_to_the_same_text_type_as_everywhere_else() {
let sql = "CREATE TABLE users (\n email VARCHAR(255) NOT NULL UNIQUE\n);\n";
let tables = accumulate_schema([sql]);
let column = &tables.get("users").unwrap()[0];
assert_eq!(column.sql_type, SqlType::Text);
assert!(column.not_null);
}
}