Skip to content

Commit b062ff1

Browse files
committed
Add support for diesel migration generate migration_name to CLI
This command will create a timestamped directory in the migrations folder, along with the empty files `up.sql` and `down.sql`. Right now I'm spitting out absolute paths, it would be nice to print them as relative instead (unsure if this should be relative to the cwd or to the parent of the migrations directory).
1 parent e5e28f8 commit b062ff1

3 files changed

Lines changed: 19 additions & 3 deletions

File tree

diesel/src/migrations/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ fn revert_migration(conn: &Connection, migration: Box<Migration>)
216216
/// of the current directory, until it reaches the directory containing
217217
/// `Cargo.toml`. Returns `MigrationError::MigrationDirectoryNotFound`
218218
/// if no directory is found.
219-
fn find_migrations_directory() -> Result<PathBuf, MigrationError> {
219+
pub fn find_migrations_directory() -> Result<PathBuf, MigrationError> {
220220
search_for_migrations_directory(&try!(env::current_dir()))
221221
}
222222

diesel_cli/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ name = "diesel"
99
[dependencies]
1010
diesel = "^0.3.0"
1111
clap = "^1.5.5"
12+
chrono = "^0.2.17"

diesel_cli/src/main.rs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1+
extern crate chrono;
12
#[macro_use]
23
extern crate clap;
34
extern crate diesel;
45

6+
use chrono::*;
57
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
68
use diesel::migrations;
7-
use std::env;
9+
use std::{env, fs};
810

911
fn main() {
1012
let database_arg = || Arg::with_name("DATABASE_URL")
@@ -70,7 +72,20 @@ fn run_migration_command(matches: &ArgMatches) {
7072
}).unwrap();
7173
}
7274
("generate", Some(args)) => {
73-
panic!("Migration generator is not implemented this pass")
75+
let migration_name = args.value_of("MIGRATION_NAME").unwrap();
76+
let timestamp = Local::now().format("%Y%m%d%H%M%S");
77+
let versioned_name = format!("{}_{}", &timestamp, migration_name);
78+
let migration_dir = migrations::find_migrations_directory()
79+
.unwrap().join(versioned_name);
80+
fs::create_dir(&migration_dir).unwrap();
81+
82+
// FIXME: It would be nice to print these as relative paths
83+
let up_path = migration_dir.join("up.sql");
84+
println!("Creating {}", up_path.display());
85+
fs::File::create(up_path).unwrap();
86+
let down_path = migration_dir.join("down.sql");
87+
println!("Creating {}", down_path.display());
88+
fs::File::create(down_path).unwrap();
7489
}
7590
_ => unreachable!("The cli parser should prevent reaching here"),
7691
}

0 commit comments

Comments
 (0)