zyvor-cli 0.1.0

CLI for Zyvor — schema-driven ORM code generator
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
mod ast;
mod error;
mod generator;
mod lexer;
mod migration;
mod naming;
mod parser;
mod validator;

use crate::ast::Schema;
use crate::error::{CliError, Result as CliResult};
use notify::Watcher;
use std::{env, fs, path::Path};

const SCHEMA_TEMPLATE: &str = r#"// Zyvor Schema
// Documentation: https://github.com/Fakhir-Israr-200219/zyvor

model User {
    id    Int    @id @default(autoincrement())
    name  String
    email String @unique
}
"#;

fn main() {
    if let Err(e) = run() {
        eprintln!("{e}");
        std::process::exit(1);
    }
}

fn run() -> CliResult<()> {
    let args: Vec<String> = env::args().skip(1).collect();

    // 1. Handle --help / --version
    if args.len() == 1 {
        match args[0].as_str() {
            "--help" | "-h" => {
                print_help();
                return Ok(());
            }
            "--version" | "-V" => {
                println!("Zyvor-CLI {}", env!("CARGO_PKG_VERSION"));
                return Ok(());
            }
            _ => {}
        }
    }

    // Only reject unknown options for simple commands (not migrate/init/dev)
    let first_arg = args.first().map(|s| s.as_str()).unwrap_or("");
    if !matches!(first_arg, "migrate" | "init" | "dev")
        && let Some(option) = args.iter().find(|arg| arg.starts_with('-'))
    {
        return Err(format!("Unknown option '{option}'. Run 'zyvor --help' for usage.").into());
    }

    // 2. Handle Commands
    let (command, schema_path, _output_path) = match args.first().map(String::as_str) {
        Some("validate") => {
            validate_argument_count(&args, 1, 2, "validate [SCHEMA]")?;
            (
                "validate",
                args.get(1).map(String::as_str).unwrap_or("rust.schema"),
                None::<&str>,
            )
        }
        Some("init") => {
            let zyvor_dir = Path::new(".zyvor");

            if zyvor_dir.exists() {
                println!(".zyvor/ already exists. Skipping init.");
                return Ok(());
            }

            fs::create_dir_all(zyvor_dir.join("generated"))
                .map_err(|e| format!("Failed to create .zyvor/generated/: {e}"))?;
            fs::create_dir_all(zyvor_dir.join("migrations"))
                .map_err(|e| format!("Failed to create .zyvor/migrations/: {e}"))?;

            fs::write(zyvor_dir.join("schema.zyvor"), SCHEMA_TEMPLATE)
                .map_err(|e| format!("Failed to write schema.zyvor: {e}"))?;

            // Write .env
            let env_content = "# Database connection string\n\
                               # ⚠️ Do NOT commit this file to git!\n\
                               DATABASE_URL=postgres://postgres:admin@localhost/zyvor_gen\n";
            fs::write(zyvor_dir.join(".env"), env_content)
                .map_err(|e| format!("Failed to write .env: {e}"))?;

            // Write config.toml
            let config_content = "[database]\n\
                                  url = \"postgres://postgres:admin@localhost/zyvor_gen\"\n";
            fs::write(zyvor_dir.join("config.toml"), config_content)
                .map_err(|e| format!("Failed to write config.toml: {e}"))?;

            // Write .gitignore
            let gitignore_content = ".env\n";
            fs::write(zyvor_dir.join(".gitignore"), gitignore_content)
                .map_err(|e| format!("Failed to write .gitignore: {e}"))?;

            println!("✅ Initialized zyvor project");
            println!();
            println!("  📁 .zyvor/schema.zyvor   ← Edit your schema here");
            println!("  📁 .zyvor/generated/       ← Entities will be generated here");
            println!("  📁 .zyvor/migrations/      ← Migration SQL will be generated here");
            println!("  📁 .zyvor/.env             ← Database URL (edit this)");
            println!("  📁 .zyvor/config.toml      ← Advanced config");
            println!("  📁 .zyvor/.gitignore       ← Protects .env from git");
            println!();
            println!("Next steps:");
            println!("  1. Edit .zyvor/schema.zyvor");
            println!("  2. Run: zyvor dev");
            return Ok(());
        }
        Some("dev") => {
            let schema_path = Path::new(".zyvor/schema.zyvor");
            let entities_output = Path::new(".zyvor/generated");
            let migrations_dir = Path::new(".zyvor/migrations");
            let snapshot_path = Path::new(".zyvor/migrations/snapshot.json");

            if !schema_path.exists() {
                return Err(CliError::ConfigError(
                    "No .zyvor/schema.zyvor found. Run 'zyvor init' first.".into(),
                ));
            }

            println!("👀 Watching .zyvor/schema.zyvor for changes...");
            println!("   Press Ctrl+C to stop\n");

            // Initial generation
            run_generation(schema_path, entities_output, migrations_dir, snapshot_path)?;

            // Setup file watcher
            let (tx, rx) = std::sync::mpsc::channel();

            let mut watcher =
                notify::recommended_watcher(move |res: Result<notify::Event, notify::Error>| {
                    if let Ok(event) = res
                        && (event.kind.is_modify() || event.kind.is_create())
                    {
                        let _ = tx.send(());
                    }
                })
                .map_err(|e| format!("Failed to create file watcher: {e}"))?;

            watcher
                .watch(schema_path, notify::RecursiveMode::NonRecursive)
                .map_err(|e| format!("Failed to watch schema file: {e}"))?;

            // Watch loop
            while rx.recv().is_ok() {
                std::thread::sleep(std::time::Duration::from_millis(300));
                while rx.try_recv().is_ok() {}

                println!("\n🔄 Schema change detected! Regenerating...");
                match run_generation(schema_path, entities_output, migrations_dir, snapshot_path) {
                    Ok(()) => println!("✅ Regeneration complete\n"),
                    Err(e) => eprintln!("❌ Regeneration failed: {e}\n"),
                }
            }

            return Ok(());
        }
        Some("generate") => {
            validate_argument_count(&args, 1, 2, "generate [SCHEMA]")?;
            (
                "generate",
                args.get(1).map(String::as_str).unwrap_or("rust.schema"),
                None,
            )
        }
        Some("migrate") => {
            validate_argument_count(
                &args,
                1,
                4,
                "migrate [SCHEMA] [OUTPUT] [--apply] [--database URL]",
            )?;

            let has_apply = args.iter().any(|a| a == "--apply");

            if has_apply {
                let db_url_owned = if let Some(pos) = args.iter().position(|a| a == "--database") {
                    args.get(pos + 1)
                        .ok_or_else(|| {
                            CliError::ConfigError("--database requires a connection string".into())
                        })?
                        .clone()
                } else {
                    load_database_url()?
                };
                let db_url: &str = &db_url_owned;

                let schema_path = args
                    .get(1)
                    .map(|s| s.as_str())
                    .filter(|s| !s.starts_with('-'))
                    .unwrap_or(".zyvor/schema.zyvor");

                let migrations_dir = Path::new(schema_path)
                    .parent()
                    .map(|p| p.join("migrations"))
                    .unwrap_or_else(|| Path::new(".zyvor/migrations").to_path_buf());

                println!("🚀 Applying migrations to database...");
                println!("   Database: {}", mask_database_url(db_url));

                let rt = tokio::runtime::Runtime::new()
                    .map_err(|e| format!("Failed to create async runtime: {e}"))?;
                // ✅ Naya — pehle DB ensure karo, phir connect
                rt.block_on(async {
                    // Auto-create database if not exists
                    ensure_database_exists(db_url).await
                        .map_err(|e| CliError::ConnectionError(e))?;

                    let pool = sqlx::PgPool::connect(db_url)
                        .await
                        .map_err(|e| CliError::ConnectionError(format!("Failed to connect to database: {e}")))?;

                    // Ensure tracking table exists
                    sqlx::raw_sql(
                        "CREATE TABLE IF NOT EXISTS _zyvor_migrations (\n\
                             id SERIAL PRIMARY KEY,\n\
                             name TEXT NOT NULL UNIQUE,\n\
                             checksum TEXT NOT NULL,\n\
                             applied_at TIMESTAMP NOT NULL DEFAULT NOW()\n\
                         );",
                    )
                    .execute(&pool)
                    .await
                    .map_err(|e| CliError::MigrationError(format!("Failed to create migration tracking table: {e}")))?;

                    // Collect all .sql files sorted by name
                    let mut migration_files: Vec<_> = fs::read_dir(&migrations_dir)
                        .map_err(|e| CliError::IoError {
                            path: migrations_dir.clone(),
                            source: e,
                        })?
                        .filter_map(|entry| entry.ok())
                        .filter(|entry| {
                            entry.path().extension()
                                .map(|ext| ext == "sql")
                                .unwrap_or(false)
                        })
                        .collect();

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

                    if migration_files.is_empty() {
                        return Err(CliError::MigrationError(
                            "No migration files found in .zyvor/migrations/. Run 'zyvor dev' first.".into(),
                        ));
                    }

                    println!("📋 Found {} migration file(s)\n", migration_files.len());

                    for migration_entry in &migration_files {
                        let migration_path = migration_entry.path();
                        let migration_name = migration_path.file_name()
                            .and_then(|n| n.to_str())
                            .unwrap_or("unknown");

                        let sql = fs::read_to_string(&migration_path)
                            .map_err(|e| CliError::IoError {
                                path: migration_path.clone(),
                                source: e,
                            })?;

                        // Calculate checksum
                        use std::collections::hash_map::DefaultHasher;
                        use std::hash::{Hash, Hasher};
                        let mut hasher = DefaultHasher::new();
                        sql.hash(&mut hasher);
                        let checksum = format!("{:x}", hasher.finish());

                        // Check if already applied
                        let existing: Option<(String,)> = sqlx::query_as(
                            "SELECT checksum FROM _zyvor_migrations WHERE name = $1"
                        )
                        .bind(migration_name)
                        .fetch_optional(&pool)
                        .await
                        .map_err(|e| CliError::MigrationError(format!("Failed to check migration history: {e}")))?;

                        if let Some((existing_checksum,)) = existing {
                            if existing_checksum == checksum {
                                println!("⏭️  {} already applied. Skipping.", migration_name);
                                continue;
                            } else {
                                return Err(CliError::MigrationError(format!(
                                    "❌ Schema drift in '{}'! Checksum mismatch.\nOld: {}\nNew: {}",
                                    migration_name, existing_checksum, checksum
                                )));
                            }
                        }

                        // Apply migration
                        println!("📝 Applying: {}", migration_name);
                        sqlx::raw_sql(&sql)
                            .execute(&pool)
                            .await
                            .map_err(|e| CliError::MigrationError(format!("Failed to apply {}: {e}", migration_name)))?;

                        // Record in tracking table
                        sqlx::query(
                            "INSERT INTO _zyvor_migrations (name, checksum) VALUES ($1, $2)"
                        )
                        .bind(migration_name)
                        .bind(&checksum)
                        .execute(&pool)
                        .await
                        .map_err(|e| CliError::MigrationError(format!("Failed to record {}: {e}", migration_name)))?;

                        println!("✅ {} applied successfully!", migration_name);
                    }

                    // List created tables
                    let tables: Vec<(String,)> = sqlx::query_as(
                        "SELECT tablename FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename"
                    )
                    .fetch_all(&pool)
                    .await
                    .map_err(|e| CliError::MigrationError(format!("Failed to list tables: {e}")))?;

                    println!("\nTables in database:");
                    for (table,) in &tables {
                        println!("  📋 {table}");
                    }

                    pool.close().await;
                    Ok::<(), CliError>(())
                })?;

                return Ok(());
            }

            // Original generate mode (no --apply flag)
            let schema_path = args
                .get(1)
                .map(|s| s.as_str())
                .filter(|s| !s.starts_with('-'))
                .unwrap_or(".zyvor/schema.zyvor");

            let output_path = args
                .get(2)
                .map(|s| s.as_str())
                .filter(|s| !s.starts_with('-'))
                .unwrap_or("migrations/0001_initial.sql");

            let source = fs::read_to_string(schema_path)
                .map_err(|e| format!("Failed to read schema '{schema_path}': {e}"))?;

            let tokens = lexer::tokenize(&source).map_err(|e| format!("Lexer error: {e:?}"))?;

            let schema = parser::Parser::new(tokens)
                .parse()
                .map_err(|e| CliError::ParseError {
                    line: 0,
                    column: 0,
                    message: format!("{e:?}"),
                })?;

            validator::validate(&schema).map_err(|e| format!("Validation error: {e:?}"))?;

            let sql = migration::generate_migration(&schema).map_err(CliError::GenerationError)?;

            if let Some(parent) = Path::new(output_path).parent()
                && !parent.as_os_str().is_empty()
            {
                fs::create_dir_all(parent)
                    .map_err(|e| format!("Failed to create migration directory: {e}"))?;
            }

            fs::write(output_path, sql)
                .map_err(|e| format!("Failed to write migration '{output_path}': {e}"))?;

            println!("Migration generated: {output_path}");
            return Ok(());
        }
        Some(other) if Path::new(other).is_file() && args.len() == 1 => ("generate", other, None),
        Some(other) => {
            return Err(CliError::ConfigError(format!(
                "Unknown command '{other}'. Run 'zyvor --help' for usage."
            )));
        }
        None => ("generate", "rust.schema", None),
    };

    // 3. Parse and Execute (for validate, generate)
    let source = fs::read_to_string(schema_path)
        .map_err(|e| format!("Failed to read schema '{schema_path}': {e}"))?;

    let tokens = lexer::tokenize(&source).map_err(|e| format!("Lexer error: {e:?}"))?;

    let schema = parser::Parser::new(tokens)
        .parse()
        .map_err(|e| CliError::ParseError {
            line: 0,
            column: 0,
            message: format!("{e:?}"),
        })?;

    validator::validate(&schema).map_err(|e| format!("Validation error: {e:?}"))?;

    match command {
        "validate" => {
            println!("Schema is valid: {schema_path}");
        }
        "generate" => {
            let output_path = "generated/entities.rs";
            let zyvor_dir = Path::new(".zyvor");
            let entities_output = zyvor_dir.join("generated");
            generator::write_modular_entities(&schema, entities_output)
                .map_err(|e| format!("Failed to write generated entities: {e}"))?;

            println!("Schema is valid: {schema_path}");
            println!("Generated entities: {output_path}");
        }
        _ => {
            return Err(CliError::ConfigError(format!(
                "Unsupported command '{command}'"
            )));
        }
    }

    Ok(())
}

fn run_generation(
    schema_path: &Path,
    entities_output: &Path,
    migrations_dir: &Path,
    snapshot_path: &Path,
) -> CliResult<()> {
    let source =
        fs::read_to_string(schema_path).map_err(|e| format!("Failed to read schema: {e}"))?;

    let tokens = lexer::tokenize(&source).map_err(|e| format!("Lexer error: {e:?}"))?;

    let schema = parser::Parser::new(tokens)
        .parse()
        .map_err(|e| CliError::ParseError {
            line: 0,
            column: 0,
            message: format!("{e:?}"),
        })?;

    validator::validate(&schema).map_err(|e| format!("Validation error: {e:?}"))?;

    // Snapshot check
    let current_content = source.clone();
    let schema_changed = if snapshot_path.exists() {
        let old_content = fs::read_to_string(snapshot_path).unwrap_or_default();
        old_content != current_content
    } else {
        true
    };

    if !schema_changed {
        println!("📋 Schema unchanged. Skipping.");
        return Ok(());
    }

    // Generate entities
    fs::create_dir_all(entities_output)
        .map_err(|e| format!("Failed to create generated dir: {e}"))?;

    generator::write_modular_entities(&schema, entities_output)
        .map_err(|e| format!("Failed to generate entities: {e}"))?;

    println!("  ✅ Generated: .zyvor/generated/ (modular)");

    // Generate migration
    fs::create_dir_all(migrations_dir)
        .map_err(|e| format!("Failed to create migrations dir: {e}"))?;

    let migration_sql =
        migration::generate_migration(&schema).map_err(CliError::GenerationError)?;
    let migration_file = migrations_dir.join("0001_initial.sql");
    fs::write(&migration_file, &migration_sql)
        .map_err(|e| format!("Failed to write migration: {e}"))?;

    println!("  ✅ Generated: .zyvor/migrations/0001_initial.sql");

    // Load old snapshot for diffing
    let old_snapshot: Option<Schema> = if snapshot_path.exists() {
        fs::read_to_string(snapshot_path)
            .ok()
            .and_then(|s| serde_json::from_str(&s).ok())
    } else {
        None
    };

    // Generate diff if old snapshot exists
    if let Some(ref old_snap) = old_snapshot {
        match migration::diff_schema(old_snap, &schema) {
            Ok(diff_sql) => {
                if !diff_sql.trim().is_empty() {
                    // Find next migration number
                    let mut next_num = 1u32;
                    if let Ok(entries) = fs::read_dir(migrations_dir) {
                        for entry in entries.flatten() {
                            if let Some(name) = entry.file_name().to_str()
                                && name.ends_with(".sql")
                                && let Some(num_str) = name.split('_').next()
                                && let Ok(n) = num_str.parse::<u32>()
                            {
                                next_num = next_num.max(n + 1);
                            }
                        }
                    }

                    let diff_filename = format!("{:04}_schema_update.sql", next_num);
                    let diff_path = migrations_dir.join(&diff_filename);
                    fs::write(&diff_path, &diff_sql)
                        .map_err(|e| format!("Failed to write diff migration: {e}"))?;
                    println!("  🔄 Schema change detected! Generated: {}", diff_filename);
                }
            }
            Err(e) => {
                println!("  ⚠️  Diff generation failed: {e}");
            }
        }
    }

    // Save new snapshot
    let snapshot_json = serde_json::to_string_pretty(&schema)
        .map_err(|e| format!("Failed to serialize snapshot: {e}"))?;
    fs::write(snapshot_path, &snapshot_json)
        .map_err(|e| format!("Failed to write snapshot: {e}"))?;
    println!("  💾 Snapshot saved");

    Ok(())
}

fn mask_database_url(url: &str) -> String {
    if let Some(at_pos) = url.find('@')
        && let Some(colon_pos) = url[..at_pos].rfind(':')
    {
        let prefix = &url[..colon_pos + 1];
        let suffix = &url[at_pos..];
        return format!("{prefix}****{suffix}");
    }
    url.to_string()
}

async fn ensure_database_exists(db_url: &str) -> Result<(), String> {
    let parsed = url::Url::parse(db_url).map_err(|e| format!("Invalid DATABASE_URL: {e}"))?;

    let db_name = parsed.path().trim_start_matches('/');
    if db_name.is_empty() {
        return Err("DATABASE_URL missing database name".into());
    }

    // Connect to default 'postgres' database
    let mut admin_url = parsed.clone();
    admin_url.set_path("/postgres");

    let pool = sqlx::PgPool::connect(admin_url.as_str())
        .await
        .map_err(|e| format!("Failed to connect to postgres DB: {e}"))?;

    // Check if target database exists
    let exists: bool =
        sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)")
            .bind(db_name)
            .fetch_one(&pool)
            .await
            .map_err(|e| format!("Failed to check database: {e}"))?;

    if !exists {
        println!("📦 Creating database '{}'...", db_name);
        let create_sql = format!("CREATE DATABASE \"{}\"", db_name.replace('"', "\"\""));
        sqlx::raw_sql(&create_sql)
            .execute(&pool)
            .await
            .map_err(|e| format!("Failed to create database '{}': {e}", db_name))?;
        println!("✅ Database '{}' created!", db_name);
    }

    pool.close().await;
    Ok(())
}

fn load_database_url() -> CliResult<String> {
    // Priority: env var > .env > config.toml
    if let Ok(url) = std::env::var("DATABASE_URL") {
        return Ok(url);
    }

    // Try loading .env file
    let env_path = Path::new(".zyvor/.env");
    if env_path.exists() {
        let content =
            fs::read_to_string(env_path).map_err(|e| format!("Failed to read .env: {e}"))?;
        for line in content.lines() {
            let line = line.trim();
            if line.starts_with('#') || line.is_empty() {
                continue;
            }
            if let Some((key, value)) = line.split_once('=')
                && key.trim() == "DATABASE_URL"
            {
                return Ok(value.trim().to_string());
            }
        }
    }

    // Try config.toml
    let config_path = Path::new(".zyvor/config.toml");
    if config_path.exists() {
        let content = fs::read_to_string(config_path)
            .map_err(|e| format!("Failed to read config.toml: {e}"))?;
        let parsed: toml::Value = content
            .parse()
            .map_err(|e| format!("Failed to parse config.toml: {e}"))?;
        if let Some(url) = parsed
            .get("database")
            .and_then(|d| d.get("url"))
            .and_then(|u| u.as_str())
        {
            return Ok(url.to_string());
        }
    }

    Err(CliError::ConfigError(
        "No database URL found.\n\
         Create .zyvor/.env with: DATABASE_URL=postgres://...\n\
         Or create .zyvor/config.toml with: [database]\n  url = \"...\""
            .into(),
    ))
}

fn validate_argument_count(args: &[String], min: usize, max: usize, usage: &str) -> CliResult<()> {
    if args.len() < min || args.len() > max {
        return Err(CliError::ConfigError(format!(
            "Invalid arguments. Usage: zyvor {}",
            usage
        )));
    }
    Ok(())
}

fn print_help() {
    println!(
        "zyvor {}\n\
         \n\
         Usage:\n\
           zyvor [SCHEMA]\n\
           zyvor validate [SCHEMA]\n\
           zyvor generate [SCHEMA]\n\
           zyvor migrate [SCHEMA] [OUTPUT]\n\
           zyvor migrate --apply --database URL\n\
           zyvor init\n\
           zyvor dev\n\
           zyvor --help\n\
           zyvor --version\n\
         \n\
         Commands:\n\
           init      Initialize a new zyvor project\n\
           dev       Watch schema and auto-generate\n\
           validate  Validate a schema\n\
           generate  Generate Rust entities (default)\n\
           migrate   Generate initial PostgreSQL migration SQL\n\
                     (Use --apply --database URL to execute directly on DB)\n\
         \n\
         Defaults:\n\
           SCHEMA    rust.schema\n\
           OUTPUT    migrations/0001_initial.sql\n",
        env!("CARGO_PKG_VERSION")
    );
}