Skip to main content

larust_convert/models/
mod.rs

1//! `app/Models/*.php` → `#[derive(Model)]` structs, with relationships.
2//! Split into `schema` (reads Phase 1's own converted SQL - the
3//! authoritative field source), `fields` (SQL→Rust type mapping,
4//! whole-struct safety), `relations` (relationship detection + verified
5//! Laravel default-argument inference, per-attribute safety), and
6//! `inferred_fields` (the no-migration fallback - see its own doc
7//! comment) - mirroring `larust-macros`'s own `model.rs`/`relations.rs`/
8//! `belongs_to_many.rs` split. See `docs/ARCHITECTURE.md`'s "Laravel
9//! conversion" section for the whole-struct-vs-per-attribute safety
10//! rationale.
11
12pub mod fields;
13pub mod inferred_fields;
14pub mod relations;
15pub mod schema;
16
17use crate::php;
18use schema::SqlColumn;
19
20pub struct ConvertedModel {
21    pub struct_name: String,
22    pub content: String,
23    /// Per-relationship methods that looked like they were attempting a
24    /// relationship but used a shape this phase doesn't support -
25    /// flagged, not fatal to the rest of the model (per-attribute
26    /// safety; see `relations.rs`'s own doc comment).
27    pub relation_notes: Vec<String>,
28    /// `Some(note)` when this model's table has no migration and its
29    /// fields came from `inferred_fields::infer` instead (a table
30    /// managed by a remote/external database, the common real-world
31    /// case this phase can't refuse to support just because there's no
32    /// local schema to check against) - the caller folds this into
33    /// `CONVERSION_REPORT.md` as its own manual-review category, distinct
34    /// from `relation_notes` and from an outright conversion failure:
35    /// the model DID convert, just with guessed field types that need
36    /// verifying against the real schema. `None` for a normal,
37    /// migration-verified model.
38    pub schema_note: Option<String>,
39}
40
41/// Converts one `app/Models/*.php` file. `tables` is the accumulated
42/// per-table column map from `schema::accumulate_schema`, already built
43/// from every one of *this app's* converted migration files. `Err`
44/// rejects the whole model only when its class/body can't be read at
45/// all, or its table's migration-derived columns include a type this
46/// phase doesn't recognize (whole-struct safety - see `fields.rs`'s own
47/// doc comment: a wrong `sqlx::FromRow` type panics or errors on every
48/// query against a *known* schema, so a genuinely bad guess there really
49/// does have to be rejected). A table with **no** migration at all is a
50/// different case, not an error - see `inferred_fields`'s own doc
51/// comment for why there's no schema to be wrong *against* in that case,
52/// so this phase still converts the model, from best-effort guessed
53/// fields, rather than refusing outright.
54pub fn convert(
55    source: &str,
56    class_name: &str,
57    tables: &std::collections::HashMap<String, Vec<SqlColumn>>,
58) -> Result<Option<ConvertedModel>, String> {
59    let tree = php::parse(source).map_err(|e| e.to_string())?;
60    if php::has_syntax_error(&tree) {
61        return Ok(None);
62    }
63    let Some(class_node) = php::find_class(&tree, source, class_name) else {
64        return Ok(None);
65    };
66
67    let explicit_table = find_table_property(class_node, source);
68    let table_name = fields::resolve_table_name(class_name, explicit_table.as_deref());
69
70    let mut relation_list = Vec::new();
71    let mut relation_notes = Vec::new();
72    let Some(body) = class_node.child_by_field_name("body") else {
73        return Err(format!("class `{class_name}` has no body"));
74    };
75    for method in php::direct_children_of_kind(body, "method_declaration") {
76        let Some(method_name_node) = method.child_by_field_name("name") else {
77            continue;
78        };
79        let Ok(method_name) = method_name_node.utf8_text(source.as_bytes()) else {
80            continue;
81        };
82        let Some(method_body) = method.child_by_field_name("body") else {
83            continue;
84        };
85        match relations::parse_relation(class_name, method_name, method_body, source) {
86            Ok(Some(relation)) => relation_list.push(relation),
87            Ok(None) => {}
88            Err(reason) => relation_notes.push(reason),
89        }
90    }
91
92    let (model_fields, schema_note) = match tables.get(&table_name) {
93        Some(columns) => {
94            let Some(model_fields) = fields::map_columns(columns) else {
95                return Err(format!(
96                    "table `{table_name}` has a column type this phase doesn't recognize; model `{class_name}` not converted"
97                ));
98            };
99            (model_fields, None)
100        }
101        None => {
102            let model_fields: Vec<fields::Field> =
103                inferred_fields::infer(class_node, source, &relation_list)
104                    .into_iter()
105                    .map(|f| fields::Field {
106                        name: f.name,
107                        rust_type: f.rust_type,
108                        is_primary_key: f.is_primary_key,
109                    })
110                    .collect();
111
112            // Every relationship kind's generated code assumes its own
113            // foreign-key field is `i64` somewhere - `belongsTo`'s
114            // explicitly (a real compile-time backstop, see `relations.
115            // rs`'s own doc comment), `hasMany`/`hasOne`/`belongsToMany`
116            // implicitly (no custom rejection message, but the *related*
117            // struct's own FK field still has to type-check against the
118            // macro-generated code that reads it). A migration-verified
119            // model can rely on `fields.rs`'s own `i64`-for-integer-
120            // columns convention to make that hold; an inferred model
121            // can't - its own fields might disagree with the `_id`
122            // convention (a `$casts` override, real source: `Blogs::
123            // $casts['categories_id'] = 'array'`), and there's no way to
124            // check the *related* struct's own inferred fields from
125            // inside this one file's own `convert()` call (each model
126            // file converts independently). Rather than risk emitting a
127            // relationship attribute that only sometimes fails to
128            // compile depending on what the related model's own
129            // inference produced, every relationship on an inferred
130            // model - either side - is deferred to a manual port.
131            for relation in std::mem::take(&mut relation_list) {
132                relation_notes.push(format!(
133                    "{}(): schema for `{table_name}` was inferred, not migration-verified - \
134                     relationship attribute omitted rather than risking a foreign-key type \
135                     mismatch; port it by hand once the real column types are confirmed",
136                    relations::method_name(&relation)
137                ));
138            }
139
140            let note = format!(
141                "no migration creates table `{table_name}` (resolved for model `{class_name}`) \
142                 - fields inferred from its own $fillable/$casts/relationships instead; verify \
143                 every type against the real (often remote or externally managed) database \
144                 schema before relying on this in production"
145            );
146            (model_fields, Some(note))
147        }
148    };
149
150    let content = render(
151        class_name,
152        &table_name,
153        &model_fields,
154        &relation_list,
155        schema_note.as_deref(),
156    );
157    Ok(Some(ConvertedModel {
158        struct_name: class_name.to_string(),
159        content,
160        relation_notes,
161        schema_note,
162    }))
163}
164
165/// Reads a Laravel model class's own `protected $NAME = ...` property's
166/// raw default-value AST node, if declared - shared by
167/// `find_table_property` (this file) and `inferred_fields`'s own
168/// `$fillable`/`$casts`/`$primaryKey`/`$timestamps` readers.
169pub(super) fn find_property_default<'a>(
170    class_node: tree_sitter::Node<'a>,
171    source: &str,
172    name: &str,
173) -> Option<tree_sitter::Node<'a>> {
174    let bytes = source.as_bytes();
175    let body = class_node.child_by_field_name("body")?;
176    for declaration in php::direct_children_of_kind(body, "property_declaration") {
177        for element in php::direct_children_of_kind(declaration, "property_element") {
178            let name_node = element.child_by_field_name("name")?;
179            let prop_name = name_node.named_child(0)?.utf8_text(bytes).ok()?;
180            if prop_name != name {
181                continue;
182            }
183            return element.child_by_field_name("default_value");
184        }
185    }
186    None
187}
188
189/// Reads a Laravel model class's own `protected $table = '...'`
190/// property, if declared - an explicit table name always wins over
191/// `fields::resolve_table_name`'s default inference.
192fn find_table_property(class_node: tree_sitter::Node, source: &str) -> Option<String> {
193    let default_value = find_property_default(class_node, source, "table")?;
194    if default_value.kind() == "string" {
195        return Some(php::unquote(
196            default_value.utf8_text(source.as_bytes()).ok()?,
197        ));
198    }
199    None
200}
201
202fn render(
203    struct_name: &str,
204    table_name: &str,
205    model_fields: &[fields::Field],
206    relation_list: &[relations::Relation],
207    schema_note: Option<&str>,
208) -> String {
209    let mut out = String::from("use larust_support::orm::sqlx;\nuse larust_support::Model;\n");
210
211    // Every `#[belongs_to(Related, ...)]`-shaped attribute below references
212    // `Related` bare - without importing it, the generated model wouldn't
213    // compile. Self-referential relations (a model relating to its own
214    // type) need no import; that type is already in scope.
215    let mut related_types: Vec<&str> = relation_list
216        .iter()
217        .map(relations::related_type_name)
218        .filter(|name| *name != struct_name)
219        .collect();
220    related_types.sort_unstable();
221    related_types.dedup();
222    if !related_types.is_empty() {
223        out.push_str(&format!(
224            "use crate::models::{{{}}};\n",
225            related_types.join(", ")
226        ));
227    }
228    out.push('\n');
229
230    if let Some(note) = schema_note {
231        out.push_str(&format!("// TODO: {note}\n"));
232    }
233    out.push_str("#[derive(Model, sqlx::FromRow)]\n");
234    out.push_str(&format!("#[table(\"{table_name}\")]\n"));
235    for relation in relation_list {
236        out.push_str(&relations::render(relation));
237        out.push('\n');
238    }
239    out.push_str(&format!("pub struct {struct_name} {{\n"));
240    for field in model_fields {
241        if field.is_primary_key {
242            out.push_str("    #[primary_key]\n");
243        }
244        out.push_str(&format!("    pub {}: {},\n", field.name, field.rust_type));
245    }
246    out.push_str("}\n");
247
248    if struct_name == "User" {
249        out.push_str(&render_authenticatable_impl(model_fields));
250    }
251
252    out
253}
254
255/// Laravel's authenticatable user model needs to satisfy
256/// `larust_support::auth::Authenticatable` for `Policy<User>` (and
257/// anything else authorization-gated) to compile against it - mirrors
258/// `scaffold.rs`'s own `USER_MODEL_RS` template exactly. Applied whenever
259/// the converted class is literally named `User`, matching Laravel's own
260/// default `config('auth.providers.users.model')` convention. Uses the
261/// model's own resolved primary-key field name (not a hardcoded `id`).
262///
263/// `Authenticatable::auth_id` is a fixed `-> i64` trait method (see
264/// `larust-auth`'s own definition) - a migration-derived primary key is
265/// always `i64` (`fields.rs` only ever maps one to `i64` +
266/// `#[primary_key]`), but `inferred_fields::infer` can type one `String`
267/// instead (a `HasUuids` model with no migration). Emitting the impl
268/// anyway in that case would generate code that doesn't compile (an
269/// `i64`-returning method body that's actually a `String`) - so this
270/// only emits the impl when the primary key really is `i64`, and leaves
271/// a comment for the (rare) non-integer case instead.
272fn render_authenticatable_impl(model_fields: &[fields::Field]) -> String {
273    let Some(pk) = model_fields.iter().find(|f| f.is_primary_key) else {
274        return String::new();
275    };
276    if pk.rust_type != "i64" {
277        return format!(
278            "\n// TODO: `{struct_name}`'s primary key (`{pk_name}: {pk_type}`) isn't `i64`, so \
279             it can't implement `larust_support::auth::Authenticatable` (its `auth_id` method is \
280             fixed to `-> i64`) - implement it by hand once the real key type is confirmed.\n",
281            struct_name = "User",
282            pk_name = pk.name,
283            pk_type = pk.rust_type,
284        );
285    }
286    let pk_name = &pk.name;
287    format!(
288        "\nimpl larust_support::auth::Authenticatable for User {{\n    fn auth_id(&self) -> i64 {{\n        self.{pk_name}\n    }}\n\n    async fn find_for_auth(id: i64) -> Result<Option<Self>, larust_support::AppError> {{\n        Self::find(id).await\n    }}\n}}\n"
289    )
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295    use schema::SqlType;
296
297    fn users_and_posts_tables() -> std::collections::HashMap<String, Vec<SqlColumn>> {
298        let mut tables = std::collections::HashMap::new();
299        tables.insert(
300            "users".to_string(),
301            vec![SqlColumn {
302                name: "id".to_string(),
303                sql_type: SqlType::IntegerPrimaryKey,
304                not_null: false,
305            }],
306        );
307        tables.insert(
308            "posts".to_string(),
309            vec![
310                SqlColumn {
311                    name: "id".to_string(),
312                    sql_type: SqlType::IntegerPrimaryKey,
313                    not_null: false,
314                },
315                SqlColumn {
316                    name: "user_id".to_string(),
317                    sql_type: SqlType::Integer,
318                    not_null: true,
319                },
320                SqlColumn {
321                    name: "title".to_string(),
322                    sql_type: SqlType::Text,
323                    not_null: true,
324                },
325            ],
326        );
327        tables
328    }
329
330    #[test]
331    fn converts_a_simple_model_with_default_table_name() {
332        let source = "<?php\nclass Post extends Model {}\n";
333        let tables = users_and_posts_tables();
334        let result = convert(source, "Post", &tables).unwrap().unwrap();
335        assert!(result.content.contains("#[table(\"posts\")]"));
336        assert!(result.content.contains("pub struct Post {"));
337        assert!(result.content.contains("#[primary_key]"));
338        assert!(result.content.contains("pub user_id: i64,"));
339        assert!(result.content.contains("pub title: String,"));
340    }
341
342    #[test]
343    fn converts_a_model_with_an_explicit_table_property() {
344        let source = "<?php\nclass Post extends Model {\n    protected $table = 'blog_posts';\n}\n";
345        let mut tables = users_and_posts_tables();
346        tables.insert("blog_posts".to_string(), tables["posts"].clone());
347        let result = convert(source, "Post", &tables).unwrap().unwrap();
348        assert!(result.content.contains("#[table(\"blog_posts\")]"));
349    }
350
351    #[test]
352    fn converts_relationships_alongside_fields() {
353        let source = "<?php\nclass Post extends Model {\n    public function author(): BelongsTo\n    {\n        return $this->belongsTo(User::class, 'user_id');\n    }\n}\n";
354        let tables = users_and_posts_tables();
355        let result = convert(source, "Post", &tables).unwrap().unwrap();
356        assert!(result
357            .content
358            .contains("#[belongs_to(User, foreign_key = \"user_id\")]"));
359        assert!(result.relation_notes.is_empty());
360    }
361
362    #[test]
363    fn an_unsupported_relationship_is_noted_without_rejecting_the_model() {
364        let source = "<?php\nclass Post extends Model {\n    public function comments()\n    {\n        return $this->hasManyThrough(Comment::class, User::class);\n    }\n}\n";
365        let tables = users_and_posts_tables();
366        let result = convert(source, "Post", &tables).unwrap().unwrap();
367        assert_eq!(result.relation_notes.len(), 1);
368        assert!(result.content.contains("pub struct Post {"));
369    }
370
371    #[test]
372    fn a_model_with_no_migration_still_converts_from_inferred_fields() {
373        // A table with no migration at all (e.g. managed by a remote or
374        // otherwise external database) no longer rejects the model
375        // outright - see `inferred_fields`'s own doc comment for why
376        // there's no schema to be wrong *against* in that case.
377        let source =
378            "<?php\nclass Order extends Model {\n    protected $fillable = ['status'];\n}\n";
379        let tables = users_and_posts_tables();
380        let result = convert(source, "Order", &tables).unwrap().unwrap();
381        assert!(result.content.contains("pub struct Order {"));
382        assert!(result.content.contains("pub id: i64,"));
383        assert!(result.content.contains("pub status: String,"));
384        let note = result.schema_note.unwrap();
385        assert!(note.contains("no migration creates table `orders`"));
386    }
387
388    #[test]
389    fn a_migration_backed_model_has_no_schema_note() {
390        let source = "<?php\nclass Post extends Model {}\n";
391        let tables = users_and_posts_tables();
392        let result = convert(source, "Post", &tables).unwrap().unwrap();
393        assert!(result.schema_note.is_none());
394    }
395
396    #[test]
397    fn a_relationship_on_an_inferred_model_is_deferred_not_left_possibly_uncompilable() {
398        // Real source: `Blogs`'s own `$casts['categories_id'] = 'array'`
399        // disagrees with the `_id`-suffix-implies-`i64` convention its
400        // own `belongsTo(Categories::class)` relationship relies on -
401        // `#[belongs_to(...)]`'s compile-time backstop requires an `i64`
402        // field, so emitting the attribute against a `String` field
403        // would generate code that fails to compile. Every relationship
404        // on an inferred model is deferred, not just this one - see
405        // `mod.rs`'s own comment on why the *related* struct's own
406        // fields can't be checked from inside this file's `convert()`
407        // call either.
408        let source = "<?php\nclass Blogs extends Model {\n    protected $fillable = ['categories_id'];\n    protected $casts = ['categories_id' => 'array'];\n\n    public function categories(): BelongsTo\n    {\n        return $this->belongsTo(Categories::class);\n    }\n}\n";
409        let tables = users_and_posts_tables();
410        let result = convert(source, "Blogs", &tables).unwrap().unwrap();
411        assert!(result.content.contains("pub categories_id: String,"));
412        assert!(!result.content.contains("#[belongs_to("));
413        assert_eq!(result.relation_notes.len(), 1);
414        assert!(result.relation_notes[0].contains("categories"));
415        assert!(result.relation_notes[0].contains("inferred"));
416    }
417
418    #[test]
419    fn rejects_the_whole_model_when_a_column_type_is_unrecognized() {
420        let source = "<?php\nclass Setting extends Model {}\n";
421        let mut tables = std::collections::HashMap::new();
422        tables.insert(
423            "settings".to_string(),
424            vec![SqlColumn {
425                name: "payload".to_string(),
426                sql_type: SqlType::Unknown,
427                not_null: true,
428            }],
429        );
430        assert!(convert(source, "Setting", &tables).is_err());
431    }
432
433    #[test]
434    fn returns_none_for_a_class_that_does_not_exist_in_the_file() {
435        let source = "<?php\nclass Post {}\n";
436        let tables = users_and_posts_tables();
437        assert!(convert(source, "User", &tables).unwrap().is_none());
438    }
439}