#![doc(html_root_url = "https://starim.github.io/trek/")]
extern crate chrono;
extern crate postgres;
use std::fs::File;
use std::io::{self, Read, Write};
use std::path::Path;
use chrono::UTC;
pub mod error;
pub mod migration;
pub mod migration_index;
pub type Result<T> = std::result::Result<T, self::error::Error>;
pub fn create_migration(name: &str, migrations_dir: &Path) -> io::Result<String> {
let file_name_without_extension = format!("migration_{}_{}", time_prefix(), name);
let file_name = file_name_without_extension.clone() + ".rs";
let mut final_path = migrations_dir.to_path_buf();
final_path.push(file_name.clone());
let final_path = final_path.as_path();
{
let mut file = try!(File::create(final_path));
try!(file.write_all(migration_template(name, &*file_name_without_extension).as_bytes()));
}
Ok(file_name)
}
fn time_prefix() -> String {
UTC::now().format("%Y%m%d%H%M%S").to_string()
}
fn migration_template(name: &str, file_name_without_extension: &str) -> String {
let capitalized_name = name.to_owned().split('_').flat_map(|word|
word.chars().enumerate().flat_map(|input| {
let index = input.0;
let character = input.1;
if index == 0 {
character.to_uppercase().collect()
} else {
vec!(character)
}
}).collect::<Vec<char>>()
).collect::<String>();
format!("\
use std::fmt::{{self, Display}};
use postgres;
use trek::migration::Migration;
#[derive(Debug)]
pub struct {capitalized_name} {{
name: String,
}}
impl {capitalized_name} {{
pub fn new() -> Self {{
{capitalized_name} {{
name: \"{file_name_without_extension}\".to_owned()
}}
}}
}}
impl Migration for {capitalized_name} {{
fn up(&self, connection: &postgres::GenericConnection) -> postgres::Result<()> {{
try!(connection.execute(\"Your SQL here.\", &[]));
Ok(())
}}
fn down(&self, connection: &postgres::GenericConnection) -> postgres::Result<()> {{
try!(connection.execute(\"Your SQL here.\", &[]));
Ok(())
}}
}}
impl Display for {capitalized_name} {{
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {{
write!(formatter, \"{{}}\", self.name)
}}
}}
",
file_name_without_extension=file_name_without_extension,
capitalized_name=capitalized_name
)
}