From c97425cb6f832af573d65fbd8f2750bcc46df16e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 19 Feb 2025 09:28:59 +0100 Subject: [PATCH] Implements a little of the needed database serde --- weaponry/Cargo.toml | 2 +- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/serde_loading.rs | 65 ++++++++-- weaponry/src/error.rs | 6 +- weaponry/src/interfaces.rs | 5 +- .../src/weaponry_structs/equipement_fields.rs | 36 +----- .../equipement_impl_database.rs | 41 +++++++ .../weaponry_structs/equipement_scenario.rs | 12 +- .../weaponry_structs/equipement_structs.rs | 115 +++++++++++++----- weaponry/src/weaponry_structs/mod.rs | 3 +- 10 files changed, 205 insertions(+), 80 deletions(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 184e041..915b59d 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -10,7 +10,7 @@ csv = "1.3.1" fastrand = "2.3.0" pretty_assertions = "1.4.1" probability = "0.20.3" -rusqlite = { version = "0.33.0", features = ["bundled"] } +rusqlite = { version = "0.33.0" } # , features = ["bundled"] serde = { version = "1.0.217", features = ["derive"] } serde_rusqlite = "0.37.0" serde_json = { version = "1.0.138", features = ["alloc"] } diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 9ddfd1985b8da960e01c8e1208ff646d29976378..f0862ffbb83007ef0f13f8c1e7db1b49184fdc40 100644 GIT binary patch delta 674 zcmZp8z}WDBae}m<0RsaAI}o!0F$)k|Ow=(33hIS>@$wijFmc~w;J(MZYGc7+ZpNyK zjozExVC4&9;J?pr$G?NW zjxPuVHwy~b@YP2&*2y#Q@^SzHBO{39FlPc&92~N;>KuZM9Nc-))k*P zoRL_Ns>kpnuQVqo4n%-(bS#KuIBDL<3=1tLh)$p$2ml+v$iZ;c6Rh+;s#YddeYi%5 z4xl4}zz~R`PG-2s@YdK~o&lx~Vk`&Pxga)J83)HE1r`AgM*epU{O|bh0^{%zzmNbU bvoaG>nqc_1$w6FzkqIdKkbm>fcy<8*6>gcv delta 178 zcmZp8z}WDBae}m<3("Eq_test") - .unwrap(); - let v = db.serialize_vec_from_table::("InnerStats", None); - db.conn - .execute( - "INSERT INTO example (id, name) VALUES (?,?)", - to_params(InnerEquipementStats::random_new()).unwrap(), - ) + let mut data_eg = DatabaseEquipementStats::random_new(); + // data_eg.id = fastrand::u8(1..u8::MAX); + // data_eg.damage_type = serde_json::to_string(&Some(DamageType(vec![DamageMod::Primary( + // PhysicalDamageType::Blunt, + // )]))) + // .unwrap(); + // data_eg.category = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap(); + // data_eg.target = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap(); + // data_eg.special = + // serde_json::to_string(&SpecialCategory(vec!["noo".to_string(), "boo".to_string()])) + // .unwrap(); + // data_eg.reload_cost = serde_json::to_string(&Some(12)).unwrap(); + data_eg.id = fastrand::u8(1..u8::MAX); + + db.initialize_empty_table::("Equipements") .unwrap(); + + let sql = &format!( + "INSERT INTO Equipements ({}) VALUES ({})", + DatabaseEquipementStats::attributes_slice() + .iter() + // .filter_map(|(k, _v)| (*k != "id").then_some(*k)) + .map(|(k, _v)| *k) + .collect::>() + .join(", "), + DatabaseEquipementStats::attributes_slice() + .iter() + // .filter_map(|(k, _v)| (*k != "id").then_some(":".to_string() + *k)) + .map(|(k, _v)| ":".to_string() + *k) + .collect::>() + .join(", ") + ); + println!("{}", sql); + let r = db.conn.execute( + sql, + to_params_named(&data_eg).unwrap().to_slice().as_slice(), + ); + println!("{:?}", r); + + let v = db.serialize_vec_from_table::("Equipements", None); + // println!("{:#?}", v); + + println!( + "{:#?}", + v.unwrap() + .into_iter() + .map(InnerEquipementStats::try_from) + .collect::>() + ); // let mut r = db.conn.prepare("SELECT * FROM InnerStats").unwrap(); // let mut v = r.query([]).unwrap(); // println!("{:?}:\n {:#?}", db, r); - - println!("{:?}", v); } diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index eb1471c..a410c4d 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -10,8 +10,12 @@ use thiserror::Error; pub enum FatalEquipementError { #[error("Rusqlite failed to connect to the given path {0}")] RusqliteConnection(#[from] rusqlite::Error), - #[error("Deserialization from object : {0}")] + + #[error("Deserialization from object failed : {0}")] SerdeRusqlite(#[from] serde_rusqlite::Error), + + #[error("Deserialisation from json failed : {0}")] + SerdeJSON(#[from] serde_json::Error), } #[derive(Error, Debug)] diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 8168595..a1d1ffc 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -165,11 +165,12 @@ pub trait RecipeDatabase { Self: std::marker::Sized; /// Serialize a vector of objects of the given type in the specified table with an optional filter of the underlying database - fn serialize_vec_from_table( + /// The FROM type is the original data, directly deserialized from the table + fn serialize_vec_from_table( &self, table: &str, filter: Option<&str>, - ) -> std::result::Result, FatalEquipementError>; + ) -> std::result::Result, FatalEquipementError>; /// Initialize an empty database & table fn initialize_empty_table( diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index b8a9904..af2ebe1 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -10,7 +10,8 @@ use strum::Display; #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only -pub struct SpecialCategory(pub(super) Vec); +// TODO: avoid pub make an impl ? +pub struct SpecialCategory(pub Vec); /// The kind of target this nature can apply to #[derive(Clone)] @@ -24,7 +25,7 @@ pub enum NatureTarget { } /// Enum of all different physical weapon damage types -#[allow(clippy::missing_docs_in_private_items)] +#[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] pub enum PhysicalDamageType { @@ -32,13 +33,6 @@ pub enum PhysicalDamageType { Slash, Pierce, } -impl From<&str> for PhysicalDamageType { - fn from(value: &str) -> Self { - let _ = value; - // Matchcase for all damage types - todo!() - } -} /// Weapon damage, combining the base weapon damage type and it's level /// @@ -52,21 +46,15 @@ pub enum DamageMod { Tertiary(PhysicalDamageType), } -impl From<&str> for DamageMod { - fn from(value: &str) -> Self { - let _ = value; - // Detect [] and recurse from - todo!() - } -} - /// Combined damage type, as a vector of all damage types /// /// Meant to be serialised to tex and deserialized directly from the table #[derive(Clone, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] -pub struct DamageType(pub(super) Vec); +// TODO: avoid pub make an impl ? +pub struct DamageType(pub Vec); +// TODO: Find a better way to make an easy creation at least for tests impl From<&str> for DamageType { fn from(value: &str) -> Self { let _ = value; @@ -109,18 +97,6 @@ pub enum WeaponCategory { Cannon, } -impl From<&str> for WeaponCategory { - fn from(value: &str) -> Self { - let _ = value; - todo!() - } -} - -// TODO: Consider this for test -// impl Equipement{ -// fn random_equipement(){} -// } - #[cfg(test)] mod test { // use super::*; diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 7b4aa33..26659fd 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -12,6 +12,8 @@ use crate::interfaces::RecipeDatabase; use rusqlite::Connection; use serde::de::DeserializeOwned; +use super::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; + /// Struct for database connection. #[derive(Debug)] pub struct EquipementDatabase { @@ -46,3 +48,42 @@ impl RecipeDatabase for EquipementDatabase { Ok(()) } } + +// #[allow(clippy::useless_conversion)] +impl TryFrom for InnerEquipementStats { + type Error = FatalEquipementError; + + fn try_from(value: DatabaseEquipementStats) -> Result { + Ok(Self { + id: vec![value.id], // Special case where manual is better than serde + name: vec![value.name], + rarity: value.rarity, // Generic case, into(), serde or cast are equivalent + cost: value.cost, + difficulty: value.difficulty, + tier: value.tier, + damage: value.damage, + p_damage: value.p_damage, + precision: value.precision, + rmax: value.rmax, + armor_break: value.armor_break, + armor_pierce: value.armor_pierce, + antimaterial: value.antimaterial, + damage_type: serde_json::from_str(&value.damage_type)?, // Serde and derive are godsent + protection: value.protection, + integrity: value.integrity, + torque_two_handed: value.torque_two_handed, + torque_one_handed: value.torque_one_handed, + dodge: value.dodge, + parry: value.parry, + speed: value.speed, + stealth: value.stealth, + category: serde_json::from_str(&value.category)?, + target: serde_json::from_str(&value.target)?, + special: serde_json::from_str(&value.special)?, + action_cost: value.action_cost, + reload_cost: serde_json::from_str(&value.reload_cost)?, + range: value.range, + agility_bonus: value.agility_bonus, + }) + } +} diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index af7098c..1d7f81e 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -11,7 +11,7 @@ use crate::weaponry_structs::Equipement; use crate::weaponry_structs::InitialEquipementList; -use crate::weaponry_structs::equipement_structs::InnerEquipementStats; +use crate::weaponry_structs::equipement_structs::DatabaseEquipementStats; use crate::{ error::{EquipementError, FatalEquipementError}, interfaces::{RecipeCollection, RecipeDatabase, Scenario, ViewTable}, @@ -72,15 +72,21 @@ pub struct CrossRecipeScenario { /// Automatically deserialize into an equipement // TODO: This macro only exists because no blanket implementation or function does this *relatively* easy step +// TODO: This place the place where all new impl and simplifications will be done macro_rules! deserde_into_equipement { ( $db:expr, $name:expr, $type:ident) => { InitialEquipementList::from_vectored( - $db.serialize_vec_from_table::( + $db.serialize_vec_from_table::( "Equipement", Some(&format!("CATEGORY == {}", $name)), )? .into_iter() - .map(|eq| $type { stats: eq }.into()) + .map(|eq| { + $type { + stats: eq.try_into().unwrap(), + } + .into() + }) .collect::>(), ) }; diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 5fc278a..0fd7c2d 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -54,7 +54,7 @@ impl FilterFunction { } /// The inner statistics of the equipement, used across all parts and final weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Default, FieldsAsSlice, Debug, Deserialize, Serialize)] +#[derive(Clone, Default, FieldsAsSlice, Debug)] #[cfg_attr(test, derive(PartialEq))] pub struct InnerEquipementStats { pub id: Vec, @@ -88,8 +88,12 @@ pub struct InnerEquipementStats { pub(super) agility_bonus: u8, } +// TODO: This implementation of default is painfull +// TODO: Have either an auto-macro implementation or a manual one +// TODO: This implementation is Quasi-redondant +// TODO: Have a way to limit code duplication #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Default, FieldsAsSlice, Debug, Deserialize, Serialize)] +#[derive(Clone, FieldsAsSlice, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] pub struct DatabaseEquipementStats { #[INTEGER] @@ -97,54 +101,91 @@ pub struct DatabaseEquipementStats { pub meta_category: String, pub name: String, #[INTEGER] - pub(super) rarity: u8, + pub rarity: u8, #[INTEGER] - pub(super) cost: u8, + pub cost: u8, #[INTEGER] - pub(super) difficulty: u8, + pub difficulty: u8, #[INTEGER] - pub(super) tier: u8, + pub tier: u8, #[INTEGER] - pub(super) damage: u8, + pub damage: u8, #[INTEGER] - pub(super) p_damage: u8, + pub p_damage: u8, #[INTEGER] - pub(super) precision: i8, + pub precision: i8, #[INTEGER] - pub(super) rmax: u8, + pub rmax: u8, #[INTEGER] - pub(super) armor_break: u8, + pub armor_break: u8, #[INTEGER] - pub(super) armor_pierce: u8, + pub armor_pierce: u8, #[INTEGER] - pub(super) antimaterial: u8, - pub(super) damage_type: String, + pub antimaterial: u8, + pub damage_type: String, #[INTEGER] - pub(super) protection: u8, + pub protection: u8, #[INTEGER] - pub(super) integrity: u8, + pub integrity: u8, #[INTEGER] - pub(super) torque_two_handed: u8, + pub torque_two_handed: u8, #[INTEGER] - pub(super) torque_one_handed: u8, + pub torque_one_handed: u8, #[INTEGER] - pub(super) dodge: u8, + pub dodge: u8, #[INTEGER] - pub(super) parry: u8, + pub parry: u8, #[INTEGER] - pub(super) speed: u8, + pub speed: u8, #[INTEGER] - pub(super) stealth: u8, - pub(super) category: String, - pub(super) target: String, - pub(super) special: String, + pub stealth: u8, + pub category: String, + pub target: String, + pub special: String, #[INTEGER] - pub(super) action_cost: u8, - pub(super) reload_cost: String, + pub action_cost: u8, + pub reload_cost: String, #[INTEGER] - pub(super) range: u8, + pub range: u8, #[INTEGER] - pub(super) agility_bonus: u8, + pub agility_bonus: u8, +} + +impl Default for DatabaseEquipementStats { + fn default() -> Self { + Self { + id: 0, + meta_category: "EqShape".to_string(), + name: String::new(), + damage_type: serde_json::to_string(&None::).unwrap(), + category: serde_json::to_string(&None::).unwrap(), + target: serde_json::to_string(&None::).unwrap(), + special: serde_json::to_string(&SpecialCategory::default()).unwrap(), + reload_cost: serde_json::to_string(&None::).unwrap(), + rarity: 0, + cost: 0, + difficulty: 0, + tier: 0, + damage: 0, + p_damage: 0, + precision: 0, + rmax: 0, + armor_break: 0, + armor_pierce: 0, + antimaterial: 0, + protection: 0, + integrity: 0, + torque_two_handed: 0, + torque_one_handed: 0, + dodge: 0, + parry: 0, + speed: 0, + stealth: 0, + range: 0, + agility_bonus: 0, + action_cost: 0, + } + } } #[allow(dead_code)] @@ -152,7 +193,7 @@ pub struct DatabaseEquipementStats { #[doc(hidden)] macro_rules! r { () => { - fastrand::u8(1..10) + fastrand::u8(1..u8::MAX) }; } // TODO: Make this a test requirement or hide it behind a profile @@ -169,6 +210,20 @@ impl InnerEquipementStats { } } } +// TODO: Make this a test requirement or hide it behind a profile +impl DatabaseEquipementStats { + /// Testing function to fuzz data + pub fn random_new() -> Self { + Self { + id: r!(), + range: r!(), + damage: r!(), + p_damage: r!(), + protection: r!(), + ..Default::default() + } + } +} /// Shape of the equipement, first mandatory part of an equipement #[derive(Default)] diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index dfdbad8..d9203c8 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -32,5 +32,6 @@ mod equipement_views; pub use equipement_structs::{Equipement, InitialEquipementList}; // All generic fields -#[allow(unused_imports)] +// #[allow(unused_imports)] +pub use equipement_fields::PhysicalDamageType; pub use equipement_fields::{DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory};