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 drizzle_migrations::schema::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::naming::{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 = Snapshot::from_parse_result(&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    let parse_result = SchemaParser::parse(&combined_code);
206    crate::snapshot::surface_parse_diagnostics(&parse_result)?;
207    Ok(parse_result)
208}
209
210/// Write migration.sql and snapshot.json to `{out_dir}/{tag}/`.
211fn write_migration_files(
212    out_dir: &Path,
213    migration_tag: &str,
214    generated: &drizzle_migrations::Plan,
215    breakpoints: bool,
216) -> Result<std::path::PathBuf, CliError> {
217    let sql_content = if breakpoints {
218        generated.statements.join("\n--> statement-breakpoint\n")
219    } else {
220        generated.statements.join("\n\n")
221    };
222
223    drizzle_migrations::writer::publish_migration_directory(out_dir, migration_tag, |folder| {
224        std::fs::write(folder.join("migration.sql"), &sql_content)
225            .map_err(|error| drizzle_migrations::MigrationError::IoError(error.to_string()))?;
226        generated
227            .snapshot
228            .save(&folder.join("snapshot.json"))
229            .map_err(|error| drizzle_migrations::MigrationError::SnapshotError(error.to_string()))
230    })
231    .map_err(map_migration_error)
232}
233
234/// Generate an empty custom migration for manual SQL
235fn generate_custom_migration(
236    out_dir: &Path,
237    _breakpoints: bool,
238    prefix: Option<MigrationPrefix>,
239    name: Option<String>,
240    bundle: bool,
241) -> Result<(), CliError> {
242    use drizzle_migrations::naming::{PrefixMode, generate_migration_tag_with_mode};
243
244    let custom_name = name.unwrap_or_else(|| "custom".to_string());
245
246    let prefix_mode = prefix.map_or(PrefixMode::Timestamp, map_prefix_mode);
247
248    let migration_tag = generate_migration_tag_with_mode(
249        prefix_mode,
250        next_migration_index(out_dir)?,
251        Some(&custom_name),
252    );
253
254    let sql_content = "-- Custom SQL migration file, put your code below! --\n\n";
255    let migration_dir = drizzle_migrations::writer::publish_migration_directory(
256        out_dir,
257        &migration_tag,
258        |folder| {
259            std::fs::write(folder.join("migration.sql"), sql_content)
260                .map_err(|error| drizzle_migrations::MigrationError::IoError(error.to_string()))
261        },
262    )
263    .map_err(map_migration_error)?;
264
265    // Regenerate {out_dir}/migrations.js bundle index when enabled.
266    if bundle {
267        write_migrations_js(out_dir)?;
268    }
269
270    println!(
271        "{}",
272        output::success(&format!("Custom migration created: {migration_tag}"))
273    );
274    println!("   {}", migration_dir.display());
275    println!(
276        "{}",
277        output::label("   Edit the migration file to add your SQL statements.")
278    );
279
280    Ok(())
281}
282
283const fn map_prefix_mode(p: MigrationPrefix) -> drizzle_migrations::PrefixMode {
284    match p {
285        MigrationPrefix::Index => drizzle_migrations::PrefixMode::Index,
286        MigrationPrefix::Timestamp => drizzle_migrations::PrefixMode::Timestamp,
287        MigrationPrefix::Supabase => drizzle_migrations::PrefixMode::Supabase,
288        MigrationPrefix::Unix => drizzle_migrations::PrefixMode::Unix,
289        MigrationPrefix::None => drizzle_migrations::PrefixMode::None,
290    }
291}
292
293/// Load the previous snapshot from the migration directory
294fn load_previous_snapshot(
295    out_dir: &Path,
296    dialect: drizzle_types::Dialect,
297) -> Result<drizzle_migrations::schema::Snapshot, CliError> {
298    use drizzle_migrations::schema::Snapshot;
299
300    if let Some(snapshot_path) = latest_v3_snapshot_path(out_dir)? {
301        return Snapshot::load(&snapshot_path, dialect)
302            .map_err(|e| CliError::IoError(e.to_string()));
303    }
304
305    // No previous snapshot, return empty
306    Ok(Snapshot::empty(dialect))
307}
308
309fn next_migration_index(out_dir: &Path) -> Result<u32, CliError> {
310    let entries = collect_v3_migration_tags(out_dir)?;
311    let mut max_index: Option<u32> = None;
312
313    for tag in &entries {
314        let Some(prefix) = tag.split('_').next() else {
315            continue;
316        };
317
318        // Index prefixes are short (`0000`); longer digit runs are timestamp
319        // (14), unix (10), or millisecond (13) prefixes, not indexes.
320        if prefix.len() > 5 || !prefix.chars().all(|c| c.is_ascii_digit()) {
321            continue;
322        }
323
324        if let Ok(idx) = prefix.parse::<u32>() {
325            max_index = Some(max_index.map_or(idx, |curr| curr.max(idx)));
326        }
327    }
328
329    Ok(max_index.map_or_else(
330        || u32::try_from(entries.len()).unwrap_or(u32::MAX),
331        |idx| idx.saturating_add(1),
332    ))
333}
334
335fn collect_v3_migration_tags(out_dir: &Path) -> Result<Vec<String>, CliError> {
336    if !out_dir.exists() {
337        return Ok(Vec::new());
338    }
339
340    let mut tags = Vec::new();
341    for entry in std::fs::read_dir(out_dir).map_err(|e| CliError::IoError(e.to_string()))? {
342        let entry = entry.map_err(|e| CliError::IoError(e.to_string()))?;
343        if !entry
344            .file_type()
345            .map_err(|e| CliError::IoError(e.to_string()))?
346            .is_dir()
347        {
348            continue;
349        }
350
351        let tag = entry.file_name().to_string_lossy().to_string();
352        if tag == "meta" {
353            continue;
354        }
355
356        if entry.path().join("migration.sql").exists() {
357            tags.push(tag);
358        }
359    }
360
361    tags.sort();
362    Ok(tags)
363}
364
365fn latest_v3_snapshot_path(out_dir: &Path) -> Result<Option<std::path::PathBuf>, CliError> {
366    if !out_dir.exists() {
367        return Ok(None);
368    }
369
370    let mut tags = Vec::new();
371    for entry in std::fs::read_dir(out_dir).map_err(|e| CliError::IoError(e.to_string()))? {
372        let entry = entry.map_err(|e| CliError::IoError(e.to_string()))?;
373        if !entry
374            .file_type()
375            .map_err(|e| CliError::IoError(e.to_string()))?
376            .is_dir()
377        {
378            continue;
379        }
380
381        let tag = entry.file_name().to_string_lossy().to_string();
382        if tag == "meta" {
383            continue;
384        }
385
386        let snapshot_path = entry.path().join("snapshot.json");
387        if snapshot_path.exists() {
388            tags.push((tag, snapshot_path));
389        }
390    }
391
392    tags.sort_by(|a, b| a.0.cmp(&b.0));
393    Ok(tags.pop().map(|(_, path)| path))
394}
395
396/// Write a `migrations.js` bundle index at the root of the migrations output
397/// folder.
398///
399/// Mirrors `drizzle-kit`'s `bundle: true` output. JS bundlers (Metro for
400/// Expo/React Native, Cloudflare Workers' bundler for Durable Objects `SQLite`)
401/// require static `import` statements to embed SQL text into the final JS
402/// bundle; this file is the entry point.
403///
404/// Rust-only consumers can ignore it — our [`drizzle_migrations::MigrationDir`]
405/// loader reads the `migration.sql` files directly.
406///
407/// # Errors
408///
409/// Returns [`CliError`] if the migrations directory cannot be enumerated or if
410/// writing the `migrations.js` file fails.
411pub fn write_migrations_js(out_dir: &Path) -> Result<(), CliError> {
412    let tags = collect_v3_migration_tags(out_dir)?;
413
414    let mut content = String::new();
415    for (idx, tag) in tags.iter().enumerate() {
416        let import_name = format!("m{idx:04}");
417        // Forward slashes work in JS import specifiers on every platform,
418        // including Windows — they are URL-style paths, not filesystem paths.
419        let _ = writeln!(
420            content,
421            "import {import_name} from './{tag}/migration.sql';"
422        );
423    }
424
425    content.push_str("\nexport default {\n  migrations: {\n");
426    for (idx, tag) in tags.iter().enumerate() {
427        let _ = writeln!(content, "    \"{tag}\": m{idx:04},");
428    }
429    content.push_str("  }\n};\n");
430
431    let migrations_js_path = out_dir.join("migrations.js");
432    std::fs::write(&migrations_js_path, content).map_err(|e| CliError::IoError(e.to_string()))?;
433
434    Ok(())
435}
436
437/// Map migration infrastructure errors to CLI errors.
438fn map_migration_error(error: drizzle_migrations::MigrationError) -> CliError {
439    match error {
440        drizzle_migrations::MigrationError::DialectMismatch => CliError::DialectMismatch,
441        drizzle_migrations::MigrationError::NoChanges => {
442            CliError::Other("No schema changes detected".to_string())
443        }
444        drizzle_migrations::MigrationError::ConfigError(_)
445        | drizzle_migrations::MigrationError::IoError(_)
446        | drizzle_migrations::MigrationError::SnapshotError(_) => {
447            CliError::MigrationError(error.to_string())
448        }
449    }
450}
451
452/// Generate diff between two snapshots
453fn generate_diff(
454    prev: &drizzle_migrations::schema::Snapshot,
455    current: &drizzle_migrations::schema::Snapshot,
456) -> Result<drizzle_migrations::Plan, CliError> {
457    drizzle_migrations::diff(prev, current).map_err(map_migration_error)
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463    use tempfile::tempdir;
464
465    fn touch_migration(out_dir: &Path, tag: &str) {
466        let dir = out_dir.join(tag);
467        std::fs::create_dir_all(&dir).expect("mkdir migration folder");
468        std::fs::write(dir.join("migration.sql"), "-- stub\n").expect("write migration.sql");
469    }
470
471    #[test]
472    fn custom_migration_rejects_unsafe_name_before_writing() {
473        let tmp = tempdir().expect("tempdir");
474        let error = generate_custom_migration(
475            tmp.path(),
476            false,
477            Some(MigrationPrefix::None),
478            Some("../escape".to_string()),
479            false,
480        )
481        .expect_err("unsafe name must fail");
482
483        assert!(matches!(error, CliError::MigrationError(_)));
484        assert_eq!(
485            std::fs::read_dir(tmp.path()).expect("read output").count(),
486            0
487        );
488    }
489
490    #[test]
491    fn custom_migration_is_published_as_complete_directory() {
492        let tmp = tempdir().expect("tempdir");
493        generate_custom_migration(
494            tmp.path(),
495            false,
496            Some(MigrationPrefix::None),
497            Some("manual_change".to_string()),
498            false,
499        )
500        .expect("generate custom migration");
501
502        let migration = tmp.path().join("manual_change");
503        assert!(migration.join("migration.sql").is_file());
504        assert_eq!(
505            std::fs::read_dir(tmp.path()).expect("read output").count(),
506            1
507        );
508    }
509
510    #[test]
511    fn migrations_js_contains_import_and_export_map_in_tag_order() {
512        let tmp = tempdir().expect("tempdir");
513        let out_dir = tmp.path();
514
515        touch_migration(out_dir, "20230331141203_first");
516        touch_migration(out_dir, "20230401091530_second");
517        touch_migration(out_dir, "20230501111111_third");
518
519        write_migrations_js(out_dir).expect("write migrations.js");
520
521        let contents =
522            std::fs::read_to_string(out_dir.join("migrations.js")).expect("read migrations.js");
523
524        assert!(
525            contents.contains("import m0000 from './20230331141203_first/migration.sql';"),
526            "first import present"
527        );
528        assert!(
529            contents.contains("import m0001 from './20230401091530_second/migration.sql';"),
530            "second import present"
531        );
532        assert!(
533            contents.contains("import m0002 from './20230501111111_third/migration.sql';"),
534            "third import present"
535        );
536        assert!(
537            contents.contains("\"20230331141203_first\": m0000,"),
538            "first map entry"
539        );
540        assert!(
541            contents.contains("\"20230401091530_second\": m0001,"),
542            "second map entry"
543        );
544        assert!(
545            contents.contains("\"20230501111111_third\": m0002,"),
546            "third map entry"
547        );
548        assert!(
549            contents.contains("export default {"),
550            "export default present"
551        );
552    }
553
554    #[test]
555    fn migrations_js_is_empty_shell_when_no_migrations_exist() {
556        let tmp = tempdir().expect("tempdir");
557        let out_dir = tmp.path();
558
559        write_migrations_js(out_dir).expect("write migrations.js");
560
561        let contents =
562            std::fs::read_to_string(out_dir.join("migrations.js")).expect("read migrations.js");
563
564        assert!(!contents.contains("import "), "no imports when empty");
565        assert!(
566            contents.contains("export default {"),
567            "export default still present"
568        );
569        assert!(
570            contents.contains("migrations: {"),
571            "migrations map still present"
572        );
573    }
574
575    #[test]
576    fn migrations_js_uses_forward_slashes_in_import_paths() {
577        // JS import specifiers use URL-style paths (always forward slashes),
578        // regardless of host filesystem separator. This guards against a
579        // Windows-specific regression that upstream shipped in beta.22.
580        let tmp = tempdir().expect("tempdir");
581        let out_dir = tmp.path();
582
583        touch_migration(out_dir, "20230331141203_first");
584
585        write_migrations_js(out_dir).expect("write migrations.js");
586
587        let contents =
588            std::fs::read_to_string(out_dir.join("migrations.js")).expect("read migrations.js");
589
590        assert!(
591            !contents.contains('\\'),
592            "import paths must use forward slashes even on Windows"
593        );
594        assert!(contents.contains("'./20230331141203_first/migration.sql'"));
595    }
596}