Skip to main content

larust_convert/models/
fields.rs

1//! SQL column -> Rust field type mapping, plus table-name resolution.
2//! Whole-struct safety lives here: [`map_columns`] returns `None` if any
3//! column's type isn't recognized, rejecting the entire model rather
4//! than emitting a partially-wrong struct - a model field is load-bearing
5//! for every query the struct participates in (`sqlx::FromRow`,
6//! `SELECT *`/`INSERT ... RETURNING *`), unlike a form-request field
7//! (Phase 2a), which is independently safe to drop.
8//!
9//! **A real, permanent, documented limitation**: Phase 1's own migration
10//! converter already maps both `boolean` and `integer`/`bigInteger`
11//! Blueprint calls to the identical SQL type `INTEGER` - by the time this
12//! module reads that output, the boolean/integer distinction is
13//! unrecoverably lost. Every `INTEGER` column becomes `i64`, never
14//! `bool`. This is accepted as a permanent gap (the same shape as
15//! `migrations.rs`'s own `timestamps()` precedent: emitted, never fully
16//! converted) rather than reaching back into raw PHP for one field's
17//! typing, which would reopen the consistency problem `schema.rs`'s own
18//! doc comment explains.
19
20use 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
30/// Maps every column of one table into Rust fields - `None` if *any*
31/// column's SQL type isn't recognized (whole-struct safety, see this
32/// module's own doc comment).
33pub 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
56/// The table name a Laravel model resolves to: an explicit `protected
57/// $table = '...'` property always wins; otherwise Laravel's own default
58/// (snake_case + pluralize of the class name) - reusing `codegen`'s
59/// existing helpers directly, no new inference needed.
60pub 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}