mdal/
migration.rs

1// Copyright (c) 2018 lpxl <lpxl@protonmail.com>
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
8
9use rusqlite::Connection;
10use std::io;
11use std::str;
12use Result;
13
14#[derive(RustEmbed)]
15#[folder = "sql/"]
16struct Sqlscript;
17
18pub const DB_VERSION: i32 = 0;
19
20fn initial_schema(conn: &Connection) -> Result<bool> {
21    if let Some(s) = Sqlscript::get("initial.sql") {
22        conn.execute_batch(str::from_utf8(&s)?)?;
23        Ok(true)
24    } else {
25        Err(Box::new(io::Error::new(
26            io::ErrorKind::Other,
27            "Failed loading initial schema file!",
28        )))
29    }
30}
31
32pub fn run(conn: &Connection) -> Result<bool> {
33    // Migration functions
34    let mfns = [initial_schema];
35
36    let version = conn.query_row::<i32, _>("SELECT `version` FROM `meta`", &[], |row| row.get(0));
37
38    match version {
39        Ok(v) => {
40            if v != DB_VERSION {
41                for f in mfns[v as usize..].iter() {
42                    f(conn)?;
43                }
44            }
45        }
46        Err(_) => {
47            for f in &mfns {
48                f(conn)?;
49            }
50        }
51    }
52
53    Ok(true)
54}