More work on standardisation and polymorphism

This commit is contained in:
Dandaedre 2025-02-28 19:07:25 +01:00
parent 01842fc64a
commit eaed13f320
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
5 changed files with 99 additions and 112 deletions

View File

@ -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

View File

@ -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::Recipes>) -> Self;
/// Create a collection from an iterator of intermediate values <T>
fn from_iter_intermediate<T>(
iter_inter: impl Iterator<Item = Result<T, FatalEquipementError>>,
) -> Result<Self, FatalEquipementError>
where
Self: std::marker::Sized,
T: Into<Self::Recipes>,
{
Ok(Self::from_vectored(
iter_inter
.map(|r| r.map(|eq_inter| Into::<Self::Recipes>::into(eq_inter)))
.collect::<Result<Vec<Self::Recipes>, 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<Self::DeserialisationType>;
/// Create the database from a file
fn new(origin: &str) -> Result<Self, FatalEquipementError>
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<FROM: DeserializeOwned + more_fields::FieldsAsSlice>(
&self,
table: &str,
filter: Option<&str>,
) -> std::result::Result<Vec<FROM>, FatalEquipementError>;
) -> Result<Vec<FROM>, 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<T: FieldsAsSlice>(
@ -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<T: DeserializeOwned>(&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<T>(
&self,
table: &str,
filter: Option<&str>,
) -> Result<impl Iterator<Item = Result<T, FatalEquipementError>> + '_, FatalEquipementError>
where
T: From<Self::InnerType>;
}
/// 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<Self, FatalEquipementError>
@ -248,35 +284,19 @@ pub trait Scenario {
/// Generate the final list type
fn generate_refined_recipes(&self) -> Result<Self::FinalListType, FatalEquipementError>;
// /// Blanket implementation deserialising all element from the database into the initial inner list used by the scenario
// fn inital_list_from_database<T>(
// &self,
// extra_sql_filter: Option<String>,
// ) -> Result<Self::FinalListType, FatalEquipementError>
// where
// T: TryFrom<InnerEquipementStats> + From<InnerEquipementStats> + Into<Equipement>,
// {
// // 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::InitialDatabaseStruct>(
// &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::<Result<Vec<_>, 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<T>(
&self,
filter: Option<&str>,
) -> Result<InitialEquipementList, FatalEquipementError>
where
T: From<Self::InitialEquipementType> + Into<Self::Recipe>;
}

View File

@ -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<T: DeserializeOwned + more_fields::FieldsAsSlice>(
&self,
table: &str,
filter: Option<&str>,
) -> Result<Vec<T>, 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<Self, FatalEquipementError> {
@ -55,6 +49,27 @@ impl RecipeDatabase for EquipementDatabase {
let _ = row;
todo!()
}
fn get_connection(&self) -> &Connection {
&self.conn
}
fn serialise_into_intermediate<T>(
&self,
table: &str,
filter: Option<&str>,
) -> Result<impl Iterator<Item = Result<T, FatalEquipementError>> + '_, FatalEquipementError>
where
T: From<Self::InnerType>,
{
// Start with Self::DatabaseType
Ok(self
.serialize_vec_from_table::<Self::DeserialisationType>(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 {

View File

@ -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::Recipes>) -> Self {
Self { inner: list }
}

View File

@ -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<T>(
&self,
sql_filter: Option<&str>,
) -> Result<InitialEquipementList, FatalEquipementError>
where
T: From<InitialEquipementType> + Into<Equipement>, // TryFrom<InitialEquipementType> +
{
// 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 <EqShape, etc> and nothing more
Ok(InitialEquipementList::from_vectored(
self.get_database()
.serialize_vec_from_table::<InitialDatabaseType>(self.get_tablename(), sql_filter)?
.into_iter()
.map(|v| {
InnerEquipementStats::try_from(v)
.map(|w| T::from(w))
.map(|v| v.into())
})
.collect::<Result<Vec<_>, FatalEquipementError>>()?,
))
}
// /// Automatically deserialize into an equipement
// fn better_deserde_into_equipement<IntermediateType>(
// &self,
// sql_filter: Option<&str>,
// ) -> Result<InitialEquipementList, FatalEquipementError>
// where
// IntermediateType: From<InitialEquipementType> + Into<Equipement>, // TryFrom<InitialEquipementType> +
// {
// let mut items = self
// .get_database()
// .serialize_vec_from_table::<InitialDatabaseType>(self.get_tablename(), sql_filter)?
// .into_iter();
// InitialEquipementList::from_iter_with_intermediate::<InitialDatabaseType, IntermediateType>(
// &mut items,
// );
// // Ok(InitialEquipementList::from_vectored(
// // items
// // .map(|v| {
// // InnerEquipementStats::try_from(v)
// // .map(|w| T::from(w))
// // .map(|v| v.into())
// // })
// // .collect::<Result<Vec<_>, 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<Self, FatalEquipementError>
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<T>(
&self,
filter: Option<&str>,
) -> Result<InitialEquipementList, FatalEquipementError>
where
T: From<<CrossRecipeScenario as Scenario>::InitialEquipementType> + Into<Equipement>,
{
RecipeCollection::from_iter_intermediate::<T>(
self.get_database()
.serialise_into_intermediate::<T>(self.get_tablename(), filter)?,
)
}
}