migratour 0.1.0

A very simple database migration tool
Documentation
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use std::env;
use std::error::Error;
use std::i32;
use std::path::Path;
use std::process;

use db::Db;
use db::DbExe;
use db::MySqlDb;
use db::PostgresDb;
use serde::Deserialize;
use serde::Deserializer;

mod db;

use std::io::Write;

use std::fs;

#[derive(Debug)]
pub enum DatabaseType {
    Postgres,
    MySql,
}

impl Default for DatabaseType {
    fn default() -> Self {
        DatabaseType::Postgres
    }
}

impl<'de> Deserialize<'de> for DatabaseType {
    fn deserialize<D>(deserializer: D) -> Result<DatabaseType, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s: String = Deserialize::deserialize(deserializer)?;
        match s.to_lowercase().as_str() {
            "postgres" => Ok(DatabaseType::Postgres),
            "mysql" => Ok(DatabaseType::MySql),
            _ => Err(serde::de::Error::unknown_variant(
                &s,
                &["postgres", "mysql"],
            )),
        }
    }
}

#[derive(Debug, Deserialize)]
struct ConfigFileInput {
    database: Option<DatabaseType>,
    database_url: Option<String>,
}

#[derive(Debug, Default)]
pub struct Config {
    pub database: DatabaseType,
    pub database_url: String,
}

impl Config {
    fn new(database: DatabaseType, database_url: String) -> Config {
        Config {
            database,
            database_url,
        }
    }
}

pub fn read_config_file() -> Result<Config, Box<dyn Error>> {
    let content = fs::read_to_string("./db.toml")?;
    let decoded: ConfigFileInput = toml::from_str(&content)?;

    let db = match decoded.database {
        None => {
            return Err("bad database type name")?;
        }
        Some(a) => a,
    };

    let db_url = match decoded.database_url {
        None => {
            return Err("bad database url")?;
        }
        Some(a) => a,
    };

    return Ok(Config::new(db, db_url));
}

#[derive(Debug, Clone)]
pub enum Command {
    Up(bool, i32),
    Down(i32),
    New(String),
    Last,
    Num,
}
impl Default for Command {
    fn default() -> Self {
        Command::New(String::default())
    }
}

#[derive(Default)]
pub struct Flags {
    pub config: Config,
    pub cmd: Command,
}

impl Flags {
    pub fn parse(args: Vec<String>) -> Result<Flags, Box<dyn Error>> {
        let mut f: Flags = Flags::default();
        let mut i = 1;
        while i < args.len() {
            match args[i].as_str() {
                "-u" | "--db-url" => {
                    if i + 1 < args.len() {
                        f.config.database_url = args[i + 1].clone();
                        i = i + 1
                    }
                }
                "-d" | "--db" => {
                    if i + 1 < args.len() {
                        f.config.database_url = args[i + 1].clone();
                        i = i + 1
                    }
                }
                "new" => {
                    if i + 1 < args.len() {
                        let mig_name = args[i + 1].clone();

                        f.cmd = Command::New(mig_name);
                        return Ok(f);
                    } else {
                        return Err("please mention the name of the migration file")?;
                    }
                }
                "up" => {
                    if i + 1 < args.len() {
                        match args[i + 1].clone().parse::<i32>() {
                            Ok(n) => {
                                f.cmd = Command::Up(false, n);
                                return Ok(f);
                            }
                            Err(_) => {
                                return Err("please enter a valid numeric value for up command")?;
                            }
                        }
                    } else {
                        f.cmd = Command::Up(true, -1);
                    }
                }
                "down" => {
                    if i + 1 < args.len() {
                        match args[i + 1].clone().parse::<i32>() {
                            Ok(n) => {
                                f.cmd = Command::Down(n);
                                return Ok(f);
                            }
                            Err(_) => {
                                return Err("please enter a valid numeric value for down command")?;
                            }
                        }
                    } else {
                        return Err("please enter a valid numeric value for down command")?;
                    }
                }

                "last" => {
                    f.cmd = Command::Last;
                    return Ok(f);
                }

                "num" => {
                    f.cmd = Command::Num;
                    return Ok(f);
                }

                _ => {
                    return Err("invalid command")?;
                }
            }

            i = i + 1;
        }

        return Ok(f);
    }
}

pub fn read_migration_files() -> Result<Vec<String>, Box<dyn Error>> {
    let entries = fs::read_dir("./migrations")?;
    let file_names: Vec<String> = entries
        .filter_map(|entry| {
            let path = entry.ok()?.path();
            if path.is_file() {
                path.file_name()?.to_str().map(|s| s.to_owned())
            } else {
                None
            }
        })
        .collect();

    return Ok(file_names);
}

pub fn new_migration(name: &String) -> Result<(), Box<dyn Error>> {
    let mg_folder_exists = Path::new("./migrations").is_dir();

    if !mg_folder_exists {
        fs::create_dir("./migrations")?;
    }

    let file_names = read_migration_files()?;

    let file_serial_extracted: Vec<String> = file_names
        .iter()
        .map(|s| s.chars().take(4).collect())
        .collect();

    let mut valid = true;
    let serial: Vec<i32> = file_serial_extracted
        .iter()
        .map(|s| {
            s.parse::<i32>().unwrap_or_else(|_| {
                valid = false;
                -1
            })
        })
        .collect();

    if valid == false {
        return Err("invalid name for your migration files")?;
    }

    let largest = serial.iter().max();
    let largets_serial = match largest {
        Some(n) => n,
        None => &0,
    }
    .to_owned();

    let new_serial = largets_serial + 1;
    let formatted_serial = format!("{:04}", new_serial);

    let migration_name_up = "./migrations/".to_owned() + &formatted_serial + "_" + name + ".up.sql";
    let migration_name_down =
        "./migrations/".to_owned() + &formatted_serial + "_" + name + ".down.sql";

    let mut up_file = fs::File::create(migration_name_up)?;
    let mut down_file = fs::File::create(migration_name_down)?;

    up_file.write("--Please write your up migrations here".as_bytes())?;
    down_file.write("--Please write your down migrations here".as_bytes())?;

    println!("initialized migration file {}", name);
    Ok(())
}

fn filter_migration_file(mg_type: &str, mg_files: Vec<String>) -> Vec<String> {
    mg_files
        .iter()
        .filter(|file_name| {
            let ext: Vec<&str> = file_name.split(".").collect();
            if let Some(second_last_word) = ext.get(ext.len() - 2) {
                if second_last_word.to_lowercase() == mg_type {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        })
        .map(|s| s.to_string())
        .collect()
}

pub async fn up_migration(pool: DbExe, num: i32) -> Result<(), Box<dyn Error>> {
    let migrations_applied_num = pool.get_migration_table_count().await?;

    let migration_files = read_migration_files()?;

    let mut up_migration_files: Vec<String> = filter_migration_file("up", migration_files);

    up_migration_files.sort();

    let unapplied_migrations: Vec<&String> = up_migration_files
        .iter()
        .skip(migrations_applied_num)
        .collect();

    let migrations_to_apply: i32;
    if num == -1 {
        migrations_to_apply = unapplied_migrations.len() as i32;
    } else {
        migrations_to_apply = num;
    }

    pool.up_migration_transaction(unapplied_migrations, migrations_to_apply)
        .await?;

    Ok(())
}

pub async fn down_migration(pool: DbExe, num: i32) -> Result<(), Box<dyn Error>> {
    let migrations_applied_num = pool.get_migration_table_count().await?;

    let migration_files = read_migration_files()?;

    let mut down_migration_files: Vec<String> = filter_migration_file("down", migration_files);

    down_migration_files.sort();

    if migrations_applied_num < num as usize {
        return Err(format!("number of applied migrations applied {} lesser than the number of migrations to be reverted {}",migrations_applied_num,down_migration_files.len()))?;
    }

    let down_migrations: Vec<&String> = down_migration_files
        .iter()
        .skip(migrations_applied_num - (num as usize))
        .take(num as usize)
        .collect();

    pool.down_migration_transaction(down_migrations).await?;

    Ok(())
}

pub async fn last_migration(pool: DbExe) -> Result<(), Box<dyn Error>> {
    let last_migration_name = pool.get_last_migration().await?;
    println!(
        "the last migration applied on the database is {}",
        last_migration_name
    );
    Ok(())
}

pub async fn cmd_run() -> Result<(), Box<dyn Error>> {
    let args: Vec<String> = env::args().collect();

    if args.len() < 2 {
        eprintln!("please pass some argument");
        process::exit(1)
    }

    let mut f = Flags::parse(args).unwrap_or_else(|err| {
        eprintln!("error parsing flags {}", err);
        process::exit(1);
    });

    if f.config.database_url == "" {
        f.config = read_config_file().unwrap_or_else(|err| {
            eprintln!("error reading file {}", err);
            process::exit(1);
        });
    }

    let db_conn: DbExe = match f.config.database {
        DatabaseType::MySql => {
            DbExe::MySqlExe(MySqlDb::new_connection(f.config.database_url).await?)
        }
        DatabaseType::Postgres => {
            DbExe::PgExe(PostgresDb::new_connection(f.config.database_url).await?)
        }
    };

    db_conn.ping_db().await.unwrap_or_else(|err| {
        eprintln!("error connecting to the database {}", err);
        process::exit(1);
    });

    let tb_exists = db_conn.table_exists().await.unwrap_or_else(|err| {
        eprintln!("error connecting to database {}", err);
        process::exit(1);
    });

    if !tb_exists {
        db_conn
            .create_migration_table()
            .await
            .unwrap_or_else(|err| {
                eprintln!("error creating database migration table {}", err);
                process::exit(1);
            })
    }

    match &f.cmd {
        Command::New(s) => new_migration(&s.clone()).unwrap_or_else(|err| {
            eprintln!("there is some error in migration files {}", err);
            process::exit(1)
        }),
        Command::Up(all, n) => {
            let num: i32;
            if *all == true {
                num = -1;
            } else {
                num = *n;
            }

            up_migration(db_conn, num).await.unwrap_or_else(|err| {
                eprintln!("there was some error when migrating up {}", err);
                process::exit(1)
            })
        }
        Command::Down(n) => down_migration(db_conn, *n).await.unwrap_or_else(|err| {
            eprintln!("there was some error when migrating down {}", err);
            process::exit(1)
        }),
        Command::Last => last_migration(db_conn).await.unwrap_or_else(|err| {
            eprintln!("there was some error when migrating down {}", err);
            process::exit(1)
        }),
        Command::Num => match db_conn.get_migration_table_count().await {
            Ok(num) => {
                println!("{} migrations have been applied", num)
            }
            Err(err) => {
                eprintln!(
                    "there was saome error counting number of migrations {}",
                    err
                );
                process::exit(1);
            }
        },
    }

    Ok(())
}