Skip to main content

larust_convert/models/
inferred_fields.rs

1//! Best-effort field inference for a model whose table has no migration -
2//! a model backed by a remote or otherwise externally-managed database
3//! has no local schema for `mod.rs`'s normal migration-derived path
4//! (`fields.rs`) to read at all.
5//!
6//! `fields.rs`'s whole-struct safety (reject the entire model rather
7//! than guess a column's type) exists because a wrong `sqlx::FromRow`
8//! type panics or errors on every query - but that safety net assumes
9//! there's a real, locally-known schema to check a guess *against*.
10//! Here there isn't one: every field type is a guess, by construction,
11//! whether this module emits one field or refuses to emit any at all.
12//! Given that, the trade-off this module makes is to still produce a
13//! real, immediately usable struct - typed from whatever the model
14//! class's own PHP already declares (`$fillable`, `$casts`, a
15//! `belongsTo` relationship's own foreign key, Eloquent's default
16//! `id`/timestamps conventions) - rather than nothing at all, with every
17//! guessed field prominently flagged (see `mod.rs`'s own handling of
18//! [`infer`]'s result) as unverified against the real, remote schema.
19
20use super::relations::Relation;
21use crate::php;
22use std::collections::{HashMap, HashSet};
23use tree_sitter::Node;
24
25pub struct InferredField {
26    pub name: String,
27    pub rust_type: String,
28    pub is_primary_key: bool,
29}
30
31/// Infers a model's fields purely from its own PHP source. Always
32/// includes a primary key (`id`, or the class's own `$primaryKey`
33/// override; typed `String` if the class uses Laravel's `HasUuids`
34/// trait - the one primary-key shape this phase can detect directly
35/// rather than assuming - else `i64`), every `$fillable` key (typed via
36/// `$casts` when present, else a `_id`-suffix-implies-`i64` /
37/// else-`String` convention), every `belongsTo` relationship's own
38/// foreign key column (`i64`) not already covered by `$fillable`, and
39/// `created_at`/`updated_at` (`Option<String>`, matching how a real
40/// migration's `timestamps()` call already renders - see `fields.rs`'s
41/// own doc comment on that column shape) unless the class declares
42/// `$timestamps = false`.
43pub fn infer(class_node: Node, source: &str, relations: &[Relation]) -> Vec<InferredField> {
44    let mut fields = Vec::new();
45    let mut seen = HashSet::new();
46
47    let pk_name =
48        find_string_property(class_node, source, "primaryKey").unwrap_or_else(|| "id".to_string());
49    let pk_type = if uses_trait(class_node, source, "HasUuids") {
50        "String"
51    } else {
52        "i64"
53    };
54    seen.insert(pk_name.clone());
55    fields.push(InferredField {
56        name: pk_name,
57        rust_type: pk_type.to_string(),
58        is_primary_key: true,
59    });
60
61    let casts = find_string_map_property(class_node, source, "casts").unwrap_or_default();
62    for key in find_string_list_property(class_node, source, "fillable").unwrap_or_default() {
63        if !seen.insert(key.clone()) {
64            continue;
65        }
66        let rust_type = cast_type(&key, &casts);
67        fields.push(InferredField {
68            name: key,
69            rust_type,
70            is_primary_key: false,
71        });
72    }
73
74    for relation in relations {
75        if let Relation::BelongsTo { foreign_key, .. } = relation {
76            if seen.insert(foreign_key.clone()) {
77                fields.push(InferredField {
78                    name: foreign_key.clone(),
79                    rust_type: "i64".to_string(),
80                    is_primary_key: false,
81                });
82            }
83        }
84    }
85
86    if timestamps_enabled(class_node, source) {
87        for name in ["created_at", "updated_at"] {
88            if seen.insert(name.to_string()) {
89                fields.push(InferredField {
90                    name: name.to_string(),
91                    rust_type: "Option<String>".to_string(),
92                    is_primary_key: false,
93                });
94            }
95        }
96    }
97
98    fields
99}
100
101/// A `$casts` hit picks the type; an unknown/absent cast falls back to
102/// the same `_id`-suffix-implies-`i64` convention `relations.rs` already
103/// relies on for foreign keys, else `String` - this phase's universal
104/// "don't know, but need *something*" type, matching `fields.rs`'s own
105/// `Text` → `String` precedent. `array`/`json`/`object`/`collection`
106/// casts land on `String` too (the raw JSON/serialized text) rather than
107/// a structured type - this phase's generated-code vocabulary has no
108/// JSON value type yet (see `fields.rs`'s own doc comment on the
109/// framework's minimal SQL-type vocabulary).
110///
111/// `boolean`/`bool` casts land on `i64`, not Rust `bool` - matching
112/// `fields.rs`'s own migration-verified path, which already maps a
113/// Blueprint `boolean()` column to `i64` for the same reason: SQLite has
114/// no native boolean column (a `boolean`-cast field is stored as a plain
115/// `INTEGER`), and `sqlx`'s backend-agnostic `Any` driver - which every
116/// generated app's pool now goes through, SQLite-only apps included -
117/// tags that column as its own generic `BigInt` kind rather than `Bool`,
118/// so decoding it straight into a `#[derive(Model, sqlx::FromRow)]`
119/// struct's `bool` field fails outright ("Rust type `bool` is not
120/// compatible with SQL type `BIGINT`"). The generated struct's field
121/// stays a real `i64`; calling code compares `!= 0` by hand, the same
122/// pattern `larust-permissions`' own `has_role`/`has_permission_to` use
123/// for their `SELECT EXISTS(...)` queries.
124fn cast_type(key: &str, casts: &HashMap<String, String>) -> String {
125    match casts.get(key).map(String::as_str) {
126        Some("boolean") | Some("bool") => "i64".to_string(),
127        Some("integer") | Some("int") => "i64".to_string(),
128        Some(cast) if cast == "float" || cast == "double" || cast.starts_with("decimal") => {
129            "f64".to_string()
130        }
131        Some("array") | Some("json") | Some("object") | Some("collection") => "String".to_string(),
132        _ if key.ends_with("_id") => "i64".to_string(),
133        _ => "String".to_string(),
134    }
135}
136
137fn find_string_property(class_node: Node, source: &str, name: &str) -> Option<String> {
138    let default_value = super::find_property_default(class_node, source, name)?;
139    if default_value.kind() != "string" {
140        return None;
141    }
142    Some(php::unquote(
143        default_value.utf8_text(source.as_bytes()).ok()?,
144    ))
145}
146
147/// `$fillable`'s shape: a sequential array of string literals - each
148/// entry is an `array_element_initializer` wrapping exactly one named
149/// child (no `=>`), distinguishing it from `$casts`'s keyed shape (see
150/// [`find_string_map_property`]).
151fn find_string_list_property(class_node: Node, source: &str, name: &str) -> Option<Vec<String>> {
152    let array_node = super::find_property_default(class_node, source, name)?;
153    if array_node.kind() != "array_creation_expression" {
154        return None;
155    }
156    let bytes = source.as_bytes();
157    let mut items = Vec::new();
158    for i in 0..array_node.named_child_count() {
159        let Some(element) = array_node.named_child(i) else {
160            continue;
161        };
162        if element.kind() != "array_element_initializer" || element.named_child_count() != 1 {
163            continue;
164        }
165        let Some(value_node) = element.named_child(0) else {
166            continue;
167        };
168        if value_node.kind() != "string" {
169            continue;
170        }
171        let Ok(text) = value_node.utf8_text(bytes) else {
172            continue;
173        };
174        items.push(php::unquote(text));
175    }
176    Some(items)
177}
178
179/// `$casts`'s shape: a keyed array of string => string entries - each
180/// entry is an `array_element_initializer` wrapping exactly two named
181/// children (key, value).
182fn find_string_map_property(
183    class_node: Node,
184    source: &str,
185    name: &str,
186) -> Option<HashMap<String, String>> {
187    let array_node = super::find_property_default(class_node, source, name)?;
188    if array_node.kind() != "array_creation_expression" {
189        return None;
190    }
191    let bytes = source.as_bytes();
192    let mut map = HashMap::new();
193    for i in 0..array_node.named_child_count() {
194        let Some(element) = array_node.named_child(i) else {
195            continue;
196        };
197        if element.kind() != "array_element_initializer" || element.named_child_count() != 2 {
198            continue;
199        }
200        let (Some(key_node), Some(value_node)) = (element.named_child(0), element.named_child(1))
201        else {
202            continue;
203        };
204        if key_node.kind() != "string" || value_node.kind() != "string" {
205            continue;
206        }
207        let (Ok(key_text), Ok(value_text)) =
208            (key_node.utf8_text(bytes), value_node.utf8_text(bytes))
209        else {
210            continue;
211        };
212        map.insert(php::unquote(key_text), php::unquote(value_text));
213    }
214    Some(map)
215}
216
217/// Whether the class body's own trait-use clause (`use HasUuids;` inside
218/// the class - a `use_declaration` node scoped to the class body, not
219/// the file-level `use` import statement, a different construct
220/// entirely) names `trait_name`. A plain substring check on the whole
221/// clause's text is enough - Laravel trait names are PascalCase
222/// identifiers with no real risk of one being a substring of an
223/// unrelated trait in the same `use A, B;` list.
224fn uses_trait(class_node: Node, source: &str, trait_name: &str) -> bool {
225    let Some(body) = class_node.child_by_field_name("body") else {
226        return false;
227    };
228    php::direct_children_of_kind(body, "use_declaration")
229        .iter()
230        .filter_map(|node| node.utf8_text(source.as_bytes()).ok())
231        .any(|text| text.contains(trait_name))
232}
233
234/// `protected $timestamps = false;` opts out of Eloquent's default
235/// `created_at`/`updated_at` columns - anything else (declared `true`,
236/// or not declared at all, Eloquent's own default) keeps them.
237fn timestamps_enabled(class_node: Node, source: &str) -> bool {
238    let Some(default_value) = super::find_property_default(class_node, source, "timestamps") else {
239        return true;
240    };
241    !(default_value.kind() == "boolean"
242        && default_value.utf8_text(source.as_bytes()).ok() == Some("false"))
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248    use crate::php;
249
250    fn infer_from(source: &str, class_name: &str) -> Vec<InferredField> {
251        let tree = php::parse(source).unwrap();
252        let class_node = php::find_class(&tree, source, class_name).unwrap();
253        infer(class_node, source, &[])
254    }
255
256    #[test]
257    fn always_includes_an_i64_id_primary_key_by_default() {
258        let fields = infer_from("<?php\nclass Post extends Model {}\n", "Post");
259        assert_eq!(fields.len(), 3); // id + created_at + updated_at
260        assert_eq!(fields[0].name, "id");
261        assert_eq!(fields[0].rust_type, "i64");
262        assert!(fields[0].is_primary_key);
263    }
264
265    #[test]
266    fn a_has_uuids_trait_types_the_primary_key_as_a_string() {
267        let source = "<?php\nclass Term extends Model {\n    use HasUuids;\n}\n";
268        let fields = infer_from(source, "Term");
269        assert_eq!(fields[0].name, "id");
270        assert_eq!(fields[0].rust_type, "String");
271        assert!(fields[0].is_primary_key);
272    }
273
274    #[test]
275    fn fillable_keys_become_string_fields_by_default() {
276        let source = "<?php\nclass Faq extends Model {\n    protected $fillable = ['name'];\n}\n";
277        let fields = infer_from(source, "Faq");
278        let name_field = fields.iter().find(|f| f.name == "name").unwrap();
279        assert_eq!(name_field.rust_type, "String");
280    }
281
282    #[test]
283    fn a_fillable_key_ending_in_id_is_typed_as_i64() {
284        let source =
285            "<?php\nclass Blogs extends Model {\n    protected $fillable = ['categories_id'];\n}\n";
286        let fields = infer_from(source, "Blogs");
287        let field = fields.iter().find(|f| f.name == "categories_id").unwrap();
288        assert_eq!(field.rust_type, "i64");
289    }
290
291    #[test]
292    fn a_boolean_cast_overrides_the_default_string_type() {
293        // `i64`, not `bool` - see `cast_type`'s own doc comment: SQLite
294        // has no native boolean column, and sqlx's `Any` driver can't
295        // decode one straight into a Rust `bool`.
296        let source = "<?php\nclass Blogs extends Model {\n    protected $fillable = ['published'];\n    protected $casts = ['published' => 'boolean'];\n}\n";
297        let fields = infer_from(source, "Blogs");
298        let field = fields.iter().find(|f| f.name == "published").unwrap();
299        assert_eq!(field.rust_type, "i64");
300    }
301
302    #[test]
303    fn an_array_cast_still_falls_back_to_string() {
304        let source = "<?php\nclass Blogs extends Model {\n    protected $fillable = ['keywords'];\n    protected $casts = ['keywords' => 'array'];\n}\n";
305        let fields = infer_from(source, "Blogs");
306        let field = fields.iter().find(|f| f.name == "keywords").unwrap();
307        assert_eq!(field.rust_type, "String");
308    }
309
310    #[test]
311    fn a_belongs_to_relations_foreign_key_is_added_when_not_already_fillable() {
312        let source = "<?php\nclass Blogs extends Model {}\n";
313        let tree = php::parse(source).unwrap();
314        let class_node = php::find_class(&tree, source, "Blogs").unwrap();
315        let relations = vec![Relation::BelongsTo {
316            method: "categories".to_string(),
317            related: "Categories".to_string(),
318            foreign_key: "categories_id".to_string(),
319            inferred: true,
320        }];
321        let fields = infer(class_node, source, &relations);
322        let field = fields.iter().find(|f| f.name == "categories_id").unwrap();
323        assert_eq!(field.rust_type, "i64");
324    }
325
326    #[test]
327    fn a_belongs_to_foreign_key_is_not_duplicated_when_already_fillable() {
328        let source =
329            "<?php\nclass Blogs extends Model {\n    protected $fillable = ['categories_id'];\n}\n";
330        let tree = php::parse(source).unwrap();
331        let class_node = php::find_class(&tree, source, "Blogs").unwrap();
332        let relations = vec![Relation::BelongsTo {
333            method: "categories".to_string(),
334            related: "Categories".to_string(),
335            foreign_key: "categories_id".to_string(),
336            inferred: true,
337        }];
338        let fields = infer(class_node, source, &relations);
339        assert_eq!(
340            fields.iter().filter(|f| f.name == "categories_id").count(),
341            1
342        );
343    }
344
345    #[test]
346    fn timestamps_are_included_by_default() {
347        let fields = infer_from("<?php\nclass Post extends Model {}\n", "Post");
348        assert!(fields.iter().any(|f| f.name == "created_at"));
349        assert!(fields.iter().any(|f| f.name == "updated_at"));
350        let created = fields.iter().find(|f| f.name == "created_at").unwrap();
351        assert_eq!(created.rust_type, "Option<String>");
352    }
353
354    #[test]
355    fn timestamps_false_omits_created_at_and_updated_at() {
356        let source = "<?php\nclass Post extends Model {\n    protected $timestamps = false;\n}\n";
357        let fields = infer_from(source, "Post");
358        assert!(!fields.iter().any(|f| f.name == "created_at"));
359        assert!(!fields.iter().any(|f| f.name == "updated_at"));
360    }
361
362    #[test]
363    fn an_explicit_primary_key_property_overrides_the_id_default() {
364        let source =
365            "<?php\nclass Post extends Model {\n    protected $primaryKey = 'post_id';\n}\n";
366        let fields = infer_from(source, "Post");
367        assert_eq!(fields[0].name, "post_id");
368        assert!(fields[0].is_primary_key);
369    }
370}