prax-cli 0.3.2

CLI tool for the Prax ORM
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
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
//! `prax migrate` commands - Database migration management.

use std::path::PathBuf;

use crate::cli::MigrateArgs;
use crate::commands::seed::{find_seed_file, get_database_url, SeedRunner};
use crate::config::{Config, CONFIG_FILE_NAME, MIGRATIONS_DIR, SCHEMA_FILE_NAME};
use crate::error::{CliError, CliResult};
use crate::output::{self, success, warn};

/// Run the migrate command
pub async fn run(args: MigrateArgs) -> CliResult<()> {
    match args.command {
        crate::cli::MigrateSubcommand::Dev(dev_args) => run_dev(dev_args).await,
        crate::cli::MigrateSubcommand::Deploy => run_deploy().await,
        crate::cli::MigrateSubcommand::Reset(reset_args) => run_reset(reset_args).await,
        crate::cli::MigrateSubcommand::Status => run_status().await,
        crate::cli::MigrateSubcommand::Resolve(resolve_args) => run_resolve(resolve_args).await,
        crate::cli::MigrateSubcommand::Diff(diff_args) => run_diff(diff_args).await,
    }
}

/// Run `prax migrate dev` - development migration workflow
async fn run_dev(args: crate::cli::MigrateDevArgs) -> CliResult<()> {
    output::header("Migrate Dev");

    let cwd = std::env::current_dir()?;
    let config = load_config(&cwd)?;

    let schema_path = args.schema.clone().unwrap_or_else(|| cwd.join(SCHEMA_FILE_NAME));
    let migrations_dir = cwd.join(MIGRATIONS_DIR);

    output::kv("Schema", &schema_path.display().to_string());
    output::kv("Migrations", &migrations_dir.display().to_string());
    output::newline();

    // Determine total steps (5 or 6 depending on seed)
    let total_steps = if args.skip_seed { 5 } else { 6 };

    // 1. Parse and validate schema
    output::step(1, total_steps, "Parsing schema...");
    let schema_content = std::fs::read_to_string(&schema_path)?;
    let schema = parse_schema(&schema_content)?;

    // 2. Check for pending migrations
    output::step(2, total_steps, "Checking migration status...");
    let pending = check_pending_migrations(&migrations_dir)?;

    if !pending.is_empty() {
        output::list(&format!("{} pending migrations found:", pending.len()));
        for migration in &pending {
            output::list_item(&migration.display().to_string());
        }
        output::newline();
    }

    // 3. Diff schema against database
    output::step(3, total_steps, "Comparing schema to database...");
    let migration_name = args.name.unwrap_or_else(|| {
        format!(
            "migration_{}",
            chrono::Utc::now().format("%Y%m%d%H%M%S")
        )
    });

    // 4. Generate migration
    output::step(4, total_steps, "Generating migration...");
    let migration_path = create_migration(&migrations_dir, &migration_name, &schema)?;

    // 5. Apply migration (if not --create-only)
    if !args.create_only {
        output::step(5, total_steps, "Applying migration...");
        apply_migration(&migration_path, &config).await?;
    } else {
        output::step(5, total_steps, "Skipping apply (--create-only)...");
    }

    // 6. Run seed (if not --skip-seed)
    if !args.skip_seed && !args.create_only {
        output::step(6, total_steps, "Running seed...");

        if let Some(seed_path) = find_seed_file(&cwd, &config) {
            let database_url = get_database_url(&config)?;
            let runner = SeedRunner::new(
                seed_path,
                database_url,
                config.database.provider.clone(),
                cwd.clone(),
            )?;

            match runner.run().await {
                Ok(result) => {
                    output::list_item(&format!("Seeded {} records", result.records_affected));
                }
                Err(e) => {
                    output::warn(&format!("Seed failed: {}. Continuing...", e));
                }
            }
        } else {
            output::list_item("No seed file found, skipping");
        }
    }

    output::newline();
    success(&format!("Migration '{}' created", migration_name));

    output::newline();
    output::section("Next steps");
    output::list_item("Review the generated migration SQL");
    output::list_item("Run `prax generate` to update your client");

    Ok(())
}

/// Run `prax migrate deploy` - production deployment
async fn run_deploy() -> CliResult<()> {
    output::header("Migrate Deploy");

    let cwd = std::env::current_dir()?;
    let config = load_config(&cwd)?;
    let migrations_dir = cwd.join(MIGRATIONS_DIR);

    output::kv("Migrations", &migrations_dir.display().to_string());
    output::newline();

    // Check for pending migrations
    output::step(1, 3, "Checking for pending migrations...");
    let pending = check_pending_migrations(&migrations_dir)?;

    if pending.is_empty() {
        output::newline();
        success("No pending migrations to apply.");
        return Ok(());
    }

    output::list(&format!("{} pending migrations:", pending.len()));
    for migration in &pending {
        output::list_item(&migration.file_name().unwrap().to_string_lossy());
    }
    output::newline();

    // Apply migrations
    output::step(2, 3, "Applying migrations...");
    for migration in &pending {
        output::list_item(&format!("Applying {}", migration.file_name().unwrap().to_string_lossy()));
        apply_migration(migration, &config).await?;
    }

    // Verify
    output::step(3, 3, "Verifying migrations...");

    output::newline();
    success(&format!(
        "Applied {} migrations successfully!",
        pending.len()
    ));

    Ok(())
}

/// Run `prax migrate reset` - reset database
async fn run_reset(args: crate::cli::MigrateResetArgs) -> CliResult<()> {
    output::header("Migrate Reset");

    let cwd = std::env::current_dir()?;
    let config = load_config(&cwd)?;

    if !args.force {
        warn("This will delete all data in the database!");
        output::newline();
        if !output::confirm("Are you sure you want to reset the database?") {
            output::newline();
            output::info("Reset cancelled.");
            return Ok(());
        }
    }

    output::newline();
    output::step(1, 4, "Dropping database...");
    // TODO: Implement database drop

    output::step(2, 4, "Creating database...");
    // TODO: Implement database create

    output::step(3, 4, "Applying migrations...");
    let migrations_dir = cwd.join(MIGRATIONS_DIR);
    let migrations = check_pending_migrations(&migrations_dir)?;

    for migration in &migrations {
        apply_migration(migration, &config).await?;
    }

    // Run seed if requested
    if args.seed {
        output::step(4, 4, "Running seed...");

        // Find and run seed file
        if let Some(seed_path) = find_seed_file(&cwd, &config) {
            let database_url = get_database_url(&config)?;
            let runner = SeedRunner::new(
                seed_path,
                database_url,
                config.database.provider.clone(),
                cwd,
            )?;

            let result = runner.run().await?;
            output::list_item(&format!("Seeded {} records", result.records_affected));
        } else {
            output::list_item("No seed file found, skipping seed");
        }
    } else {
        output::step(4, 4, "Skipping seed...");
    }

    output::newline();
    success("Database reset complete!");

    Ok(())
}

/// Run `prax migrate status` - show migration status
async fn run_status() -> CliResult<()> {
    output::header("Migration Status");

    let cwd = std::env::current_dir()?;
    let _config = load_config(&cwd)?;
    let migrations_dir = cwd.join(MIGRATIONS_DIR);

    // List all migrations
    let mut migrations = Vec::new();
    if migrations_dir.exists() {
        for entry in std::fs::read_dir(&migrations_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                migrations.push(path);
            }
        }
    }
    migrations.sort();

    if migrations.is_empty() {
        output::info("No migrations found.");
        output::newline();
        output::section("Getting started");
        output::list_item("Run `prax migrate dev` to create your first migration");
        return Ok(());
    }

    output::section("Migrations");

    for (i, migration) in migrations.iter().enumerate() {
        let name = migration.file_name().unwrap().to_string_lossy();
        let applied = is_migration_applied(migration)?;

        let status = if applied {
            output::style_success("✓ Applied")
        } else {
            output::style_pending("â—‹ Pending")
        };

        output::numbered_item(i + 1, &format!("{} - {}", name, status));
    }

    output::newline();

    let applied_count = migrations.iter().filter(|m| is_migration_applied(m).unwrap_or(false)).count();
    let pending_count = migrations.len() - applied_count;

    output::kv("Total", &migrations.len().to_string());
    output::kv("Applied", &applied_count.to_string());
    output::kv("Pending", &pending_count.to_string());

    Ok(())
}

/// Run `prax migrate resolve` - resolve migration issues
async fn run_resolve(args: crate::cli::MigrateResolveArgs) -> CliResult<()> {
    output::header("Migrate Resolve");

    if args.rolled_back {
        output::step(1, 2, "Marking migration as rolled back...");
        // TODO: Mark migration as rolled back in history table

        output::step(2, 2, "Updating migration history...");

        output::newline();
        success(&format!(
            "Migration '{}' marked as rolled back",
            args.migration
        ));
    } else if args.applied {
        output::step(1, 2, "Marking migration as applied...");
        // TODO: Mark migration as applied in history table

        output::step(2, 2, "Updating migration history...");

        output::newline();
        success(&format!(
            "Migration '{}' marked as applied",
            args.migration
        ));
    } else {
        return Err(CliError::Command(
            "Must specify --applied or --rolled-back".to_string()
        ).into());
    }

    Ok(())
}

/// Run `prax migrate diff` - generate migration diff without applying
async fn run_diff(args: crate::cli::MigrateDiffArgs) -> CliResult<()> {
    output::header("Migrate Diff");

    let cwd = std::env::current_dir()?;
    let schema_path = args.schema.unwrap_or_else(|| cwd.join(SCHEMA_FILE_NAME));

    // Parse schema
    output::step(1, 3, "Parsing schema...");
    let schema_content = std::fs::read_to_string(&schema_path)?;
    let schema = parse_schema(&schema_content)?;

    // Get current database state
    output::step(2, 3, "Introspecting database...");
    // TODO: Implement database introspection

    // Generate diff
    output::step(3, 3, "Generating diff...");
    let diff_sql = generate_schema_diff(&schema)?;

    output::newline();

    if diff_sql.is_empty() {
        success("Schema is in sync with database - no changes needed");
    } else {
        output::section("Generated SQL");
        output::code(&diff_sql, "sql");

        if let Some(output_path) = args.output {
            std::fs::write(&output_path, &diff_sql)?;
            output::newline();
            success(&format!("Diff written to {}", output_path.display()));
        }
    }

    Ok(())
}

// =============================================================================
// Helper Functions
// =============================================================================

fn load_config(cwd: &PathBuf) -> CliResult<Config> {
    let config_path = cwd.join(CONFIG_FILE_NAME);
    if config_path.exists() {
        Config::load(&config_path)
    } else {
        Ok(Config::default())
    }
}

fn parse_schema(content: &str) -> CliResult<prax_schema::Schema> {
    prax_schema::parse_schema(content)
        .map_err(|e| CliError::Schema(format!("Failed to parse schema: {}", e)))
}

fn check_pending_migrations(migrations_dir: &PathBuf) -> CliResult<Vec<PathBuf>> {
    let mut pending = Vec::new();

    if !migrations_dir.exists() {
        return Ok(pending);
    }

    for entry in std::fs::read_dir(migrations_dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            if !is_migration_applied(&path)? {
                pending.push(path);
            }
        }
    }

    pending.sort();
    Ok(pending)
}

fn is_migration_applied(migration_path: &PathBuf) -> CliResult<bool> {
    // Check for a marker file indicating the migration has been applied
    // In production, this would check the migration history table
    let marker = migration_path.join(".applied");
    Ok(marker.exists())
}

fn create_migration(
    migrations_dir: &PathBuf,
    name: &str,
    schema: &prax_schema::ast::Schema,
) -> CliResult<PathBuf> {
    // Create migration directory
    let timestamp = chrono::Utc::now().format("%Y%m%d%H%M%S");
    let migration_name = format!("{}_{}", timestamp, name);
    let migration_path = migrations_dir.join(&migration_name);

    std::fs::create_dir_all(&migration_path)?;

    // Generate migration SQL
    let sql = generate_schema_diff(schema)?;

    // Write migration.sql
    let sql_path = migration_path.join("migration.sql");
    std::fs::write(&sql_path, &sql)?;

    Ok(migration_path)
}

fn generate_schema_diff(schema: &prax_schema::ast::Schema) -> CliResult<String> {
    use prax_schema::ast::{FieldType, ScalarType};

    let mut sql = String::new();

    sql.push_str("-- Migration generated by Prax\n\n");

    // Generate CREATE TABLE statements for each model
    for model in schema.models.values() {
        let table_name = model.table_name();

        sql.push_str(&format!("CREATE TABLE IF NOT EXISTS \"{}\" (\n", table_name));

        let mut columns = Vec::new();
        let mut primary_keys = Vec::new();

        for field in model.fields.values() {
            if field.is_relation() {
                continue;
            }

            let column_name = field
                .get_attribute("map")
                .and_then(|a| a.first_arg())
                .and_then(|v| v.as_string())
                .map(|s| s.to_string())
                .unwrap_or_else(|| to_snake_case(field.name()));

            let sql_type = field_type_to_sql(&field.field_type);
            let mut column_def = format!("    \"{}\" {}", column_name, sql_type);

            // Add constraints
            if field.is_id() {
                primary_keys.push(column_name.clone());
            }

            if field.has_attribute("auto") || field.has_attribute("autoincrement") {
                // PostgreSQL uses SERIAL types
                column_def = format!(
                    "    \"{}\" SERIAL",
                    column_name
                );
            }

            if field.has_attribute("unique") {
                column_def.push_str(" UNIQUE");
            }

            if !field.is_optional() && !field.is_id() {
                column_def.push_str(" NOT NULL");
            }

            // Default values
            if let Some(default_attr) = field.get_attribute("default") {
                if let Some(value) = default_attr.first_arg() {
                    let value_str = format_attribute_value(value);
                    column_def.push_str(&format!(
                        " DEFAULT {}",
                        sql_default_value(&value_str)
                    ));
                }
            }

            columns.push(column_def);
        }

        sql.push_str(&columns.join(",\n"));

        if !primary_keys.is_empty() {
            sql.push_str(",\n");
            sql.push_str(&format!(
                "    PRIMARY KEY (\"{}\")",
                primary_keys.join("\", \"")
            ));
        }

        sql.push_str("\n);\n\n");
        sql.push_str("\n");
    }

    // Generate enums
    for enum_def in schema.enums.values() {
        let enum_name = enum_def
            .attributes
            .iter()
            .find(|a| a.is("map"))
            .and_then(|a: &prax_schema::ast::Attribute| a.first_arg())
            .and_then(|v: &prax_schema::ast::AttributeValue| v.as_string())
            .map(|s| s.to_string())
            .unwrap_or_else(|| to_snake_case(enum_def.name()));

        sql.push_str(&format!(
            "DO $$ BEGIN\n    CREATE TYPE \"{}\" AS ENUM (",
            enum_name
        ));

        let variants: Vec<String> = enum_def
            .variants
            .iter()
            .map(|v| format!("'{}'", v.name()))
            .collect();

        sql.push_str(&variants.join(", "));
        sql.push_str(");\nEXCEPTION\n    WHEN duplicate_object THEN null;\nEND $$;\n\n");
    }

    return Ok(sql);

    fn field_type_to_sql(field_type: &FieldType) -> String {
        match field_type {
            FieldType::Scalar(scalar) => match scalar {
                ScalarType::Int => "INTEGER".to_string(),
                ScalarType::BigInt => "BIGINT".to_string(),
                ScalarType::Float => "DOUBLE PRECISION".to_string(),
                ScalarType::String => "TEXT".to_string(),
                ScalarType::Boolean => "BOOLEAN".to_string(),
                ScalarType::DateTime => "TIMESTAMP WITH TIME ZONE".to_string(),
                ScalarType::Date => "DATE".to_string(),
                ScalarType::Time => "TIME".to_string(),
                ScalarType::Json => "JSONB".to_string(),
                ScalarType::Bytes => "BYTEA".to_string(),
                ScalarType::Decimal => "DECIMAL".to_string(),
                ScalarType::Uuid => "UUID".to_string(),
                ScalarType::Cuid | ScalarType::Cuid2 | ScalarType::NanoId | ScalarType::Ulid => {
                    "TEXT".to_string()
                }
            },
            FieldType::Enum(name) => format!("\"{}\"", to_snake_case(name)),
            _ => "TEXT".to_string(),
        }
    }
}

async fn apply_migration(migration_path: &PathBuf, _config: &Config) -> CliResult<()> {
    let sql_path = migration_path.join("migration.sql");

    if !sql_path.exists() {
        return Err(CliError::Migration(format!(
            "Migration file not found: {}",
            sql_path.display()
        )));
    }

    let _sql = std::fs::read_to_string(&sql_path)?;

    // TODO: Execute SQL against database
    // This would use the database URL from config

    // Mark as applied
    let marker = migration_path.join(".applied");
    std::fs::write(&marker, chrono::Utc::now().to_rfc3339())?;

    Ok(())
}

fn sql_default_value(value: &str) -> String {
    match value.to_lowercase().as_str() {
        "now()" => "CURRENT_TIMESTAMP".to_string(),
        "uuid()" => "gen_random_uuid()".to_string(),
        "cuid()" | "cuid2()" | "nanoid()" | "ulid()" => {
            // These need application-level generation
            "''".to_string()
        }
        "true" => "TRUE".to_string(),
        "false" => "FALSE".to_string(),
        _ => value.to_string(),
    }
}

fn to_snake_case(name: &str) -> String {
    let mut result = String::new();
    for (i, c) in name.chars().enumerate() {
        if c.is_uppercase() {
            if i > 0 {
                result.push('_');
            }
            result.push(c.to_lowercase().next().unwrap());
        } else {
            result.push(c);
        }
    }
    result
}

fn format_attribute_value(value: &prax_schema::ast::AttributeValue) -> String {
    use prax_schema::ast::AttributeValue;

    match value {
        AttributeValue::String(s) => format!("\"{}\"", s),
        AttributeValue::Int(i) => i.to_string(),
        AttributeValue::Float(f) => f.to_string(),
        AttributeValue::Boolean(b) => b.to_string(),
        AttributeValue::Ident(id) => id.to_string(),
        AttributeValue::Function(name, args) => {
            if args.is_empty() {
                format!("{}()", name)
            } else {
                let arg_strs: Vec<String> = args.iter().map(format_attribute_value).collect();
                format!("{}({})", name, arg_strs.join(", "))
            }
        }
        AttributeValue::Array(items) => {
            let item_strs: Vec<String> = items.iter().map(format_attribute_value).collect();
            format!("[{}]", item_strs.join(", "))
        }
        AttributeValue::FieldRef(field) => field.to_string(),
        AttributeValue::FieldRefList(fields) => {
            format!(
                "[{}]",
                fields
                    .iter()
                    .map(|f| f.to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        }
    }
}