Add some data access methods to Connection
[recipes.git] / backend / src / db.rs
index 6458c7e..2bf383b 100644 (file)
-use std::path::Path;\r
-use std::fs;\r
+use std::{fs::{self, File}, path::Path, io::Read};\r
 \r
+use itertools::Itertools;\r
 //use rusqlite::types::ToSql;\r
 //use rusqlite::{Connection, Result, NO_PARAMS};\r
+use r2d2::Pool;\r
+use r2d2_sqlite::SqliteConnectionManager;\r
+\r
+use crate::consts;\r
+use crate::model;\r
 \r
 const CURRENT_DB_VERSION: u32 = 1;\r
 \r
+#[derive(Debug)]\r
+pub enum DBError {\r
+    SqliteError(rusqlite::Error),\r
+    R2d2Error(r2d2::Error),\r
+    UnsupportedVersion(u32),\r
+    Other(String),\r
+}\r
+\r
+impl From<rusqlite::Error> for DBError  {\r
+    fn from(error: rusqlite::Error) -> Self {\r
+        DBError::SqliteError(error)\r
+    }\r
+}\r
+\r
+impl From<r2d2::Error> for DBError  {\r
+    fn from(error: r2d2::Error) -> Self {\r
+        DBError::R2d2Error(error)\r
+    }\r
+}\r
+\r
+type Result<T> = std::result::Result<T, DBError>;\r
+\r
+#[derive(Clone)]\r
 pub struct Connection {\r
-    con: rusqlite::Connection\r
+    //con: rusqlite::Connection\r
+    pool: Pool<SqliteConnectionManager>\r
 }\r
 \r
 impl Connection {\r
-    pub fn new() -> Connection {\r
+    pub fn new() -> Result<Connection> {\r
 \r
-        // TODO: use a constant in consts module.\r
-        let data_dir = Path::new("data");\r
+        let data_dir = Path::new(consts::DB_DIRECTORY);\r
 \r
         if !data_dir.exists() {\r
             fs::DirBuilder::new().create(data_dir).unwrap();\r
         }\r
 \r
-        Connection { con: rusqlite::Connection::open(data_dir.join("recipes.sqlite")).unwrap() }\r
-    }\r
+        let manager = SqliteConnectionManager::file(consts::DB_FILENAME);\r
+        let pool = r2d2::Pool::new(manager).unwrap();\r
 \r
-    pub fn create_or_update(self: &Self) -> rusqlite::Result<&str> {\r
-        //let connection = Connection::new();\r
-        // let mut stmt = connection.sqlite_con.prepare("SELECT * FROM versions ORDER BY date").unwrap();\r
-        // let mut stmt = connection.sqlite_con..prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='versions'").unwrap();\r
+        let connection = Connection { pool };\r
+        connection.create_or_update()?;\r
+        Ok(connection)\r
+    }\r
 \r
+    /*\r
+     * Called after the connection has been established for creating or updating the database.\r
+     * The 'Version' table tracks the current state of the database.\r
+     */\r
+    fn create_or_update(&self) -> Result<()> {\r
         // Check the Database version.\r
-        let version = {\r
-            let stmt_version_table = self.con.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='versions'")?;\r
-            /*if stmt_version_table.query(rusqlite::NO_PARAMS)?.count() == 0 {\r
-                0\r
-            } else {\r
-                1 // let stmt_versions = self.con.prepare("SELECT number FROM [")\r
-            }*/\r
-            0\r
+        let mut con = self.pool.get()?;\r
+        let tx = con.transaction()?;\r
+\r
+        // Version 0 corresponds to an empty database.\r
+        let mut version = {\r
+            match tx.query_row(\r
+                    "SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'",\r
+                        [],\r
+                        |row| row.get::<usize, String>(0)\r
+                    ) {\r
+                Ok(_) => tx.query_row("SELECT [version] FROM [Version] ORDER BY [id] DESC", [], |row| row.get(0)).unwrap_or_default(),\r
+                Err(_) => 0\r
+            }\r
         };\r
 \r
-        self.con.query_row(\r
-            "SELECT name FROM sqlite_master WHERE type='table' AND name='versions'",\r
-            rusqlite::NO_PARAMS,\r
-            |row| Ok(dbg!("test"))\r
-        )\r
+        while Connection::update_to_next_version(version, &tx)? {\r
+            version += 1;\r
+        }\r
+\r
+        tx.commit()?;\r
+\r
+        Ok(())\r
     }\r
+\r
+    fn update_to_next_version(current_version: u32, tx: &rusqlite::Transaction) -> Result<bool> {\r
+        let next_version = current_version + 1;\r
+\r
+        if next_version <= CURRENT_DB_VERSION {\r
+            println!("Update to version {}...", next_version);\r
+        }\r
+\r
+        fn update_version(to_version: u32, tx: &rusqlite::Transaction) -> Result<()> {\r
+            tx.execute("INSERT INTO [Version] ([version], [datetime]) VALUES (?1, datetime('now'))", [to_version]).map(|_| ()).map_err(DBError::from)\r
+        }\r
+\r
+        fn ok(updated: bool) -> Result<bool> {\r
+            if updated {\r
+                println!("Version updated");\r
+            }\r
+            Ok(updated)\r
+        }\r
+\r
+        match next_version {\r
+            1 => {\r
+                tx.execute_batch(&load_sql_file(next_version)?)?;\r
+                update_version(next_version, tx)?;\r
+\r
+                ok(true)\r
+            }\r
+\r
+            // Version 1 doesn't exist yet.\r
+            2 =>\r
+                ok(false),\r
+\r
+            v =>\r
+                Err(DBError::UnsupportedVersion(v)),\r
+        }\r
+    }\r
+\r
+    pub fn get_all_recipe_titles(&self) -> Result<Vec<(i32, String)>> {\r
+        let con = self.pool.get()?;\r
+        let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?;\r
+        let titles =\r
+            stmt.query_map([], |row| {\r
+                Ok((row.get(0)?, row.get(1)?))\r
+            })?.map(|r| r.unwrap()).collect_vec(); // TODO: remove unwrap.\r
+        Ok(titles)\r
+    }\r
+\r
+    pub fn get_all_recipes(&self) -> Result<Vec<model::Recipe>> {\r
+        let con = self.pool.get()?;\r
+        let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?;\r
+        let recipes =\r
+            stmt.query_map([], |row| {\r
+                Ok(model::Recipe::new(row.get(0)?, row.get(1)?))\r
+            })?.map(|r| r.unwrap()).collect_vec(); // TODO: remove unwrap.\r
+        Ok(recipes)\r
+    }\r
+\r
+    pub fn get_recipe(&self, id: i32) -> Result<model::Recipe> {\r
+        let con = self.pool.get()?;\r
+        con.query_row("SELECT [id], [title] FROM [Recipe] WHERE [id] = ?1", [id], |row| {\r
+            Ok(model::Recipe::new(row.get(0)?, row.get(1)?))\r
+        }).map_err(DBError::from)\r
+    }\r
+}\r
+\r
+fn load_sql_file(version: u32) -> Result<String> {\r
+    let sql_file = consts::SQL_FILENAME.replace("{VERSION}", &version.to_string());\r
+    let mut file = File::open(&sql_file).map_err(|err| DBError::Other(format!("Cannot open SQL file ({}): {}", &sql_file, err.to_string())))?;\r
+    let mut sql = String::new();\r
+    file.read_to_string(&mut sql).map_err(|err| DBError::Other(format!("Cannot read SQL file ({}) : {}", &sql_file, err.to_string())))?;\r
+    Ok(sql)\r
 }
\ No newline at end of file