ferro-cli 0.2.4

CLI for scaffolding Ferro web applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! db:sync command - Run migrations and sync entity files from database schema

use console::style;
use sea_orm::{ConnectionTrait, Database, DbBackend, Statement};
use std::env;
use std::fs;
use std::path::Path;
use std::process::Command;

use crate::templates;
use crate::templates::{ColumnInfo, TableInfo};

pub fn run(skip_migrations: bool, regenerate_models: bool) {
    // Check we're in a Ferro project
    if !Path::new("src/models").exists() && !Path::new("src/migrations").exists() {
        eprintln!(
            "{} Not in a Ferro project directory",
            style("Error:").red().bold()
        );
        std::process::exit(1);
    }

    // Run migrations first (unless skipped)
    if !skip_migrations {
        run_migrations();
    }

    // Generate entities from database
    generate_entities(regenerate_models);
}

fn run_migrations() {
    if !Path::new("src/migrations").exists() {
        println!(
            "{} No migrations directory found, skipping migrations",
            style("Info:").yellow()
        );
        return;
    }

    if !Path::new("src/bin/migrate.rs").exists() {
        println!(
            "{} Migration binary not found, skipping migrations",
            style("Info:").yellow()
        );
        return;
    }

    println!("{} Running pending migrations...", style("").cyan());

    let status = Command::new("cargo")
        .args(["run", "--bin", "migrate", "--", "up"])
        .status()
        .expect("Failed to execute cargo command");

    if !status.success() {
        eprintln!("{} Migration failed", style("Error:").red().bold());
        std::process::exit(1);
    }
    println!("{} Migrations complete", style("").green());
}

fn generate_entities(regenerate_models: bool) {
    // Load DATABASE_URL from .env
    dotenvy::dotenv().ok();

    let database_url = match env::var("DATABASE_URL") {
        Ok(url) => url,
        Err(_) => {
            eprintln!(
                "{} DATABASE_URL not set in .env",
                style("Error:").red().bold()
            );
            std::process::exit(1);
        }
    };

    println!("{} Discovering database schema...", style("").cyan());

    // Use tokio runtime for async schema discovery
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        discover_and_generate(&database_url, regenerate_models).await;
    });
}

async fn discover_and_generate(database_url: &str, regenerate_models: bool) {
    let is_sqlite = database_url.starts_with("sqlite");

    // Connect to database
    let db = match Database::connect(database_url).await {
        Ok(db) => db,
        Err(e) => {
            eprintln!(
                "{} Failed to connect to database: {}",
                style("Error:").red().bold(),
                e
            );
            std::process::exit(1);
        }
    };

    // Discover tables based on database type
    let tables = if is_sqlite {
        discover_sqlite_tables(&db).await
    } else {
        discover_postgres_tables(&db).await
    };

    // Filter out migration tables
    let tables: Vec<_> = tables
        .into_iter()
        .filter(|t| t.name != "seaql_migrations" && !t.name.starts_with("_"))
        .collect();

    if tables.is_empty() {
        println!("{} No tables found in database", style("Info:").yellow());
        return;
    }

    println!(
        "{} Found {} table(s): {}",
        style("").green(),
        tables.len(),
        tables
            .iter()
            .map(|t| t.name.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    );

    // Create models directory if it doesn't exist
    let models_dir = Path::new("src/models");
    if !models_dir.exists() {
        fs::create_dir_all(models_dir).expect("Failed to create models directory");
        println!("{} Created src/models directory", style("").green());
    }

    // Create entities directory
    let entities_dir = models_dir.join("entities");
    if !entities_dir.exists() {
        fs::create_dir_all(&entities_dir).expect("Failed to create entities directory");
        println!(
            "{} Created src/models/entities directory",
            style("").green()
        );
    }

    // Generate entity files
    for table in &tables {
        generate_entity_file(table, &entities_dir);
        if regenerate_models {
            generate_user_file(table, models_dir);
        } else {
            generate_user_file_if_not_exists(table, models_dir);
        }
    }

    // Update mod.rs files
    update_entities_mod(&tables, &entities_dir);
    update_models_mod(&tables, models_dir);

    println!();
    println!(
        "{} Entity files generated successfully!",
        style("").green().bold()
    );
    println!();
    println!("Generated files:");
    for table in &tables {
        println!(
            "  {} src/models/entities/{}.rs (auto-generated)",
            style("").dim(),
            table.name
        );
        println!(
            "  {} src/models/{}.rs (user customizations)",
            style("").dim(),
            table.name
        );
    }
}

async fn discover_sqlite_tables(db: &sea_orm::DatabaseConnection) -> Vec<TableInfo> {
    let mut tables = Vec::new();

    // Get all table names
    let table_names: Vec<String> = db
        .query_all(Statement::from_string(
            DbBackend::Sqlite,
            "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
        ))
        .await
        .unwrap_or_default()
        .iter()
        .filter_map(|row| row.try_get_by_index::<String>(0).ok())
        .collect();

    for table_name in table_names {
        let columns = discover_sqlite_columns(db, &table_name).await;
        tables.push(TableInfo {
            name: table_name,
            columns,
        });
    }

    tables
}

async fn discover_sqlite_columns(
    db: &sea_orm::DatabaseConnection,
    table_name: &str,
) -> Vec<ColumnInfo> {
    let query = format!("PRAGMA table_info({table_name})");
    let rows = db
        .query_all(Statement::from_string(DbBackend::Sqlite, query))
        .await
        .unwrap_or_default();

    rows.iter()
        .filter_map(|row| {
            let name: String = row.try_get_by_index(1).ok()?;
            let col_type: String = row.try_get_by_index(2).ok()?;
            let notnull: i32 = row.try_get_by_index(3).ok()?;
            let pk: i32 = row.try_get_by_index(5).ok()?;

            Some(ColumnInfo {
                name,
                col_type,
                is_nullable: notnull == 0,
                is_primary_key: pk > 0,
            })
        })
        .collect()
}

async fn discover_postgres_tables(db: &sea_orm::DatabaseConnection) -> Vec<TableInfo> {
    let mut tables = Vec::new();

    // Get all table names from public schema
    let table_names: Vec<String> = db
        .query_all(Statement::from_string(
            DbBackend::Postgres,
            "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE'",
        ))
        .await
        .unwrap_or_default()
        .iter()
        .filter_map(|row| row.try_get_by_index::<String>(0).ok())
        .collect();

    for table_name in table_names {
        let columns = discover_postgres_columns(db, &table_name).await;
        tables.push(TableInfo {
            name: table_name,
            columns,
        });
    }

    tables
}

async fn discover_postgres_columns(
    db: &sea_orm::DatabaseConnection,
    table_name: &str,
) -> Vec<ColumnInfo> {
    let query = format!(
        r#"
        SELECT
            c.column_name,
            c.data_type,
            c.is_nullable,
            CASE WHEN pk.column_name IS NOT NULL THEN true ELSE false END as is_pk
        FROM information_schema.columns c
        LEFT JOIN (
            SELECT ku.column_name
            FROM information_schema.table_constraints tc
            JOIN information_schema.key_column_usage ku
                ON tc.constraint_name = ku.constraint_name
            WHERE tc.constraint_type = 'PRIMARY KEY'
                AND tc.table_name = '{table_name}'
        ) pk ON c.column_name = pk.column_name
        WHERE c.table_name = '{table_name}'
        ORDER BY c.ordinal_position
        "#
    );

    let rows = db
        .query_all(Statement::from_string(DbBackend::Postgres, query))
        .await
        .unwrap_or_default();

    rows.iter()
        .filter_map(|row| {
            let name: String = row.try_get_by_index(0).ok()?;
            let col_type: String = row.try_get_by_index(1).ok()?;
            let is_nullable_str: String = row.try_get_by_index(2).ok()?;
            let is_pk: bool = row.try_get_by_index(3).ok()?;

            Some(ColumnInfo {
                name,
                col_type,
                is_nullable: is_nullable_str == "YES",
                is_primary_key: is_pk,
            })
        })
        .collect()
}

fn generate_entity_file(table: &TableInfo, entities_dir: &Path) {
    let entity_file = entities_dir.join(format!("{}.rs", table.name));
    let content = templates::entity_template(&table.name, &table.columns);

    fs::write(&entity_file, content).expect("Failed to write entity file");
    println!(
        "{} Generated src/models/entities/{}.rs",
        style("").green(),
        table.name
    );
}

fn generate_user_file_if_not_exists(table: &TableInfo, models_dir: &Path) {
    let user_file = models_dir.join(format!("{}.rs", table.name));

    // Only create if it doesn't exist
    if user_file.exists() {
        println!(
            "{} Skipped src/models/{}.rs (already exists)",
            style("").dim(),
            table.name
        );
        return;
    }

    let struct_name = to_pascal_case(&singularize(&table.name));
    let content = templates::user_model_template(&table.name, &struct_name, &table.columns);

    fs::write(&user_file, content).expect("Failed to write user model file");
    println!(
        "{} Created src/models/{}.rs",
        style("").green(),
        table.name
    );
}

fn generate_user_file(table: &TableInfo, models_dir: &Path) {
    let user_file = models_dir.join(format!("{}.rs", table.name));
    let struct_name = to_pascal_case(&singularize(&table.name));
    let content = templates::user_model_template(&table.name, &struct_name, &table.columns);

    fs::write(&user_file, content).expect("Failed to write user model file");
    println!(
        "{} Regenerated src/models/{}.rs",
        style("").green(),
        table.name
    );
}

fn update_entities_mod(tables: &[TableInfo], entities_dir: &Path) {
    let mod_file = entities_dir.join("mod.rs");
    let content = templates::entities_mod_template(tables);

    fs::write(&mod_file, content).expect("Failed to write entities/mod.rs");
    println!("{} Updated src/models/entities/mod.rs", style("").green());
}

fn update_models_mod(tables: &[TableInfo], models_dir: &Path) {
    let mod_file = models_dir.join("mod.rs");

    // Read existing content or create new
    let existing_content = if mod_file.exists() {
        fs::read_to_string(&mod_file).unwrap_or_default()
    } else {
        "//! Application models\n\n".to_string()
    };

    let mut lines: Vec<String> = existing_content.lines().map(String::from).collect();

    // Check if entities module is declared
    let has_entities_mod = lines.iter().any(|l| {
        let trimmed = l.trim();
        trimmed == "pub mod entities;" || trimmed == "mod entities;"
    });

    // Find insertion point (after doc comments)
    let mut insert_idx = 0;
    for (i, line) in lines.iter().enumerate() {
        if line.starts_with("//!") || line.is_empty() {
            insert_idx = i + 1;
        } else {
            break;
        }
    }

    // Add entities module if not present
    if !has_entities_mod {
        lines.insert(insert_idx, "pub mod entities;".to_string());
        insert_idx += 1;
    }

    // Add missing table modules
    for table in tables {
        let mod_decl = format!("pub mod {};", table.name);
        let alt_mod_decl = format!("mod {};", table.name);

        if !lines
            .iter()
            .any(|l| l.trim() == mod_decl || l.trim() == alt_mod_decl)
        {
            // Find last pub mod declaration
            let mut last_mod_idx = insert_idx;
            for (i, line) in lines.iter().enumerate() {
                if line.trim().starts_with("pub mod ") || line.trim().starts_with("mod ") {
                    last_mod_idx = i + 1;
                }
            }
            lines.insert(last_mod_idx, mod_decl);
        }
    }

    let content = lines.join("\n");
    fs::write(&mod_file, content).expect("Failed to write models/mod.rs");
    println!("{} Updated src/models/mod.rs", style("").green());
}

fn to_pascal_case(s: &str) -> String {
    let mut result = String::new();
    let mut capitalize_next = true;

    for c in s.chars() {
        if c == '_' || c == '-' || c == ' ' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(c.to_uppercase().next().unwrap());
            capitalize_next = false;
        } else {
            result.push(c);
        }
    }
    result
}

fn singularize(word: &str) -> String {
    // Basic singularization
    if let Some(stem) = word.strip_suffix("ies") {
        format!("{stem}y")
    } else if let Some(stem) = word.strip_suffix("es") {
        if word.ends_with("ses") || word.ends_with("xes") {
            word.to_string()
        } else {
            stem.to_string()
        }
    } else if let Some(stem) = word.strip_suffix('s') {
        if word.ends_with("ss") || word.ends_with("us") {
            word.to_string()
        } else {
            stem.to_string()
        }
    } else {
        word.to_string()
    }
}