Skip to main content

ferriorm_codegen/
generator.rs

1//! Top-level code generation orchestrator.
2//!
3//! [`generate`] is the main entry point. It takes a validated
4//! [`ferriorm_core::schema::Schema`] and an output directory, then writes all
5//! generated Rust source files: per-model modules, an enums module, the
6//! `FerriormClient` module, and a `mod.rs` that ties them together. Each file is
7//! prefixed with an auto-generated header so users know not to edit it.
8
9use ferriorm_core::schema::Schema;
10use ferriorm_core::utils::to_snake_case;
11use std::fs;
12use std::path::Path;
13
14use crate::client::generate_client_module;
15use crate::enums::generate_enums_module;
16use crate::formatter::format_token_stream;
17use crate::model::generate_model_module;
18
19/// Generate all Rust source files from a validated schema.
20pub fn generate(schema: &Schema, output_dir: &Path) -> Result<(), GenerateError> {
21    // Ensure output directory exists
22    fs::create_dir_all(output_dir)
23        .map_err(|e| GenerateError::Io(format!("Failed to create output dir: {e}")))?;
24
25    let mut mod_entries = Vec::new();
26
27    // Generate enums.rs
28    if !schema.enums.is_empty() {
29        let tokens = generate_enums_module(&schema.enums);
30        let code = format_token_stream(tokens);
31        write_file(output_dir, "enums.rs", &code)?;
32        mod_entries.push("pub mod enums;".to_string());
33    }
34
35    // Generate per-model modules
36    for model in &schema.models {
37        let model_tokens = generate_model_module(model);
38        let relation_types = crate::relations::gen_relation_types(model, schema);
39        let relation_include = crate::relations::gen_find_many_include(model, schema);
40        let tokens = quote::quote! {
41            #model_tokens
42            #relation_types
43            #relation_include
44        };
45        let code = format_token_stream(tokens);
46        let filename = format!("{}.rs", to_snake_case(&model.name));
47        write_file(output_dir, &filename, &code)?;
48        mod_entries.push(format!("pub mod {};", to_snake_case(&model.name)));
49    }
50
51    // Generate client.rs
52    let client_tokens = generate_client_module(schema);
53    let client_code = format_token_stream(client_tokens);
54    write_file(output_dir, "client.rs", &client_code)?;
55    mod_entries.push("pub mod client;".to_string());
56
57    // Generate mod.rs (write directly, not through write_file to avoid double header)
58    let mut mod_content = String::from(
59        "// AUTO-GENERATED by ferriorm. Do not edit.\n\
60         //\n\
61         // NOTE: The generated code uses `#[derive(sqlx::FromRow)]` which requires\n\
62         // `sqlx` as a direct dependency in your Cargo.toml. The derive macro expands\n\
63         // to code with absolute `::sqlx::` paths that cannot be resolved through\n\
64         // re-exports alone. See the installation guide for required dependencies.\n\n",
65    );
66    for entry in &mod_entries {
67        mod_content.push_str(entry);
68        mod_content.push('\n');
69    }
70    mod_content.push('\n');
71    mod_content.push_str("pub use client::FerriormClient;\n");
72    if !schema.enums.is_empty() {
73        mod_content.push_str("pub use enums::*;\n");
74    }
75
76    let mod_path = output_dir.join("mod.rs");
77    fs::write(&mod_path, mod_content)
78        .map_err(|e| GenerateError::Io(format!("Failed to write {}: {e}", mod_path.display())))?;
79
80    Ok(())
81}
82
83fn write_file(dir: &Path, filename: &str, content: &str) -> Result<(), GenerateError> {
84    let path = dir.join(filename);
85
86    // Add auto-generated header
87    let full_content = format!("// AUTO-GENERATED by ferriorm. Do not edit.\n\n{content}");
88
89    fs::write(&path, full_content)
90        .map_err(|e| GenerateError::Io(format!("Failed to write {}: {e}", path.display())))?;
91
92    Ok(())
93}
94
95#[derive(Debug)]
96pub enum GenerateError {
97    Io(String),
98    CodeGen(String),
99}
100
101impl std::fmt::Display for GenerateError {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        match self {
104            Self::Io(msg) => write!(f, "IO error: {msg}"),
105            Self::CodeGen(msg) => write!(f, "Code generation error: {msg}"),
106        }
107    }
108}
109
110impl std::error::Error for GenerateError {}