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
#![doc(html_root_url = "https://starim.github.io/trek/")]

extern crate chrono;
extern crate postgres;

use std::fs::File;
use std::io::{self, Write};
use std::path::Path;

use chrono::UTC;

pub mod error;
pub mod migration;
pub mod migration_index;


/// A type alias for the result type used by most of the methods in this crate's API.
pub type Result<T> = std::result::Result<T, self::error::Error>;

/// A convenience method that automates creating a new, empty database migration from a name and a
/// directory where the new migration file should be created.
///
/// # Examples:
///
/// ```no_run
/// # use std::path::Path;
/// # use trek::create_migration;
/// let migrations_dir = Path::new("src/db/migrations/");
/// match create_migration("create_users_table", migrations_dir) {
///     Ok(name) => println!("Created new migration named {}", name),
///     Err(error) => println!("Error creating new database migration: {}", 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()
}

/// Takes a name (e.g. "create_users_table"), a file name without the extension (e.g.
/// "20150822094521_create_users_table"), and the schema version for a new migration and returns a
/// string that can be written into the new migration file to fill in all the boilerplate code a
/// migration requires
fn migration_template(name: &str, file_name_without_extension: &str) -> String {
    // turns "my_migration" into "MyMigration"
    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 {
                // some exotic Unicode characters have an uppercase form composed of multiple
                // characters
                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
    )
}