From 862021e0b27c095013e0762f34d9ba23adb72c10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Mon, 17 Feb 2025 19:35:35 +0100 Subject: [PATCH] refactor database.rs into struct and impl --- weaponry/src/database.rs | 98 ++++++++++++------- weaponry/src/error.rs | 4 +- weaponry/src/interfaces.rs | 4 +- .../weaponry_structs/equipement_scenario.rs | 6 +- 4 files changed, 69 insertions(+), 43 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 0a3c366..ded6b6a 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -5,38 +5,65 @@ //! Should dump whole database in a vec of structs from weaponry_structs #![allow(dead_code)] -//use crate::weaponry_structs::equipement_structs::InnerEquipementStats; -use rusqlite::{self, Connection, Result}; +use crate::{error::FatalEquipementError, interfaces::RecipeDatabase}; +use rusqlite::{self, Connection}; use serde::de::DeserializeOwned; -use serde_rusqlite::*; + +/// Struct for database connection. +pub struct EquipementDatabase { + /// Connection parameter for rusqlite + pub conn: rusqlite::Connection, +} + +impl EquipementDatabase { + /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. + fn new(filename: Option) -> Result { + Ok(Self { + conn: filename.map_or_else(Connection::open_in_memory, Connection::open)?, + }) + } + + /// Public function to get data from db. Returns the result as a vec with structs + pub fn get_data_from_fields( + &self, + fields: &[&str], + table_name: &str, + ) -> Result, serde_rusqlite::Error> + where + T: DeserializeOwned, + { + let gen_query = { + let fields = fields; + let table_name = table_name; + format!("SELECT {} FROM {};", fields.join(", "), table_name) + }; + let mut query_result = self.conn.prepare(&gen_query)?; + let res = serde_rusqlite::from_rows::(query_result.query([])?) + .filter_map(|s| s.ok()) + .collect(); + Ok(res) + } +} + +impl RecipeDatabase for EquipementDatabase { + fn serialize_vec_from_table(table: &str) -> Result, crate::error::EquipementError> { + todo!() + } + + fn serialize_vec_from_table_with_query( + table: &str, + query: &str, + ) -> Result, crate::error::EquipementError> { + todo!() + } +} /// Generate a SELECT query with fields generated from a struct. Returns a String +#[inline] fn generate_query(fields: &[&str], table_name: &str) -> String { format!("SELECT {} FROM {};", fields.join(", "), table_name) } -/// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. -fn initialize_database_conn(filename: Option) -> Result { - filename.map_or_else(Connection::open_in_memory, Connection::open) -} - -/// Public function to get data from db -pub fn get_data_from_fields( - db_conn: rusqlite::Connection, - fields: &[&str], - table_name: &str, -) -> Result> -where - T: DeserializeOwned, -{ - let gen_query = generate_query(fields, table_name); - let mut query_result = db_conn.prepare(&gen_query)?; - let res = from_rows::(query_result.query([])?) - .filter_map(|s| s.ok()) - .collect(); - Ok(res) -} - #[cfg(test)] mod test { use super::*; @@ -50,14 +77,14 @@ mod test { name: String, } - fn set_up() -> Result { - let conn = initialize_database_conn(None)?; - conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",())?; - conn.execute( + fn set_up() -> Result { + let equip_db = EquipementDatabase::new(None)?; + equip_db.conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",())?; + equip_db.conn.execute( "INSERT INTO TestStruct (id, name) VALUES (1, 'dupont'), (2, 'durand');", (), )?; - Ok(conn) + Ok(equip_db) } #[test] @@ -83,13 +110,10 @@ mod test { #[ignore] #[test] fn test_get_data() { - let _conn = set_up().unwrap(); - let result = get_data_from_fields::( - _conn, - &TestStruct::FIELD_NAMES_AS_ARRAY, - "TestStruct", - ) - .unwrap(); + let conn = set_up().unwrap(); + let result = conn + .get_data_from_fields::(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct") + .unwrap(); println!("{:?}", result); assert!(result.is_empty()) } diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index 3d85c1e..03a749e 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -8,8 +8,8 @@ use thiserror::Error; #[derive(Error, Debug)] /// Unrecoverable Error, all these error cannot gracefully fail and must return to the User for further handling pub enum FatalEquipementError { - #[error("Unkown error has errored")] - Unknown, + #[error("Rusqlite Error")] + RusqliteConnection(#[from] rusqlite::Error), } #[derive(Error, Debug)] diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 58e512a..c02bbf2 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -157,13 +157,13 @@ pub trait DbSerializable { /// A generic database+connection, handling all the deserialization of the inner types pub trait RecipeDatabase { /// Serialize a vector of objects of the given type in the specified table of the underlying database - fn serialize_vec_from_table(table: &str) -> Result; + fn serialize_vec_from_table(table: &str) -> std::result::Result, EquipementError>; /// Serialize a specified vector of objects of the given type with an additionnal restriction fn serialize_vec_from_table_with_query( table: &str, query: &str, - ) -> Result; + ) -> std::result::Result, EquipementError>; } /// Trait implemented by any struct aiming to be a public recipe diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index da91630..3f107fd 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -16,7 +16,9 @@ use super::equipement_advanced_repr::RefinedEquipementList; /// Mock of the existing database pub struct DatabaseMock {} impl RecipeDatabase for DatabaseMock { - fn serialize_vec_from_table(table: &str) -> Result { + fn serialize_vec_from_table( + table: &str, + ) -> std::result::Result, crate::error::EquipementError> { let _ = table; todo!() } @@ -24,7 +26,7 @@ impl RecipeDatabase for DatabaseMock { fn serialize_vec_from_table_with_query( table: &str, query: &str, - ) -> Result { + ) -> std::result::Result, crate::error::EquipementError> { let _ = table; let _ = query; todo!()