-use std::path::Path;\r
-use std::fs;\r
+use std::{fmt::Display, fs::{self, File}, path::Path, io::Read};\r
\r
-//use rusqlite::types::ToSql;\r
-//use rusqlite::{Connection, Result, NO_PARAMS};\r
+use itertools::Itertools;\r
+use chrono::{prelude::*, Duration};\r
+use rusqlite::{params, Params, OptionalExtension};\r
+use r2d2::Pool;\r
+use r2d2_sqlite::SqliteConnectionManager;\r
+use rand::distributions::{Alphanumeric, DistString};\r
+\r
+use crate::consts;\r
+use crate::hash::hash;\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
+// TODO: Is there a better solution?\r
+impl DBError {\r
+ fn from_dyn_error(error: Box<dyn std::error::Error>) -> Self {\r
+ DBError::Other(error.to_string())\r
+ }\r
+}\r
+\r
+type Result<T> = std::result::Result<T, DBError>;\r
+\r
+#[derive(Debug)]\r
+pub enum SignUpResult {\r
+ UserAlreadyExists,\r
+ UserCreatedWaitingForValidation(String), // Validation token.\r
+}\r
+\r
+#[derive(Debug)]\r
+pub enum ValidationResult {\r
+ ValidationExpired,\r
+ OK,\r
+}\r
+\r
+#[derive(Debug)]\r
+pub enum SignInResult {\r
+ NotValidToken,\r
+ OK,\r
+}\r
+\r
+#[derive(Debug)]\r
+pub enum AuthenticationResult {\r
+ NotValidToken,\r
+ OK,\r
+}\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
+ let path = Path::new(consts::DB_DIRECTORY).join(consts::DB_FILENAME);\r
+ Self::new_from_file(path)\r
+ }\r
\r
- // TODO: use a constant in consts module.\r
- let data_dir = Path::new("data");\r
+ pub fn new_in_memory() -> Result<Connection> {\r
+ Self::create_connection(SqliteConnectionManager::memory())\r
+ }\r
\r
- if !data_dir.exists() {\r
- fs::DirBuilder::new().create(data_dir).unwrap();\r
+ pub fn new_from_file<P: AsRef<Path>>(file: P) -> Result<Connection> {\r
+ if let Some(data_dir) = file.as_ref().parent() {\r
+ if !data_dir.exists() {\r
+ fs::DirBuilder::new().create(data_dir).unwrap();\r
+ }\r
}\r
\r
- Connection { con: rusqlite::Connection::open(data_dir.join("recipes.sqlite")).unwrap() }\r
+ Self::create_connection(SqliteConnectionManager::file(file))\r
}\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
-\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
+ 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
- pub fn get_all_recipes() {\r
+ fn create_connection(manager: SqliteConnectionManager) -> Result<Connection> {;\r
+ let pool = r2d2::Pool::new(manager).unwrap();\r
+ let connection = Connection { pool };\r
+ connection.create_or_update()?;\r
+ Ok(connection)\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
+ let sql_file = consts::SQL_FILENAME.replace("{VERSION}", &next_version.to_string());\r
+ tx.execute_batch(&load_sql_file(&sql_file)?)?;\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
-}
\ No newline at end of file
+\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
+ /* Not used for the moment.\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
+ pub fn sign_up(&self, password: &str, email: &str) -> Result<SignUpResult> {\r
+ self.sign_up_with_given_time(password, email, Utc::now())\r
+ }\r
+\r
+ fn sign_up_with_given_time(&self, password: &str, email: &str, datetime: DateTime<Utc>) -> Result<SignUpResult> {\r
+ let mut con = self.pool.get()?;\r
+ let tx = con.transaction()?;\r
+ let token =\r
+ match tx.query_row("SELECT [id], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| {\r
+ Ok((r.get::<&str, i32>("id")?, r.get::<&str, Option<String>>("validation_token")?))\r
+ }).optional()? {\r
+ Some((id, validation_token)) => {\r
+ if validation_token.is_none() {\r
+ return Ok(SignUpResult::UserAlreadyExists)\r
+ }\r
+ let token = generate_token();\r
+ let hashed_password = hash(password).map_err(|e| DBError::from_dyn_error(e))?;\r
+ tx.execute("UPDATE [User] SET [validation_token] = ?2, [creation_datetime] = ?3, [password] = ?4 WHERE [id] = ?1", params![id, token, datetime, hashed_password])?;\r
+ token\r
+ },\r
+ None => {\r
+ let token = generate_token();\r
+ let hashed_password = hash(password).map_err(|e| DBError::from_dyn_error(e))?;\r
+ tx.execute("INSERT INTO [User] ([email], [validation_token], [creation_datetime], [password]) VALUES (?1, ?2, ?3, ?4)", params![email, token, datetime, hashed_password])?;\r
+ token\r
+ },\r
+ };\r
+ tx.commit()?;\r
+ Ok(SignUpResult::UserCreatedWaitingForValidation(token))\r
+ }\r
+\r
+ pub fn validation(&self, token: &str, validation_time: Duration) -> Result<ValidationResult> {\r
+ todo!()\r
+ }\r
+\r
+ pub fn sign_in(&self, password: &str, email: String) -> Result<SignInResult> {\r
+ todo!()\r
+ }\r
+\r
+ pub fn authentication(&self, token: &str) -> Result<AuthenticationResult> {\r
+ todo!()\r
+ }\r
+\r
+ pub fn logout(&self, token: &str) -> Result<()> {\r
+ todo!()\r
+ }\r
+\r
+ /// Execute a given SQL file.\r
+ pub fn execute_file<P: AsRef<Path> + Display>(&self, file: P) -> Result<()> {\r
+ let con = self.pool.get()?;\r
+ let sql = load_sql_file(file)?;\r
+ con.execute_batch(&sql).map_err(DBError::from)\r
+ }\r
+\r
+ /// Execute any SQL statement.\r
+ /// Mainly used for testing.\r
+ pub fn execute_sql<P: Params>(&self, sql: &str, params: P) -> Result<usize> {\r
+ let con = self.pool.get()?;\r
+ con.execute(sql, params).map_err(DBError::from)\r
+ }\r
+}\r
+\r
+fn load_sql_file<P: AsRef<Path> + Display>(sql_file: P) -> Result<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
+}\r
+\r
+fn generate_token() -> String {\r
+ Alphanumeric.sample_string(&mut rand::thread_rng(), 24)\r
+}\r
+\r
+#[cfg(test)]\r
+mod tests {\r
+ use super::*;\r
+\r
+ #[test]\r
+ fn sign_up() -> Result<()> {\r
+ let connection = Connection::new_in_memory()?;\r
+ match connection.sign_up("12345", "paul@test.org")? {\r
+ SignUpResult::UserCreatedWaitingForValidation(_) => (), // Nominal case.\r
+ other => panic!("{:?}", other),\r
+ }\r
+ Ok(())\r
+ }\r
+\r
+ #[test]\r
+ fn sign_up_to_an_already_existing_user() -> Result<()> {\r
+ let connection = Connection::new_in_memory()?;\r
+ connection.execute_sql("\r
+ INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token])\r
+ VALUES (\r
+ 1,\r
+ 'paul@test.org',\r
+ 'paul',\r
+ '$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY',\r
+ 0,\r
+ NULL\r
+ );", [])?;\r
+ match connection.sign_up("12345", "paul@test.org")? {\r
+ SignUpResult::UserAlreadyExists => (), // Nominal case.\r
+ other => panic!("{:?}", other),\r
+ }\r
+ Ok(())\r
+ }\r
+\r
+ #[test]\r
+ fn sign_up_to_an_unvalidated_already_existing_user() -> Result<()> {\r
+ todo!()\r
+ }\r
+\r
+ fn sign_up_then_send_validation_at_time() -> Result<()> {\r
+ todo!()\r
+ }\r
+\r
+ fn sign_up_then_send_validation_too_late() -> Result<()> {\r
+ todo!()\r
+ }\r
+\r
+ //fn sign_up_then_send_validation_then_sign_in()\r
+}\r