166 lines
5.8 KiB
Rust
166 lines
5.8 KiB
Rust
#![allow(dead_code)]
|
|
|
|
use crate::monster_structs::{
|
|
self, CreatureReward, MonsterAllAttacks, MonsterRepetableInitRow, PlayerBalancing,
|
|
};
|
|
use crate::monster_structs::{
|
|
CreatureBodyPart, CreatureData, CreatureListAttacks, CreatureStats, FullMonster,
|
|
MonsterSingleAttack,
|
|
};
|
|
use anyhow::{Context, anyhow};
|
|
use cli_parser::Config;
|
|
use more_fields::FieldsAsSlice;
|
|
use rusqlite::Connection;
|
|
use serde::de::DeserializeOwned;
|
|
|
|
/// Deserialise a table row (or rows) into the given type and add a nice context message.
|
|
macro_rules! fetch_from {
|
|
($ty:ty, $connection:expr,$name:expr, $table:expr, $cols_opt:expr) => {{
|
|
// `connection` and `creature.name` must be in scope when the macro is expanded
|
|
generic_deserialize::<$ty>(
|
|
&$connection,
|
|
$table,
|
|
Some(&format!("creature_id={}", $name.id)),
|
|
$cols_opt,
|
|
)
|
|
.context(format!("Fetching {} from {}", $table, $name.name))?
|
|
}};
|
|
}
|
|
|
|
/// Fetch all data from the database
|
|
pub(crate) fn fetch_all_creature_data(
|
|
connection: &Connection,
|
|
config: &Config,
|
|
filter: Option<&str>,
|
|
) -> Result<Vec<FullMonster>, anyhow::Error> {
|
|
let list_creatures =
|
|
generic_deserialize::<CreatureData>(connection, "creature", filter, Some("id"))?;
|
|
let mut finished_creatures = Vec::new();
|
|
for creature in list_creatures.iter() {
|
|
// println!("Working on {}@{}", creature.id, creature.name);
|
|
let creature_stats: CreatureStats =
|
|
fetch_one_field(connection, creature, "creature_stats")?;
|
|
finished_creatures.push(FullMonster {
|
|
id: creature.id,
|
|
name: creature.name.clone(),
|
|
init_full: MonsterRepetableInitRow::vec_from(
|
|
&creature_stats.p1_init,
|
|
&creature_stats.p2_init,
|
|
&creature_stats.p1_actions,
|
|
&creature_stats.p2_actions,
|
|
),
|
|
stats: creature_stats, // fetch_one_field(connection, creature, "creature_stats")?,
|
|
all_attacks: MonsterAllAttacks::from_retrieved_data(
|
|
&fetch_from!(
|
|
MonsterSingleAttack,
|
|
connection,
|
|
creature,
|
|
"creature_abilities",
|
|
Some("phase, attack_group, ordering")
|
|
),
|
|
config,
|
|
),
|
|
attacks: CreatureListAttacks {
|
|
attacks: fetch_from!(
|
|
MonsterSingleAttack,
|
|
connection,
|
|
creature,
|
|
"creature_abilities",
|
|
Some("phase, attack_group, ordering")
|
|
),
|
|
},
|
|
body_parts: monster_structs::CreatureListBodyParts {
|
|
body_parts: fetch_from!(
|
|
CreatureBodyPart,
|
|
connection,
|
|
creature,
|
|
"creature_body_parts",
|
|
None
|
|
),
|
|
},
|
|
rewards: monster_structs::CreatureListRewards {
|
|
rewards: fetch_from!(
|
|
CreatureReward,
|
|
connection,
|
|
creature,
|
|
"creature_rewards",
|
|
None
|
|
),
|
|
},
|
|
balancing: fetch_one_field(connection, creature, "creature_balancing")?,
|
|
data: creature.clone(),
|
|
});
|
|
}
|
|
Ok(finished_creatures)
|
|
}
|
|
|
|
pub(crate) fn fetch_all_player_data(
|
|
connection: &Connection,
|
|
config: &Config,
|
|
) -> Result<Vec<PlayerBalancing>, anyhow::Error> {
|
|
let _ = config;
|
|
generic_deserialize::<PlayerBalancing>(connection, "player_balancing", None, None)
|
|
}
|
|
|
|
/// Fetches **the single** row that matches `creature` from the given `table_name`.
|
|
///
|
|
/// The query is performed through the `fetch_from!` macro, which returns a vector of
|
|
/// values deserialised into `T`. If the resulting vector does not contain exactly
|
|
/// one element an error is returned; otherwise the sole value is extracted.
|
|
fn fetch_one_field<T: DeserializeOwned + FieldsAsSlice>(
|
|
connection: &Connection,
|
|
creature: &CreatureData,
|
|
table_name: &str,
|
|
) -> Result<T, anyhow::Error> {
|
|
let mut creature_stats = fetch_from!(T, connection, creature, table_name, None);
|
|
if creature_stats.len() != 1 {
|
|
return Err(anyhow!(
|
|
"The number of {} entries for the creature {} should be exactly one found {}",
|
|
table_name,
|
|
creature.name,
|
|
creature_stats.len()
|
|
));
|
|
};
|
|
Ok(creature_stats.pop().unwrap())
|
|
}
|
|
|
|
/// A generic Deserialisation from a database
|
|
fn generic_deserialize<T: more_fields::FieldsAsSlice + DeserializeOwned>(
|
|
connection: &Connection,
|
|
table_name: &str,
|
|
filter: Option<&str>,
|
|
sort: Option<&str>,
|
|
) -> Result<Vec<T>, anyhow::Error> {
|
|
let info = format!(
|
|
"Querying data on {} with {} WHERE {:?} ORDER BY {:?}",
|
|
table_name,
|
|
std::any::type_name::<T>(),
|
|
filter,
|
|
sort,
|
|
);
|
|
let generate_select_query = generate_select_query::<T>(table_name, filter, sort);
|
|
// println!("{}", generate_select_query);
|
|
let mut r = connection.prepare(&generate_select_query).context(info)?;
|
|
let rows = r.query([])?;
|
|
let r = serde_rusqlite::from_rows::<T>(rows).collect::<Result<Vec<T>, serde_rusqlite::Error>>();
|
|
r.context("No")
|
|
}
|
|
|
|
fn generate_select_query<T: more_fields::FieldsAsSlice>(
|
|
table_name: &str,
|
|
filter: Option<&str>,
|
|
sort: Option<&str>,
|
|
) -> String {
|
|
format!(
|
|
"SELECT {} FROM {}{}{};",
|
|
T::attributes_slice()
|
|
.iter()
|
|
.map(|(k, _v)| k.to_owned())
|
|
.collect::<Vec<_>>()
|
|
.join(","),
|
|
table_name,
|
|
filter.map_or_else(String::default, |j| " WHERE ".to_string() + j),
|
|
sort.map_or_else(String::default, |j| " ORDER BY ".to_string() + j)
|
|
)
|
|
}
|