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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/*!
Embedded / programmable migrations

*/
use std;
use std::path::{Path, PathBuf};
use chrono::{DateTime, Utc};

use drivers;
use migratable::Migratable;
use config::Config;
use connection::DbConn;
use {DbKind, invalid_tag, Direction, DT_FORMAT};
use errors::*;


/// Define a migration that uses SQL statements saved in files.
///
/// Files defined in this migration must be present at run-time
#[derive(Clone, Debug)]
pub struct FileMigration {
    pub tag: String,
    pub up: Option<PathBuf>,
    pub down: Option<PathBuf>,
    pub stamp: Option<DateTime<Utc>>,
}
impl FileMigration {
    /// Create a new `FileMigration` with a given tag
    ///
    /// Tags may contain [a-z0-9-]
    pub fn with_tag(tag: &str) -> Result<Self> {
        if invalid_tag(tag) {
            bail_fmt!(ErrorKind::Migration, "Invalid tag `{}`. Tags can contain [a-z0-9-]", tag);
        }
        Ok(Self {
            tag: tag.to_owned(),
            up: None,
            down: None,
            stamp: None,
        })
    }

    fn check_path(path: &Path) -> Result<()> {
        if !path.exists() {
            bail_fmt!(ErrorKind::MigrationNotFound, "Migration file not found: {:?}", path)
        }
        Ok(())
    }

    /// Define the file to use for running `up` migrations
    pub fn up<T: AsRef<Path>>(&mut self, up_file: T) -> Result<&mut Self> {
        let path = up_file.as_ref();
        Self::check_path(path)?;
        self.up = Some(path.to_owned());
        Ok(self)
    }

    /// Define the file to use for running `down` migrations
    pub fn down<T: AsRef<Path>>(&mut self, down_file: T) -> Result<&mut Self> {
        let path = down_file.as_ref();
        Self::check_path(path)?;
        self.down = Some(path.to_owned());
        Ok(self)
    }

    /// Box this migration up so it can be stored with other migrations
    pub fn boxed(&self) -> Box<Migratable> {
        Box::new(self.clone())
    }
}

impl Migratable for FileMigration {
    fn apply_up(&self, db_kind: DbKind, config: &Config) -> std::result::Result<(), Box<std::error::Error>> {
        if let Some(ref up) = self.up {
            match db_kind {
                DbKind::Sqlite => {
                    let db_path = config.database_path()?;
                    drivers::sqlite::run_migration(&db_path, up)?;
                }
                DbKind::Postgres => {
                    let conn_str = config.connect_string()?;
                    drivers::pg::run_migration(&conn_str, up)?;
                }
            }
        } else {
            print_flush!("(empty) ...");
        }
        Ok(())
    }
    fn apply_down(&self, db_kind: DbKind, config: &Config) -> std::result::Result<(), Box<std::error::Error>> {
        if let Some(ref down) = self.down {
            match db_kind {
                DbKind::Sqlite => {
                    let db_path = config.database_path()?;
                    drivers::sqlite::run_migration(&db_path, down)?;
                }
                DbKind::Postgres => {
                    let conn_str = config.connect_string()?;
                    drivers::pg::run_migration(&conn_str, down)?;
                }
            }
        } else {
            print_flush!("(empty) ...");
        }
        Ok(())
    }
    fn tag(&self) -> String {
        match self.stamp.as_ref() {
            Some(dt) => {
                let dt_string = dt.format(DT_FORMAT).to_string();
                format!("{}_{}", dt_string, self.tag)
            }
            None => self.tag.to_owned(),
        }
    }
    fn description(&self, direction: &Direction) -> String {
        match *direction {
            Direction::Up   => self.up.as_ref().map(|p| format!("{:?}", p)).unwrap_or_else(|| self.tag()),
            Direction::Down => self.down.as_ref().map(|p| format!("{:?}", p)).unwrap_or_else(|| self.tag()),
        }
    }
}


/// Define an embedded migration
///
/// SQL statements provided to `EmbeddedMigration` will be embedded in
/// the executable so no files are required at run-time. The
/// standard `include_str!` macro can be used to embed contents of files.
/// Database specific features (`postgresql`/`sqlite`) are required to use
/// this functionality.
///
/// # Example
///
/// ```rust,no_run
/// # extern crate migrant_lib;
/// # use migrant_lib::EmbeddedMigration;
/// # fn main() { run().unwrap(); }
/// # fn run() -> Result<(), Box<std::error::Error>> {
/// EmbeddedMigration::with_tag("initial")?
///     .up(include_str!("../migrations/initial/up.sql"))
///     .down(include_str!("../migrations/initial/down.sql"));
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct EmbeddedMigration {
    pub tag: String,
    pub up: Option<&'static str>,
    pub down: Option<&'static str>,
}
impl EmbeddedMigration {
    /// Create a new `EmbeddedMigration` with the given tag
    ///
    /// Tags may contain [a-z0-9-]
    pub fn with_tag(tag: &str) -> Result<Self> {
        if invalid_tag(tag) {
            bail_fmt!(ErrorKind::Migration, "Invalid tag `{}`. Tags can contain [a-z0-9-]", tag);
        }
        Ok(Self {
            tag: tag.to_owned(),
            up: None,
            down: None,
        })
    }

    /// Statement to use for `up` migrations
    pub fn up(&mut self, stmt: &'static str) -> &mut Self {
        self.up = Some(stmt);
        self
    }

    /// Statement to use for `down` migrations
    pub fn down(&mut self, stmt: &'static str) -> &mut Self {
        self.down = Some(stmt);
        self
    }

    /// Box this migration up so it can be stored with other migrations
    pub fn boxed(&self) -> Box<Migratable> {
        Box::new(self.clone())
    }
}

impl Migratable for EmbeddedMigration {
    fn apply_up(&self, _db_kind: DbKind, _config: &Config) -> std::result::Result<(), Box<std::error::Error>> {
        if let Some(ref _up) = self.up {
            #[cfg(any(feature="postgresql", feature="sqlite"))]
            match _db_kind {
                DbKind::Sqlite => {
                    let db_path = _config.database_path()?;
                    drivers::sqlite::run_migration_str(&db_path, _up)?;
                }
                DbKind::Postgres => {
                    let conn_str = _config.connect_string()?;
                    drivers::pg::run_migration_str(&conn_str, _up)?;
                }
            }
            #[cfg(not(any(feature="postgresql", feature="sqlite")))]
            panic!("** Migrant ERROR: Database specific feature required to run embedded-file migration **");
        } else {
            print_flush!("(empty) ...");
        }
        Ok(())
    }
    fn apply_down(&self, db_kind: DbKind, config: &Config) -> std::result::Result<(), Box<std::error::Error>> {
        if let Some(ref down) = self.down {
            match db_kind {
                DbKind::Sqlite => {
                    let db_path = config.database_path()?;
                    drivers::sqlite::run_migration_str(&db_path, down)?;
                }
                DbKind::Postgres => {
                    let conn_str = config.connect_string()?;
                    drivers::pg::run_migration_str(&conn_str, down)?;
                }
            }
        } else {
            print_flush!("(empty) ...");
        }
        Ok(())
    }
    fn tag(&self) -> String {
        self.tag.to_owned()
    }
    fn description(&self, _: &Direction) -> String {
        self.tag()
    }
}


/// Define a programmable migration
///
/// `FnMigration`s have full database access. Database specific
/// features (`postgresql`/`sqlite`) are required to use this functionality.
/// A full re-export of database specific crates are available in `migrant_lib::types`
#[derive(Clone, Debug)]
pub struct FnMigration<T, U> {
    pub tag: String,
    pub up: Option<T>,
    pub down: Option<U>,
}

impl<T, U> FnMigration<T, U>
    where T: 'static + Clone + Fn(DbConn) -> std::result::Result<(), Box<std::error::Error>>,
          U: 'static + Clone + Fn(DbConn) -> std::result::Result<(), Box<std::error::Error>>
{
    /// Create a new `FnMigration` with the given tag
    ///
    /// Tags may contain [a-z0-9-]
    pub fn with_tag(tag: &str) -> Result<Self> {
        if invalid_tag(tag) {
            bail_fmt!(ErrorKind::Migration, "Invalid tag `{}`. Tags can contain [a-z0-9-]", tag);
        }
        Ok(Self {
            tag: tag.to_owned(),
            up: None,
            down: None,
        })
    }

    /// Function to use for `up` migrations
    pub fn up(&mut self, f_up: T) -> &mut Self {
        self.up = Some(f_up);
        self
    }

    /// Function to use for `down` migrations
    pub fn down(&mut self, f_down: U) -> &mut Self {
        self.down = Some(f_down);
        self
    }

    /// Box this migration up so it can be stored with other migrations
    pub fn boxed(&self) -> Box<Migratable> {
        Box::new(self.clone())
    }
}

impl<T, U> Migratable for FnMigration<T, U>
    where T: 'static + Clone + Fn(DbConn) -> std::result::Result<(), Box<std::error::Error>>,
          U: 'static + Clone + Fn(DbConn) -> std::result::Result<(), Box<std::error::Error>>
{
    fn apply_up(&self, _: DbKind, config: &Config) -> std::result::Result<(), Box<::std::error::Error>> {
        if let Some(ref up) = self.up {
            up(DbConn::new(config))?;
        } else {
            print_flush!("(empty) ...");
        }
        Ok(())
    }

    fn apply_down(&self, _: DbKind, config: &Config) -> std::result::Result<(), Box<::std::error::Error>> {
        if let Some(ref down) = self.down {
            down(DbConn::new(config))?;
        } else {
            print_flush!("(empty) ...");
        }
        Ok(())
    }

    fn tag(&self) -> String {
        self.tag.to_owned()
    }

    fn description(&self, _: &Direction) -> String {
        self.tag()
    }
}