diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index c9766d4..ac8ccac 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -79,6 +79,7 @@ mod test { } /// setting up test db and table, also adding arbitrary data inside fn mock_set_up(db_filename: &str) -> EquipementDatabase { + let _ = std::fs::remove_file(db_filename); let equip_db = EquipementDatabase::new(db_filename).unwrap(); equip_db.conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",()).unwrap(); equip_db diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 186cca4..5d4badf 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -8,9 +8,10 @@ use std::{path::Path, rc::Rc}; use more_fields::FieldsAsSlice; +use rusqlite::Connection; use serde::de::DeserializeOwned; -use crate::error::FatalEquipementError; +use crate::{error::FatalEquipementError, weaponry_structs::InitialEquipementList}; /// Trait representing a view table /// @@ -91,6 +92,21 @@ where /// Create a collection from a vector fn from_vectored(list: Vec) -> Self; + + /// Create a collection from an iterator of intermediate values + fn from_iter_intermediate( + iter_inter: impl Iterator>, + ) -> Result + where + Self: std::marker::Sized, + T: Into, + { + Ok(Self::from_vectored( + iter_inter + .map(|r| r.map(|eq_inter| Into::::into(eq_inter))) + .collect::, FatalEquipementError>>()?, + )) + } } /// Trait that ensure that two elements of a recipe are combinable, @@ -176,6 +192,11 @@ pub trait ToAnalysis { /// A generic database+connection, handling all the deserialization of the inner types pub trait RecipeDatabase { + /// The initial Deserialisation struct, SQL will be deserialized into this + type DeserialisationType: DeserializeOwned; + /// The used type that Deserialisation type will be converted into + type InnerType: TryFrom; + /// Create the database from a file fn new(origin: &str) -> Result where @@ -183,11 +204,17 @@ pub trait RecipeDatabase { /// Serialize a vector of objects of the given type in the specified table with an optional filter of the underlying database /// The FROM type is the original data, directly deserialized from the table + // TODO[:] : This element is partly responsible for the difficulty simplifying and generalizing deserialisation fn serialize_vec_from_table( &self, table: &str, filter: Option<&str>, - ) -> std::result::Result, FatalEquipementError>; + ) -> Result, crate::error::FatalEquipementError> { + crate::database::get_data(self.get_connection(), table, filter) + } + + /// Get a reference to the underlying database connection + fn get_connection(&self) -> &Connection; /// Initialize an empty database & table fn initialize_empty_table( @@ -197,6 +224,17 @@ pub trait RecipeDatabase { /// Insert a row inside the database, while mostly unused this function is needed to initialize the empty table with an empty row if needed fn insert_row(&self, row: T) -> Result<(), FatalEquipementError>; + + /// Serialize a request into an intermediate T representation, + /// T having all the implementation specifics of the part in details + /// eg. EqShape, EqPart etc.. + fn serialise_into_intermediate( + &self, + table: &str, + filter: Option<&str>, + ) -> Result> + '_, FatalEquipementError> + where + T: From; } /// Trait implemented by any struct aiming to be a public recipe @@ -233,12 +271,10 @@ pub trait Scenario { type FinalListType: RefinedList + ToTex + ToCSV + ToAnalysis; /// Inner configuration type Config; - - // /// The initial element List - // type InitialElementList: RecipeCollection; - - // /// The Inner Database struct to deserialize initially - // type InitialDatabaseStruct; + /// The initial equipement type, the database serialisation will be to be converted into this type + type InitialEquipementType; + /// The inner element that all serialised data will be serialized into after the intermediate step + type Recipe; /// Create a Scenario from a given config fn new_with_config(config: Self::Config) -> Result @@ -248,35 +284,19 @@ pub trait Scenario { /// Generate the final list type fn generate_refined_recipes(&self) -> Result; - // /// Blanket implementation deserialising all element from the database into the initial inner list used by the scenario - // fn inital_list_from_database( - // &self, - // extra_sql_filter: Option, - // ) -> Result - // where - // T: TryFrom + From + Into, - // { - // // TODO: This likely has too high a complexity and should either be a blanket implementation - // // : or require the inner workings to implement methods to easily allow this deserialisation - // Ok(Self::InitialElementList::from_vectored( - // self.get_database() - // .serialize_vec_from_table::( - // &self.get_tablename(), - // Some(&format!("META_CATEGORY LIKE '{}'", name)), - // )? - // .into_iter() - // .map(|v| { - // InnerEquipementStats::try_from(v) - // .map(|w| T::from(w)) - // .map(|v| v.into()) - // }) - // .collect::, FatalEquipementError>>()?, - // )) - // } - /// Retrieve a reference to the inner database fn get_database(&self) -> &Self::DatabaseType; /// Retrieve A config fn get_tablename(&self) -> &str; + + /// Automatically deserialize into an equipement + // TODO: Add to trait + // TODO: Add an optionnal initial filter ? + fn deserde_into_equipement( + &self, + filter: Option<&str>, + ) -> Result + where + T: From + Into; } diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index bc0dab3..27d2374 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -6,7 +6,7 @@ // use super::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}; -use crate::database::{generate_create_table_query, get_data}; +use crate::database::generate_create_table_query; use crate::error::FatalEquipementError; use crate::interfaces::{FixedRecipe, RecipeDatabase}; use rusqlite::Connection; @@ -24,14 +24,8 @@ pub struct EquipementDatabase { } impl RecipeDatabase for EquipementDatabase { - // TODO[:] : This element is partly responsible for the difficulty simplifying and generalizing deserialisation - fn serialize_vec_from_table( - &self, - table: &str, - filter: Option<&str>, - ) -> Result, crate::error::FatalEquipementError> { - get_data(&self.conn, table, filter) - } + type DeserialisationType = DatabaseEquipementStats; + type InnerType = InnerEquipementStats; /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. fn new(filename: &str) -> Result { @@ -55,6 +49,27 @@ impl RecipeDatabase for EquipementDatabase { let _ = row; todo!() } + + fn get_connection(&self) -> &Connection { + &self.conn + } + + fn serialise_into_intermediate( + &self, + table: &str, + filter: Option<&str>, + ) -> Result> + '_, FatalEquipementError> + where + T: From, + { + // Start with Self::DatabaseType + Ok(self + .serialize_vec_from_table::(table, filter)? + .into_iter() + .map(|db_element| { + Self::InnerType::try_from(db_element).map(|inner_eq| T::from(inner_eq)) + })) + } } #[allow(missing_docs)] pub struct EquipementFixedRecipe { diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index 561f38a..35aa891 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -34,6 +34,7 @@ impl Combinable for Equipement { impl RecipeCollection for InitialEquipementList { type Recipes = Equipement; + // Should likely be internal fn from_vectored(list: Vec) -> Self { Self { inner: list } } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index a9a40ed..90b6ad3 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -13,10 +13,7 @@ use crate::{ weaponry_structs::{ Equipement, InitialEquipementList, RefinedEquipementList, equipement_impl_database::EquipementDatabase, - equipement_structs::{ - DatabaseEquipementStats, EqFinishing, EqMaterial, EqNature, EqShape, - InnerEquipementStats, - }, + equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats}, }, }; @@ -58,70 +55,7 @@ pub struct IndividualElementsScenario { config: ConfigEquipementScenario, } -/// The initial equipement type, to be converted into post deserialisation -type InitialEquipementType = InnerEquipementStats; -/// The initial database typ -type InitialDatabaseType = DatabaseEquipementStats; - impl CrossRecipeScenario { - /// Automatically deserialize into an equipement - // TODO: Add to trait - // TODO: Add an optionnal initial filter ? - fn deserde_into_equipement( - &self, - sql_filter: Option<&str>, - ) -> Result - where - T: From + Into, // TryFrom + - { - // TODO: This likely has too high a complexity and should either be a blanket implementation - // : or require the inner workings to implement methods to easily allow this deserialisation - // : Most of this complexity comes from the fact that no clear definition of flow is given to - // : the whole implementation - // : Beside many struct "need" to know way too much of the inner workings of the other to funtion - // : A very long and tedious overhall is now needed - // : At the very least, The InitialEquipementList sould be able to initialize itself with only - // : the intermediate representation and nothing more - Ok(InitialEquipementList::from_vectored( - self.get_database() - .serialize_vec_from_table::(self.get_tablename(), sql_filter)? - .into_iter() - .map(|v| { - InnerEquipementStats::try_from(v) - .map(|w| T::from(w)) - .map(|v| v.into()) - }) - .collect::, FatalEquipementError>>()?, - )) - } - - // /// Automatically deserialize into an equipement - // fn better_deserde_into_equipement( - // &self, - // sql_filter: Option<&str>, - // ) -> Result - // where - // IntermediateType: From + Into, // TryFrom + - // { - // let mut items = self - // .get_database() - // .serialize_vec_from_table::(self.get_tablename(), sql_filter)? - // .into_iter(); - // InitialEquipementList::from_iter_with_intermediate::( - // &mut items, - // ); - // // Ok(InitialEquipementList::from_vectored( - // // items - // // .map(|v| { - // // InnerEquipementStats::try_from(v) - // // .map(|w| T::from(w)) - // // .map(|v| v.into()) - // // }) - // // .collect::, FatalEquipementError>>()?, - // // )) - // todo!() - // } - /// Generate all the operations to be processed with the current config // TODO: Defer this to a custom type in the config some sort of OperationSelector fn generate_selected_operation( @@ -161,11 +95,11 @@ impl CrossRecipeScenario { } impl Scenario for CrossRecipeScenario { - // TODO[3]: Could be skipped type DatabaseType = EquipementDatabase; type FinalListType = RefinedEquipementList; type Config = ConfigEquipementScenario; - // type InitialInnerList = InitialEquipementList; + type InitialEquipementType = InnerEquipementStats; + type Recipe = Equipement; fn new_with_config(config: Self::Config) -> Result where @@ -199,4 +133,20 @@ impl Scenario for CrossRecipeScenario { fn get_database(&self) -> &Self::DatabaseType { &self.database } + + /// Automatically deserialize into an equipement + // TODO: Add to trait + // TODO: Add an optionnal initial filter ? + fn deserde_into_equipement( + &self, + filter: Option<&str>, + ) -> Result + where + T: From<::InitialEquipementType> + Into, + { + RecipeCollection::from_iter_intermediate::( + self.get_database() + .serialise_into_intermediate::(self.get_tablename(), filter)?, + ) + } }