X-Git-Url: http://git.euphorik.ch/?a=blobdiff_plain;f=backend%2Fsrc%2Fdb.rs;h=1d38a454f03091e1d1020f1a19001919494aef8b;hb=108476e3554ea3a25dca5b5ab260f38c1e734221;hp=f3356d206eb8330027e7d8ab6271f370a3e7b52c;hpb=212222751363c15b2155555ac700ff50b69ac578;p=recipes.git diff --git a/backend/src/db.rs b/backend/src/db.rs index f3356d2..1d38a45 100644 --- a/backend/src/db.rs +++ b/backend/src/db.rs @@ -1,39 +1,136 @@ -use std::path::Path; -use std::fs; +use crate::consts::SQL_FILENAME; + +use super::consts; + +use std::{fs::{self, File}, path::Path, io::Read}; //use rusqlite::types::ToSql; //use rusqlite::{Connection, Result, NO_PARAMS}; +use r2d2::Pool; +use r2d2_sqlite::SqliteConnectionManager; const CURRENT_DB_VERSION: u32 = 1; -struct Connection { - pub sqlite_con : rusqlite::Connection +#[derive(Debug)] +pub enum DBError { + SqliteError(rusqlite::Error), + R2d2Error(r2d2::Error), + UnsupportedVersion(u32), + Other(String), +} + +pub struct Connection { + //con: rusqlite::Connection + pool: Pool +} + +pub struct Recipe { + pub title: String, + pub id: i32, +} + +impl std::convert::From for DBError { + fn from(error: rusqlite::Error) -> Self { + DBError::SqliteError(error) + } +} + +impl std::convert::From for DBError { + fn from(error: r2d2::Error) -> Self { + DBError::R2d2Error(error) + } } impl Connection { - fn new() -> Connection { + pub fn new() -> Result { - // TODO: use a constant in consts module. - let data_dir = Path::new("data"); + let data_dir = Path::new(consts::DB_DIRECTORY); if !data_dir.exists() { fs::DirBuilder::new().create(data_dir).unwrap(); } - Connection { sqlite_con : rusqlite::Connection::open(data_dir.join("recipes.sqlite")).unwrap() } + let manager = SqliteConnectionManager::file(consts::DB_FILENAME); + let pool = r2d2::Pool::new(manager).unwrap(); + + let connection = Connection { pool }; + connection.create_or_update()?; + Ok(connection) } -} -pub fn create_or_update() { - let connection = Connection::new(); + /* + * Called after the connection has been established for creating or updating the database. + * The 'Version' table tracks the current state of the database. + */ + fn create_or_update(self: &Self) -> Result<(), DBError> { + // let connection = Connection::new(); + // let mut stmt = connection.sqlite_con.prepare("SELECT * FROM versions ORDER BY date").unwrap(); + // let mut stmt = connection.sqlite_con.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='versions'").unwrap(); + + // Check the Database version. + let mut con = self.pool.get()?; + let tx = con.transaction()?; + + // Version 0 corresponds to an empty database. + let mut version = { + match tx.query_row( + "SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'", + [], + |row| row.get::(0) + ) { + Ok(_) => tx.query_row("SELECT [version] FROM [Version]", [], |row| row.get(0)).unwrap_or_default(), + Err(_) => 0 + } + }; + + while Connection::update_to_next_version(version, &tx)? { + version += 1; + } - // let mut stmt = connection.sqlite_con.prepare("SELECT * FROM versions ORDER BY date").unwrap(); + tx.commit()?; + + Ok(()) + } + + fn update_to_next_version(current_version: u32, tx: &rusqlite::Transaction) -> Result { + let next_version = current_version + 1; + + if next_version <= CURRENT_DB_VERSION { + println!("Update to version {}...", next_version); + } + + fn ok(updated: bool) -> Result { + if updated { + println!("Version updated"); + } + Ok(updated) + } + + match next_version { + 1 => { + tx.execute_batch(&load_sql_file(next_version)?)?; + + ok(true) + } + + // Version 1 doesn't exist yet. + 2 => + ok(false), + + v => + Err(DBError::UnsupportedVersion(v)), + } + } + + pub fn get_all_recipes() { + + } +} - //let mut stmt = connection.sqlite_con..prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='versions'").unwrap(); - connection.sqlite_con.query_row( - "SELECT name FROM sqlite_master WHERE type='table' AND name='versions'", - rusqlite::NO_PARAMS, - |row| Ok(dbg!("test")) - ) - .unwrap(); +fn load_sql_file(version: u32) -> Result { + let sql_file = SQL_FILENAME.replace("{VERSION}", &version.to_string()); + let mut file = File::open(&sql_file).map_err(|err| DBError::Other(format!("Cannot open SQL file ({}): {}", &sql_file, err.to_string())))?; + let mut sql = String::new(); + file.read_to_string(&mut sql).map_err(|err| DBError::Other(format!("Cannot read SQL file ({}) : {}", &sql_file, err.to_string())))?; + Ok(sql) } \ No newline at end of file