ormada-cli 0.1.0

CLI tool for Ormada ORM migrations - generate, run, and manage database migrations
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! CLI command implementations

use anyhow::{bail, Context, Result};
use colored::Colorize;
use std::path::Path;

use crate::config::{generate_migration_id, CliConfig};
use crate::generator::MigrationGenerator;
use ormada_schema::{discover_models, DiscoveryConfig};

/// Initialize migrations directory
///
/// Creates the migrations directory and an ormada.toml config file.
/// If a custom path is provided, it's saved to ormada.toml for future commands.
///
/// Running twice:
/// - If directory exists: prints "already exists" and exits
/// - If ormada.toml exists with different path: warns about mismatch
pub async fn migrate_init(custom_path: Option<&str>) -> Result<()> {
    let mut config = CliConfig::load()?;

    // Use custom path if provided
    if let Some(path) = custom_path {
        config.migrations_dir = std::path::PathBuf::from(path);
    }

    let migrations_path = config.migrations_path();
    let config_path = config.project_root.join("ormada.toml");

    // Check if ormada.toml exists with a different path
    if config_path.exists() {
        let existing_config = std::fs::read_to_string(&config_path)?;
        if let Some(existing_path) = parse_migrations_path_from_toml(&existing_config) {
            let new_path = config.migrations_dir.to_string_lossy();
            if existing_path != new_path {
                println!(
                    "{} ormada.toml already exists with migrations_dir = \"{}\"",
                    "!".yellow(),
                    existing_path
                );
                println!("  To use a different path, edit ormada.toml or delete it first");
                return Ok(());
            }
        }
    }

    if migrations_path.exists() {
        println!(
            "{} Migrations directory already exists at {}",
            "".green(),
            migrations_path.display()
        );

        // Still create/update ormada.toml if it doesn't exist
        if !config_path.exists() {
            write_ormada_toml(&config_path, &config.migrations_dir)?;
            println!("{} Created ormada.toml", "".green());
        }

        return Ok(());
    }

    config.ensure_migrations_dir()?;

    // Create a mod.rs file
    let mod_path = migrations_path.join("mod.rs");
    std::fs::write(
        &mod_path,
        "//! Database migrations\n//!\n//! Generated by `ormada migrate init`\n",
    )?;

    // Create ormada.toml config file
    write_ormada_toml(&config_path, &config.migrations_dir)?;

    println!("{} Created migrations directory at {}", "".green(), migrations_path.display());
    println!("{} Created ormada.toml", "".green());
    println!(
        "  Run {} to generate your first migration",
        "ormada migrate make \"initial\"".cyan()
    );

    Ok(())
}

/// Parse migrations_dir from ormada.toml content
fn parse_migrations_path_from_toml(content: &str) -> Option<String> {
    for line in content.lines() {
        let line = line.trim();
        if line.starts_with("migrations_dir") {
            if let Some((_key, value)) = line.split_once('=') {
                let value = value.trim().trim_matches('"');
                return Some(value.to_string());
            }
        }
    }
    None
}

/// Write ormada.toml config file
fn write_ormada_toml(path: &std::path::Path, migrations_dir: &std::path::Path) -> Result<()> {
    let content = format!(
        r#"# Ormada ORM Configuration
# Generated by `ormada migrate init`

[migrations]
# Directory containing migration files
migrations_dir = "{}"

# [database]
# url = "postgres://user:pass@localhost/db"
"#,
        migrations_dir.display()
    );
    std::fs::write(path, content)?;
    Ok(())
}

/// Generate a new migration from model changes
pub async fn migrate_make(name: &str, _yes: bool) -> Result<()> {
    let config = CliConfig::load()?;
    config.ensure_migrations_dir()?;

    println!("{} Scanning models...", "".blue());

    // Discover models from source
    let discovery_config = DiscoveryConfig::default();
    let models = discover_models(&config.project_root, &discovery_config)
        .context("Failed to discover models")?;

    if models.is_empty() {
        println!("{} No models found with #[ormada_model] attribute", "!".yellow());
        println!(
            "  Make sure your models are in {} and use #[ormada_model(table = \"...\")]",
            config
                .model_paths
                .first()
                .map(|p| p.display().to_string())
                .unwrap_or_else(|| "src".to_string())
        );
        return Ok(());
    }

    println!("  Found {} model(s)", models.len());
    for model in &models {
        println!("    {} {}", "".dimmed(), model.name);
    }

    // Load existing migrations to compare
    let migrations_path = config.migrations_path();
    let existing_schema = load_existing_schema(&migrations_path)?;

    // Generate diff
    let operations = ormada_schema::generate_diff(&existing_schema, &models);

    if operations.is_empty() {
        println!("{} No changes detected", "".green());
        return Ok(());
    }

    println!("\n{} Detected {} change(s):", "".blue(), operations.len());
    for op in &operations {
        println!("    {} {}", "".dimmed(), format_operation(op));
    }

    // Generate migration file
    let migration_id = generate_migration_id(name);
    let generator = MigrationGenerator::new(&migrations_path);
    let migration_path = generator.generate(&migration_id, &models, &operations)?;

    println!("\n{} Created migration: {}", "".green(), migration_path.display());
    println!("  Review the migration file and run {} to apply", "ormada migrate run".cyan());

    Ok(())
}

/// Show migration status
pub async fn migrate_status() -> Result<()> {
    use crate::tracker::MigrationRunner;

    let config = CliConfig::load()?;
    let migrations_path = config.migrations_path();

    if !migrations_path.exists() {
        println!("{} No migrations directory found", "!".yellow());
        println!("  Run {} to initialize", "ormada migrate init".cyan());
        return Ok(());
    }

    // List migration files
    let mut migrations: Vec<_> = std::fs::read_dir(&migrations_path)?
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path().extension().is_some_and(|ext| ext == "rs") && e.file_name() != "mod.rs"
        })
        .collect();

    migrations.sort_by_key(|e| e.file_name());

    if migrations.is_empty() {
        println!("{} No migrations found", "!".yellow());
        println!(
            "  Run {} to create your first migration",
            "ormada migrate make \"initial\"".cyan()
        );
        return Ok(());
    }

    // Try to get applied migrations from database
    let applied_versions: std::collections::HashSet<String> = if let Some(ref db_url) =
        config.database_url
    {
        match MigrationRunner::new(db_url).await {
            Ok(runner) => match runner.get_applied_migrations().await {
                Ok(applied) => applied.into_iter().map(|m| m.version).collect(),
                Err(_) => std::collections::HashSet::new(),
            },
            Err(_) => {
                println!("{} Could not connect to database - showing all as pending", "!".yellow());
                std::collections::HashSet::new()
            }
        }
    } else {
        println!("{} DATABASE_URL not set - cannot check applied status", "!".yellow());
        std::collections::HashSet::new()
    };

    let mut applied_count = 0;
    let mut pending_count = 0;

    println!("{} Migrations:", "".blue());
    for entry in &migrations {
        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        let version = name_str.trim_end_matches(".rs");

        if applied_versions.contains(version) {
            println!("  {} {}", "".green(), version);
            applied_count += 1;
        } else {
            println!("  {} {}", "".dimmed(), version);
            pending_count += 1;
        }
    }

    println!();
    if applied_count > 0 {
        println!("  {} applied, {} pending", applied_count.to_string().green(), pending_count);
    } else {
        println!("  {} = pending, {} = applied", "".dimmed(), "".green());
    }

    Ok(())
}

/// Apply pending migrations
pub async fn migrate_run(_migration: Option<&str>, dry_run: bool) -> Result<()> {
    use crate::sql_generator::generate_sql;
    use crate::tracker::{MigrationRunner, PendingMigration};

    let config = CliConfig::load()?;

    let database_url = config.database_url.as_ref().ok_or_else(|| {
        anyhow::anyhow!("DATABASE_URL not set. Set it in environment or ormada.toml")
    })?;

    let migrations_path = config.migrations_path();
    if !migrations_path.exists() {
        bail!("No migrations directory found. Run `ormada migrate init` first.");
    }

    println!("{} Connecting to database...", "".blue());

    // Connect to database
    let runner = MigrationRunner::new(database_url).await?;

    println!("{} Scanning migrations...", "".blue());

    // Discover models from migration files
    let discovery_config = DiscoveryConfig {
        include_paths: vec![migrations_path.to_string_lossy().to_string()],
        skip_non_migratable: false,
        skip_test_models: true,
        ..Default::default()
    };

    let models = discover_models(&migrations_path, &discovery_config)
        .context("Failed to parse migration files")?;

    if models.is_empty() {
        println!("{} No migrations found", "!".yellow());
        return Ok(());
    }

    // Generate SQL for each migration file
    let mut pending_migrations = Vec::new();

    // Read migration files and generate SQL
    let mut migration_files: Vec<_> = std::fs::read_dir(&migrations_path)?
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path().extension().is_some_and(|ext| ext == "rs") && e.file_name() != "mod.rs"
        })
        .collect();

    migration_files.sort_by_key(|e| e.file_name());

    for entry in &migration_files {
        let file_name = entry.file_name();
        let version = file_name.to_string_lossy().trim_end_matches(".rs").to_string();

        // Parse this specific migration file
        let file_path = entry.path();
        let content = std::fs::read_to_string(&file_path)?;

        // Parse the migration to get schema operations
        let file_models =
            ormada_schema::parse_source(&content, &version, &discovery_config).unwrap_or_default();

        if file_models.is_empty() {
            continue;
        }

        // Generate SQL from schema (for initial migrations, create tables)
        let operations: Vec<_> = file_models
            .iter()
            .map(|m| ormada_schema::SchemaOperation::CreateTable(m.clone()))
            .collect();

        let sql = generate_sql(&operations);

        if !sql.is_empty() {
            let name = version.split('_').skip(2).collect::<Vec<_>>().join("_");

            pending_migrations.push(PendingMigration::new(&version, &name, &sql));
        }
    }

    if pending_migrations.is_empty() {
        println!("{} No migrations to apply", "".green());
        return Ok(());
    }

    println!("  Found {} migration(s)", pending_migrations.len());

    // Run migrations
    let report = runner.run_migrations(&pending_migrations, dry_run).await?;

    // Display report
    println!("\n{}", report.format());

    if dry_run && !report.applied.is_empty() {
        println!("\n{}", "SQL that would be executed:".cyan());
        for m in &pending_migrations {
            if report.applied.iter().any(|a| a.version == m.version) {
                println!("\n-- {} --", m.version.green());
                println!("{}", m.sql);
            }
        }
    }

    Ok(())
}

/// Rollback migrations
pub async fn migrate_rollback(steps: u32, yes: bool) -> Result<()> {
    use crate::tracker::MigrationRunner;
    use dialoguer::Confirm;

    let config = CliConfig::load()?;

    let database_url = config
        .database_url
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("DATABASE_URL not set"))?;

    println!("{} Connecting to database...", "".blue());
    let runner = MigrationRunner::new(database_url).await?;

    let applied = runner.get_applied_migrations().await?;

    if applied.is_empty() {
        println!("{} No migrations to rollback", "!".yellow());
        return Ok(());
    }

    let to_rollback: Vec<_> = applied.iter().rev().take(steps as usize).collect();

    if to_rollback.is_empty() {
        println!("{} No migrations to rollback", "!".yellow());
        return Ok(());
    }

    println!("{} Migrations to rollback:", "".blue());
    for m in &to_rollback {
        println!("  {} {} ({})", "".red(), m.version, m.name);
    }

    if !yes {
        let confirm = Confirm::new()
            .with_prompt("Are you sure you want to rollback these migrations?")
            .default(false)
            .interact()?;

        if !confirm {
            println!("{} Rollback cancelled", "!".yellow());
            return Ok(());
        }
    }

    // Note: Rollback requires storing down migrations or reversible operations
    // For now, we only support removing the tracking record (manual schema cleanup needed)
    println!(
        "{} Rollback removes migration records but does NOT reverse schema changes",
        "!".yellow()
    );
    println!("  You must manually reverse the schema changes or restore from backup");

    for m in &to_rollback {
        runner.remove_migration_record(&m.version).await?;
        println!("  {} Removed: {}", "".green(), m.version);
    }

    println!("\n{} Rolled back {} migration(s)", "".green(), to_rollback.len());

    Ok(())
}

/// Generate SQL for pending migrations
pub async fn migrate_sql(output: Option<&str>) -> Result<()> {
    use crate::sql_generator::generate_sql;
    use crate::tracker::{MigrationRunner, PendingMigration};

    let config = CliConfig::load()?;
    let migrations_path = config.migrations_path();

    if !migrations_path.exists() {
        bail!("No migrations directory found. Run `ormada migrate init` first.");
    }

    // Parse migration files
    let discovery_config = DiscoveryConfig {
        include_paths: vec![migrations_path.to_string_lossy().to_string()],
        skip_non_migratable: false,
        skip_test_models: true,
        ..Default::default()
    };

    let mut migration_files: Vec<_> = std::fs::read_dir(&migrations_path)?
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path().extension().is_some_and(|ext| ext == "rs") && e.file_name() != "mod.rs"
        })
        .collect();

    migration_files.sort_by_key(|e| e.file_name());

    let mut all_migrations = Vec::new();

    for entry in &migration_files {
        let file_name = entry.file_name();
        let version = file_name.to_string_lossy().trim_end_matches(".rs").to_string();
        let file_path = entry.path();
        let content = std::fs::read_to_string(&file_path)?;

        let file_models =
            ormada_schema::parse_source(&content, &version, &discovery_config).unwrap_or_default();

        if file_models.is_empty() {
            continue;
        }

        let operations: Vec<_> = file_models
            .iter()
            .map(|m| ormada_schema::SchemaOperation::CreateTable(m.clone()))
            .collect();

        let sql = generate_sql(&operations);

        if !sql.is_empty() {
            let name = version.split('_').skip(2).collect::<Vec<_>>().join("_");
            all_migrations.push(PendingMigration::new(&version, &name, &sql));
        }
    }

    // Filter to pending only if database is available
    let pending_migrations = if let Some(ref db_url) = config.database_url {
        match MigrationRunner::new(db_url).await {
            Ok(runner) => {
                runner.get_pending_migrations(&all_migrations).await.unwrap_or(all_migrations)
            }
            Err(_) => all_migrations,
        }
    } else {
        all_migrations
    };

    if pending_migrations.is_empty() {
        println!("{} No pending migrations", "".green());
        return Ok(());
    }

    // Generate combined SQL
    let mut combined_sql = String::new();
    combined_sql.push_str("-- Ormada Migration SQL\n");
    combined_sql.push_str(&format!(
        "-- Generated: {}\n\n",
        chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
    ));

    for m in &pending_migrations {
        combined_sql.push_str(&format!("-- Migration: {} ({})\n", m.version, m.name));
        combined_sql.push_str(&format!("-- Checksum: {}\n", &m.checksum[..16]));
        combined_sql.push_str("-- ----------------------------------------\n\n");
        combined_sql.push_str(&m.sql);
        combined_sql.push_str("\n\n");
    }

    if let Some(path) = output {
        std::fs::write(path, &combined_sql)?;
        println!("{} SQL written to: {}", "".green(), path);
    } else {
        println!("{}", combined_sql);
    }

    Ok(())
}

/// Load existing schema from migration files
fn load_existing_schema(migrations_path: &Path) -> Result<Vec<ormada_schema::TableSchema>> {
    if !migrations_path.exists() {
        return Ok(Vec::new());
    }

    let discovery_config = DiscoveryConfig {
        include_paths: vec![migrations_path.to_string_lossy().to_string()],
        exclude_paths: vec![],
        skip_non_migratable: false,
        skip_test_models: true,
    };

    // Get all migration files sorted by name (which includes timestamp)
    let mut migration_files: Vec<_> = std::fs::read_dir(migrations_path)?
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path().extension().is_some_and(|ext| ext == "rs") && e.file_name() != "mod.rs"
        })
        .collect();

    migration_files.sort_by_key(|e| e.file_name());

    // Parse each migration and accumulate schema
    let mut schemas: std::collections::HashMap<String, ormada_schema::TableSchema> =
        std::collections::HashMap::new();

    for entry in migration_files {
        let file_path = entry.path();
        let file_name = entry.file_name().to_string_lossy().to_string();

        let content = match std::fs::read_to_string(&file_path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        let tables = ormada_schema::parse_source(&content, &file_name, &discovery_config)
            .unwrap_or_default();

        for table in tables {
            // For delta migrations (extends), we would need to merge
            // For now, just use the latest definition for each table
            schemas.insert(table.name.clone(), table);
        }
    }

    Ok(schemas.into_values().collect())
}

/// Format a schema operation for display
fn format_operation(op: &ormada_schema::SchemaOperation) -> String {
    use ormada_schema::SchemaOperation::*;

    match op {
        CreateTable(schema) => format!("Create table '{}'", schema.name),
        DropTable(name) => format!("Drop table '{}'", name),
        RenameTable { from, to } => format!("Rename table '{}' to '{}'", from, to),
        AddColumn { table, column } => format!("Add column '{}' to '{}'", column.name, table),
        DropColumn { table, column } => format!("Drop column '{}' from '{}'", column, table),
        RenameColumn { table, from, to } => {
            format!("Rename column '{}' to '{}' in '{}'", from, to, table)
        }
        AlterColumn { table, column, .. } => format!("Alter column '{}' in '{}'", column, table),
        CreateIndex { table, index } => format!("Create index '{}' on '{}'", index.name, table),
        DropIndex { table, name } => format!("Drop index '{}' from '{}'", name, table),
        AddForeignKey { table, foreign_key } => {
            format!(
                "Add foreign key '{}' -> '{}' on '{}'",
                foreign_key.column, foreign_key.references_table, table
            )
        }
        DropForeignKey { table, name } => format!("Drop foreign key '{}' from '{}'", name, table),
    }
}