Add an error management in db module
[recipes.git] / backend / src / db.rs
index 0002b41..ac97f1b 100644 (file)
@@ -1,6 +1,142 @@
+use std::path::Path;\r
+use std::fs;\r
 \r
+//use rusqlite::types::ToSql;\r
+//use rusqlite::{Connection, Result, NO_PARAMS};\r
 \r
+//extern crate r2d2;\r
+//extern crate r2d2_sqlite;\r
+//extern crate rusqlite;\r
 \r
-fn create_or_update() {\r
+use r2d2_sqlite::SqliteConnectionManager;\r
+use r2d2::Pool;\r
 \r
+#[derive(Debug)]\r
+pub enum DbError {\r
+    SqliteError(rusqlite::Error),\r
+    R2d2Error(r2d2::Error),\r
+    UnsupportedVersion(i32),\r
+}\r
+\r
+use super::consts;\r
+\r
+const CURRENT_DB_VERSION: u32 = 1;\r
+\r
+pub struct Connection {\r
+    //con: rusqlite::Connection\r
+    pool: Pool<SqliteConnectionManager>\r
+}\r
+\r
+pub struct Recipe {\r
+    pub title: String,\r
+    pub id: i32,\r
+}\r
+\r
+impl std::convert::From<rusqlite::Error> for DbError  {\r
+    fn from(error: rusqlite::Error) -> Self {\r
+        DbError::SqliteError(error)\r
+    }\r
+}\r
+\r
+impl std::convert::From<r2d2::Error> for DbError  {\r
+    fn from(error: r2d2::Error) -> Self {\r
+        DbError::R2d2Error(error)\r
+    }\r
+}\r
+\r
+impl Connection {\r
+    pub fn new() -> Result<Connection, DbError> {\r
+\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
+        let manager = SqliteConnectionManager::file("file.db");\r
+        let pool = r2d2::Pool::new(manager).unwrap();\r
+\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: &Self) -> Result<(), DbError> {\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
+\r
+        // Check the Database version.\r
+        let mut con = self.pool.get()?;\r
+        let tx = con.transaction()?;\r
+\r
+        let mut version = {\r
+            match tx.query_row(\r
+                    "SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'",\r
+                        rusqlite::NO_PARAMS,\r
+                        |row| row.get::<usize, String>(0)\r
+                    ) {\r
+                Ok(_) => tx.query_row("SELECT [version] FROM [Version]", rusqlite::NO_PARAMS, |row| row.get(0)).unwrap_or_default(),\r
+                Err(_) => 0\r
+            }\r
+        };\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(version: i32, tx: &rusqlite::Transaction) -> Result<bool, DbError> {\r
+        match version {\r
+            0 => {\r
+                println!("Update to version 1...");\r
+\r
+                // Initial structure.\r
+                tx.execute_batch(\r
+                    "\r
+                    CREATE TABLE [Version] (\r
+                        [id] INTEGER PRIMARY KEY,\r
+                        [version] INTEGER NOT NULL UNIQUE,\r
+                        [datetime] INTEGER DATETIME\r
+                    );\r
+\r
+                    CREATE TABLE [Recipe] (\r
+                        [id] INTEGER PRIMARY KEY,\r
+                        [title] INTEGER NOT NULL,\r
+                        [description] INTEGER DATETIME\r
+                    );\r
+                    "\r
+                )?;\r
+\r
+                /*\r
+                tx.execute(\r
+                    "\r
+                    INSERT INTO Version\r
+                    ",\r
+                    rusqlite::NO_PARAMS\r
+                );*/\r
+\r
+                Ok(true)\r
+            }\r
+\r
+            // Current version.\r
+            1 =>\r
+                Ok(false),\r
+\r
+            v =>\r
+                Err(DbError::UnsupportedVersion(v)),\r
+        }\r
+    }\r
+\r
+    pub fn get_all_recipes() {\r
+\r
+    }\r
 }
\ No newline at end of file