larust_convert/models/
fields.rs1use super::schema::{SqlColumn, SqlType};
21use crate::codegen;
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct Field {
25 pub name: String,
26 pub rust_type: String,
27 pub is_primary_key: bool,
28}
29
30pub fn map_columns(columns: &[SqlColumn]) -> Option<Vec<Field>> {
34 columns.iter().map(map_column).collect()
35}
36
37fn map_column(column: &SqlColumn) -> Option<Field> {
38 let (base_type, is_primary_key) = match column.sql_type {
39 SqlType::IntegerPrimaryKey => ("i64", true),
40 SqlType::Integer => ("i64", false),
41 SqlType::Text => ("String", false),
42 SqlType::Unknown => return None,
43 };
44 let rust_type = if !is_primary_key && !column.not_null {
45 format!("Option<{base_type}>")
46 } else {
47 base_type.to_string()
48 };
49 Some(Field {
50 name: column.name.clone(),
51 rust_type,
52 is_primary_key,
53 })
54}
55
56pub fn resolve_table_name(class_name: &str, explicit_table: Option<&str>) -> String {
61 explicit_table
62 .map(str::to_string)
63 .unwrap_or_else(|| codegen::pluralize(&codegen::to_snake_case(class_name)))
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 fn column(name: &str, sql_type: SqlType, not_null: bool) -> SqlColumn {
71 SqlColumn {
72 name: name.to_string(),
73 sql_type,
74 not_null,
75 }
76 }
77
78 #[test]
79 fn maps_a_primary_key_column() {
80 let columns = [column("id", SqlType::IntegerPrimaryKey, false)];
81 let fields = map_columns(&columns).unwrap();
82 assert_eq!(fields[0].rust_type, "i64");
83 assert!(fields[0].is_primary_key);
84 }
85
86 #[test]
87 fn maps_not_null_integer_and_text_columns() {
88 let columns = [
89 column("user_id", SqlType::Integer, true),
90 column("title", SqlType::Text, true),
91 ];
92 let fields = map_columns(&columns).unwrap();
93 assert_eq!(fields[0].rust_type, "i64");
94 assert_eq!(fields[1].rust_type, "String");
95 }
96
97 #[test]
98 fn maps_nullable_columns_to_option() {
99 let columns = [column("bio", SqlType::Text, false)];
100 let fields = map_columns(&columns).unwrap();
101 assert_eq!(fields[0].rust_type, "Option<String>");
102 }
103
104 #[test]
105 fn an_unknown_column_rejects_the_whole_model() {
106 let columns = [
107 column("id", SqlType::IntegerPrimaryKey, false),
108 column("metadata", SqlType::Unknown, true),
109 ];
110 assert!(map_columns(&columns).is_none());
111 }
112
113 #[test]
114 fn resolve_table_name_prefers_the_explicit_property() {
115 assert_eq!(resolve_table_name("Post", Some("blog_posts")), "blog_posts");
116 }
117
118 #[test]
119 fn resolve_table_name_falls_back_to_snake_case_pluralized() {
120 assert_eq!(resolve_table_name("Post", None), "posts");
121 assert_eq!(resolve_table_name("Category", None), "categories");
122 }
123}