Documentation
// Copyright (c) 2018 lpxl <lpxl@protonmail.com>
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

use rusqlite::Connection;
use std::io;
use std::str;
use Result;

#[derive(RustEmbed)]
#[folder = "sql/"]
struct Sqlscript;

pub const DB_VERSION: i32 = 0;

fn initial_schema(conn: &Connection) -> Result<bool> {
    if let Some(s) = Sqlscript::get("initial.sql") {
        conn.execute_batch(str::from_utf8(&s)?)?;
        Ok(true)
    } else {
        Err(Box::new(io::Error::new(
            io::ErrorKind::Other,
            "Failed loading initial schema file!",
        )))
    }
}

pub fn run(conn: &Connection) -> Result<bool> {
    // Migration functions
    let mfns = [initial_schema];

    let version = conn.query_row::<i32, _>("SELECT `version` FROM `meta`", &[], |row| row.get(0));

    match version {
        Ok(v) => {
            if v != DB_VERSION {
                for f in mfns[v as usize..].iter() {
                    f(conn)?;
                }
            }
        }
        Err(_) => {
            for f in &mfns {
                f(conn)?;
            }
        }
    }

    Ok(true)
}