Skip to main content

drizzle_cli/commands/
generate.rs

1//! Generate command implementation
2//!
3//! Generates migration files from schema changes.
4
5use std::fmt::Write;
6use std::path::Path;
7
8use crate::commands::overrides;
9use crate::config::{Casing, Config, Dialect, Driver, MigrationPrefix};
10use crate::error::CliError;
11use crate::output;
12use crate::snapshot::parse_result_to_snapshot;
13
14#[derive(clap::Args, Debug, Clone)]
15pub struct GenerateOptions {
16    /// Migration name (optional, auto-generated if not provided)
17    #[arg(short, long)]
18    pub name: Option<String>,
19
20    /// Create a custom (empty) migration file for manual SQL
21    #[arg(long)]
22    pub custom: bool,
23
24    /// Casing for generated identifiers (`camelCase` or `snake_case`)
25    #[arg(long)]
26    pub casing: Option<Casing>,
27
28    /// Override dialect from config
29    #[arg(long)]
30    pub dialect: Option<Dialect>,
31
32    /// Override driver from config
33    #[arg(long)]
34    pub driver: Option<Driver>,
35
36    /// Override schema path(s)
37    #[arg(long, value_delimiter = ',')]
38    pub schema: Option<Vec<String>>,
39
40    /// Override output directory
41    #[arg(long)]
42    pub out: Option<std::path::PathBuf>,
43
44    /// Override breakpoints setting
45    #[arg(long)]
46    pub breakpoints: Option<bool>,
47}
48
49/// Run the generate command.
50///
51/// # Errors
52///
53/// Returns [`CliError`] if the requested database cannot be resolved, the
54/// schema files fail to parse, snapshot/diff generation fails, or writing the
55/// new migration and journal files to disk fails.
56pub fn run(config: &Config, db_name: Option<&str>, opts: GenerateOptions) -> Result<(), CliError> {
57    use drizzle_migrations::words::{PrefixMode, generate_migration_tag_with_mode};
58
59    let db = config.database(db_name)?;
60
61    // CLI flag overrides config
62    let effective_casing = opts.casing.or(db.casing);
63    let effective_dialect = overrides::resolve_dialect(db, opts.dialect);
64    let effective_driver = overrides::resolve_driver(db, effective_dialect, opts.driver)?;
65    let effective_breakpoints = opts.breakpoints.unwrap_or(db.breakpoints);
66    let out_dir = opts
67        .out
68        .clone()
69        .unwrap_or_else(|| db.migrations_dir().to_path_buf());
70
71    crate::commands::harness::print_db_header(config, db_name);
72
73    println!("{}", output::heading("Generating migration..."));
74
75    println!(
76        "  {}: {}",
77        output::label("Dialect"),
78        effective_dialect.as_str()
79    );
80    if let Some(driver) = effective_driver {
81        println!("  {}: {}", output::label("Driver"), driver);
82    }
83
84    // Create output directories if they don't exist
85    std::fs::create_dir_all(&out_dir).map_err(|e| CliError::IoError(e.to_string()))?;
86
87    let legacy_journal_path = out_dir.join("meta").join("_journal.json");
88    if legacy_journal_path.exists() {
89        return Err(CliError::Other(
90            "Detected old drizzle-kit migration folders. Upgrade them before generating new migrations."
91                .to_string(),
92        ));
93    }
94
95    // Handle custom migration (empty migration file for manual SQL)
96    if opts.custom {
97        let bundle = db.bundle_enabled();
98        return generate_custom_migration(
99            &out_dir,
100            effective_breakpoints,
101            db.migrations.as_ref().and_then(|m| m.prefix),
102            opts.name,
103            bundle,
104        );
105    }
106
107    // Parse schema files
108    let parse_result = parse_schema_files(db, opts.schema.as_deref())?;
109
110    if parse_result.tables.is_empty() && parse_result.indexes.is_empty() {
111        println!(
112            "{}",
113            output::warning("No tables or indexes found in schema files.")
114        );
115        return Ok(());
116    }
117
118    println!(
119        "  {} {} table(s), {} index(es)",
120        output::label("Found"),
121        parse_result.tables.len(),
122        parse_result.indexes.len()
123    );
124
125    // Get dialect from config
126    let dialect = effective_dialect.to_base();
127
128    // Build current snapshot from parsed schema (use config dialect, not parser-detected)
129    let current_snapshot = parse_result_to_snapshot(&parse_result, dialect, effective_casing);
130
131    // Load previous snapshot if exists
132    let prev_snapshot = load_previous_snapshot(&out_dir, dialect)?;
133
134    // Generate diff
135    let generated = generate_diff(&prev_snapshot, &current_snapshot)?;
136
137    if generated.is_empty() {
138        println!("{}", output::warning("No schema changes detected 😴"));
139        return Ok(());
140    }
141
142    println!(
143        "  {} {} SQL statement(s)",
144        output::label("Generated"),
145        generated.statements.len()
146    );
147
148    let prefix_mode = db
149        .migrations
150        .as_ref()
151        .and_then(|m| m.prefix)
152        .map_or(PrefixMode::Timestamp, map_prefix_mode);
153
154    let next_idx = next_migration_index(&out_dir)?;
155    let migration_tag =
156        generate_migration_tag_with_mode(prefix_mode, next_idx, opts.name.as_deref());
157
158    let migration_dir =
159        write_migration_files(&out_dir, &migration_tag, &generated, effective_breakpoints)?;
160
161    // Regenerate {out_dir}/migrations.js bundle index when enabled.
162    // Auto-enabled for driver = durable-sqlite (see `DatabaseConfig::bundle_enabled`).
163    if db.bundle_enabled() {
164        write_migrations_js(&out_dir)?;
165    }
166
167    println!(
168        "{}",
169        output::success(&format!("Migration generated: {migration_tag}"))
170    );
171    println!("   {}", migration_dir.display());
172
173    Ok(())
174}
175
176/// Resolve and parse schema files.
177fn parse_schema_files(
178    db: &crate::config::DatabaseConfig,
179    schema_override: Option<&[String]>,
180) -> Result<drizzle_migrations::parser::ParseResult, CliError> {
181    use drizzle_migrations::parser::SchemaParser;
182
183    let schema_files = overrides::resolve_schema_files(db, schema_override)?;
184    if schema_files.is_empty() {
185        return Err(CliError::NoSchemaFiles(overrides::resolve_schema_display(
186            db,
187            schema_override,
188        )));
189    }
190
191    println!(
192        "  {} {} schema file(s)",
193        output::label("Parsing"),
194        schema_files.len()
195    );
196
197    let mut combined_code = String::new();
198    for path in &schema_files {
199        let code = std::fs::read_to_string(path)
200            .map_err(|e| CliError::IoError(format!("Failed to read {}: {}", path.display(), e)))?;
201        combined_code.push_str(&code);
202        combined_code.push('\n');
203    }
204
205    Ok(SchemaParser::parse(&combined_code))
206}
207
208/// Write migration.sql and snapshot.json to `{out_dir}/{tag}/`.
209fn write_migration_files(
210    out_dir: &Path,
211    migration_tag: &str,
212    generated: &drizzle_migrations::Plan,
213    breakpoints: bool,
214) -> Result<std::path::PathBuf, CliError> {
215    let sql_content = if breakpoints {
216        generated.statements.join("\n--> statement-breakpoint\n")
217    } else {
218        generated.statements.join("\n\n")
219    };
220
221    drizzle_migrations::writer::publish_migration_directory(out_dir, migration_tag, |folder| {
222        std::fs::write(folder.join("migration.sql"), &sql_content)
223            .map_err(|error| drizzle_migrations::MigrationError::IoError(error.to_string()))?;
224        generated
225            .snapshot
226            .save(&folder.join("snapshot.json"))
227            .map_err(|error| drizzle_migrations::MigrationError::SnapshotError(error.to_string()))
228    })
229    .map_err(map_migration_error)
230}
231
232/// Generate an empty custom migration for manual SQL
233fn generate_custom_migration(
234    out_dir: &Path,
235    _breakpoints: bool,
236    prefix: Option<MigrationPrefix>,
237    name: Option<String>,
238    bundle: bool,
239) -> Result<(), CliError> {
240    use drizzle_migrations::words::{PrefixMode, generate_migration_tag_with_mode};
241
242    let custom_name = name.unwrap_or_else(|| "custom".to_string());
243
244    let prefix_mode = prefix.map_or(PrefixMode::Timestamp, map_prefix_mode);
245
246    let migration_tag = generate_migration_tag_with_mode(
247        prefix_mode,
248        next_migration_index(out_dir)?,
249        Some(&custom_name),
250    );
251
252    let sql_content = "-- Custom SQL migration file, put your code below! --\n\n";
253    let migration_dir = drizzle_migrations::writer::publish_migration_directory(
254        out_dir,
255        &migration_tag,
256        |folder| {
257            std::fs::write(folder.join("migration.sql"), sql_content)
258                .map_err(|error| drizzle_migrations::MigrationError::IoError(error.to_string()))
259        },
260    )
261    .map_err(map_migration_error)?;
262
263    // Regenerate {out_dir}/migrations.js bundle index when enabled.
264    if bundle {
265        write_migrations_js(out_dir)?;
266    }
267
268    println!(
269        "{}",
270        output::success(&format!("Custom migration created: {migration_tag}"))
271    );
272    println!("   {}", migration_dir.display());
273    println!(
274        "{}",
275        output::label("   Edit the migration file to add your SQL statements.")
276    );
277
278    Ok(())
279}
280
281const fn map_prefix_mode(p: MigrationPrefix) -> drizzle_migrations::PrefixMode {
282    match p {
283        MigrationPrefix::Index => drizzle_migrations::PrefixMode::Index,
284        MigrationPrefix::Timestamp => drizzle_migrations::PrefixMode::Timestamp,
285        MigrationPrefix::Supabase => drizzle_migrations::PrefixMode::Supabase,
286        MigrationPrefix::Unix => drizzle_migrations::PrefixMode::Unix,
287        MigrationPrefix::None => drizzle_migrations::PrefixMode::None,
288    }
289}
290
291/// Load the previous snapshot from the migration directory
292fn load_previous_snapshot(
293    out_dir: &Path,
294    dialect: drizzle_types::Dialect,
295) -> Result<drizzle_migrations::schema::Snapshot, CliError> {
296    use drizzle_migrations::schema::Snapshot;
297
298    if let Some(snapshot_path) = latest_v3_snapshot_path(out_dir)? {
299        return Snapshot::load(&snapshot_path, dialect)
300            .map_err(|e| CliError::IoError(e.to_string()));
301    }
302
303    // No previous snapshot, return empty
304    Ok(Snapshot::empty(dialect))
305}
306
307fn next_migration_index(out_dir: &Path) -> Result<u32, CliError> {
308    let entries = collect_v3_migration_tags(out_dir)?;
309    let mut max_index: Option<u32> = None;
310
311    for tag in &entries {
312        let Some(prefix) = tag.split('_').next() else {
313            continue;
314        };
315
316        if prefix.len() > 10 || !prefix.chars().all(|c| c.is_ascii_digit()) {
317            continue;
318        }
319
320        if let Ok(idx) = prefix.parse::<u32>() {
321            max_index = Some(max_index.map_or(idx, |curr| curr.max(idx)));
322        }
323    }
324
325    Ok(max_index.map_or_else(
326        || u32::try_from(entries.len()).unwrap_or(u32::MAX),
327        |idx| idx.saturating_add(1),
328    ))
329}
330
331fn collect_v3_migration_tags(out_dir: &Path) -> Result<Vec<String>, CliError> {
332    if !out_dir.exists() {
333        return Ok(Vec::new());
334    }
335
336    let mut tags = Vec::new();
337    for entry in std::fs::read_dir(out_dir).map_err(|e| CliError::IoError(e.to_string()))? {
338        let entry = entry.map_err(|e| CliError::IoError(e.to_string()))?;
339        if !entry
340            .file_type()
341            .map_err(|e| CliError::IoError(e.to_string()))?
342            .is_dir()
343        {
344            continue;
345        }
346
347        let tag = entry.file_name().to_string_lossy().to_string();
348        if tag == "meta" {
349            continue;
350        }
351
352        if entry.path().join("migration.sql").exists() {
353            tags.push(tag);
354        }
355    }
356
357    tags.sort();
358    Ok(tags)
359}
360
361fn latest_v3_snapshot_path(out_dir: &Path) -> Result<Option<std::path::PathBuf>, CliError> {
362    if !out_dir.exists() {
363        return Ok(None);
364    }
365
366    let mut tags = Vec::new();
367    for entry in std::fs::read_dir(out_dir).map_err(|e| CliError::IoError(e.to_string()))? {
368        let entry = entry.map_err(|e| CliError::IoError(e.to_string()))?;
369        if !entry
370            .file_type()
371            .map_err(|e| CliError::IoError(e.to_string()))?
372            .is_dir()
373        {
374            continue;
375        }
376
377        let tag = entry.file_name().to_string_lossy().to_string();
378        if tag == "meta" {
379            continue;
380        }
381
382        let snapshot_path = entry.path().join("snapshot.json");
383        if snapshot_path.exists() {
384            tags.push((tag, snapshot_path));
385        }
386    }
387
388    tags.sort_by(|a, b| a.0.cmp(&b.0));
389    Ok(tags.pop().map(|(_, path)| path))
390}
391
392/// Write a `migrations.js` bundle index at the root of the migrations output
393/// folder.
394///
395/// Mirrors `drizzle-kit`'s `bundle: true` output. JS bundlers (Metro for
396/// Expo/React Native, Cloudflare Workers' bundler for Durable Objects `SQLite`)
397/// require static `import` statements to embed SQL text into the final JS
398/// bundle; this file is the entry point.
399///
400/// Rust-only consumers can ignore it — our [`drizzle_migrations::MigrationDir`]
401/// loader reads the `migration.sql` files directly.
402///
403/// # Errors
404///
405/// Returns [`CliError`] if the migrations directory cannot be enumerated or if
406/// writing the `migrations.js` file fails.
407pub fn write_migrations_js(out_dir: &Path) -> Result<(), CliError> {
408    let tags = collect_v3_migration_tags(out_dir)?;
409
410    let mut content = String::new();
411    for (idx, tag) in tags.iter().enumerate() {
412        let import_name = format!("m{idx:04}");
413        // Forward slashes work in JS import specifiers on every platform,
414        // including Windows — they are URL-style paths, not filesystem paths.
415        let _ = writeln!(
416            content,
417            "import {import_name} from './{tag}/migration.sql';"
418        );
419    }
420
421    content.push_str("\nexport default {\n  migrations: {\n");
422    for (idx, tag) in tags.iter().enumerate() {
423        let _ = writeln!(content, "    \"{tag}\": m{idx:04},");
424    }
425    content.push_str("  }\n};\n");
426
427    let migrations_js_path = out_dir.join("migrations.js");
428    std::fs::write(&migrations_js_path, content).map_err(|e| CliError::IoError(e.to_string()))?;
429
430    Ok(())
431}
432
433/// Map migration infrastructure errors to CLI errors.
434fn map_migration_error(error: drizzle_migrations::MigrationError) -> CliError {
435    match error {
436        drizzle_migrations::MigrationError::DialectMismatch => CliError::DialectMismatch,
437        drizzle_migrations::MigrationError::NoChanges => {
438            CliError::Other("No schema changes detected".to_string())
439        }
440        drizzle_migrations::MigrationError::ConfigError(_)
441        | drizzle_migrations::MigrationError::IoError(_)
442        | drizzle_migrations::MigrationError::SnapshotError(_) => {
443            CliError::MigrationError(error.to_string())
444        }
445    }
446}
447
448/// Generate diff between two snapshots
449fn generate_diff(
450    prev: &drizzle_migrations::schema::Snapshot,
451    current: &drizzle_migrations::schema::Snapshot,
452) -> Result<drizzle_migrations::Plan, CliError> {
453    drizzle_migrations::diff(prev, current).map_err(map_migration_error)
454}
455
456#[cfg(test)]
457mod tests {
458    use super::*;
459    use tempfile::tempdir;
460
461    fn touch_migration(out_dir: &Path, tag: &str) {
462        let dir = out_dir.join(tag);
463        std::fs::create_dir_all(&dir).expect("mkdir migration folder");
464        std::fs::write(dir.join("migration.sql"), "-- stub\n").expect("write migration.sql");
465    }
466
467    #[test]
468    fn custom_migration_rejects_unsafe_name_before_writing() {
469        let tmp = tempdir().expect("tempdir");
470        let error = generate_custom_migration(
471            tmp.path(),
472            false,
473            Some(MigrationPrefix::None),
474            Some("../escape".to_string()),
475            false,
476        )
477        .expect_err("unsafe name must fail");
478
479        assert!(matches!(error, CliError::MigrationError(_)));
480        assert_eq!(
481            std::fs::read_dir(tmp.path()).expect("read output").count(),
482            0
483        );
484    }
485
486    #[test]
487    fn custom_migration_is_published_as_complete_directory() {
488        let tmp = tempdir().expect("tempdir");
489        generate_custom_migration(
490            tmp.path(),
491            false,
492            Some(MigrationPrefix::None),
493            Some("manual_change".to_string()),
494            false,
495        )
496        .expect("generate custom migration");
497
498        let migration = tmp.path().join("manual_change");
499        assert!(migration.join("migration.sql").is_file());
500        assert_eq!(
501            std::fs::read_dir(tmp.path()).expect("read output").count(),
502            1
503        );
504    }
505
506    #[test]
507    fn migrations_js_contains_import_and_export_map_in_tag_order() {
508        let tmp = tempdir().expect("tempdir");
509        let out_dir = tmp.path();
510
511        touch_migration(out_dir, "20230331141203_first");
512        touch_migration(out_dir, "20230401091530_second");
513        touch_migration(out_dir, "20230501111111_third");
514
515        write_migrations_js(out_dir).expect("write migrations.js");
516
517        let contents =
518            std::fs::read_to_string(out_dir.join("migrations.js")).expect("read migrations.js");
519
520        assert!(
521            contents.contains("import m0000 from './20230331141203_first/migration.sql';"),
522            "first import present"
523        );
524        assert!(
525            contents.contains("import m0001 from './20230401091530_second/migration.sql';"),
526            "second import present"
527        );
528        assert!(
529            contents.contains("import m0002 from './20230501111111_third/migration.sql';"),
530            "third import present"
531        );
532        assert!(
533            contents.contains("\"20230331141203_first\": m0000,"),
534            "first map entry"
535        );
536        assert!(
537            contents.contains("\"20230401091530_second\": m0001,"),
538            "second map entry"
539        );
540        assert!(
541            contents.contains("\"20230501111111_third\": m0002,"),
542            "third map entry"
543        );
544        assert!(
545            contents.contains("export default {"),
546            "export default present"
547        );
548    }
549
550    #[test]
551    fn migrations_js_is_empty_shell_when_no_migrations_exist() {
552        let tmp = tempdir().expect("tempdir");
553        let out_dir = tmp.path();
554
555        write_migrations_js(out_dir).expect("write migrations.js");
556
557        let contents =
558            std::fs::read_to_string(out_dir.join("migrations.js")).expect("read migrations.js");
559
560        assert!(!contents.contains("import "), "no imports when empty");
561        assert!(
562            contents.contains("export default {"),
563            "export default still present"
564        );
565        assert!(
566            contents.contains("migrations: {"),
567            "migrations map still present"
568        );
569    }
570
571    #[test]
572    fn migrations_js_uses_forward_slashes_in_import_paths() {
573        // JS import specifiers use URL-style paths (always forward slashes),
574        // regardless of host filesystem separator. This guards against a
575        // Windows-specific regression that upstream shipped in beta.22.
576        let tmp = tempdir().expect("tempdir");
577        let out_dir = tmp.path();
578
579        touch_migration(out_dir, "20230331141203_first");
580
581        write_migrations_js(out_dir).expect("write migrations.js");
582
583        let contents =
584            std::fs::read_to_string(out_dir.join("migrations.js")).expect("read migrations.js");
585
586        assert!(
587            !contents.contains('\\'),
588            "import paths must use forward slashes even on Windows"
589        );
590        assert!(contents.contains("'./20230331141203_first/migration.sql'"));
591    }
592}