refactor database.rs into struct and impl

This commit is contained in:
Frédéric CAMPO 2025-02-17 19:35:35 +01:00
parent a5d44b82e4
commit 862021e0b2
Signed by: llowin
GPG Key ID: 19EACF0560706F99
4 changed files with 69 additions and 43 deletions

View File

@ -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<String>) -> Result<Self, FatalEquipementError> {
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<T>(
&self,
fields: &[&str],
table_name: &str,
) -> Result<Vec<T>, 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::<T>(query_result.query([])?)
.filter_map(|s| s.ok())
.collect();
Ok(res)
}
}
impl RecipeDatabase for EquipementDatabase {
fn serialize_vec_from_table<T>(table: &str) -> Result<Vec<T>, crate::error::EquipementError> {
todo!()
}
fn serialize_vec_from_table_with_query<T>(
table: &str,
query: &str,
) -> Result<Vec<T>, 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<String>) -> Result<Connection> {
filename.map_or_else(Connection::open_in_memory, Connection::open)
}
/// Public function to get data from db
pub fn get_data_from_fields<T>(
db_conn: rusqlite::Connection,
fields: &[&str],
table_name: &str,
) -> Result<Vec<T>>
where
T: DeserializeOwned,
{
let gen_query = generate_query(fields, table_name);
let mut query_result = db_conn.prepare(&gen_query)?;
let res = from_rows::<T>(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<Connection> {
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<EquipementDatabase, FatalEquipementError> {
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::<TestStruct>(
_conn,
&TestStruct::FIELD_NAMES_AS_ARRAY,
"TestStruct",
)
.unwrap();
let conn = set_up().unwrap();
let result = conn
.get_data_from_fields::<TestStruct>(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct")
.unwrap();
println!("{:?}", result);
assert!(result.is_empty())
}

View File

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

View File

@ -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<T>(table: &str) -> Result<T, EquipementError>;
fn serialize_vec_from_table<T>(table: &str) -> std::result::Result<Vec<T>, EquipementError>;
/// Serialize a specified vector of objects of the given type with an additionnal restriction
fn serialize_vec_from_table_with_query<T>(
table: &str,
query: &str,
) -> Result<T, EquipementError>;
) -> std::result::Result<Vec<T>, EquipementError>;
}
/// Trait implemented by any struct aiming to be a public recipe

View File

@ -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<T>(table: &str) -> Result<T, crate::error::EquipementError> {
fn serialize_vec_from_table<T>(
table: &str,
) -> std::result::Result<Vec<T>, crate::error::EquipementError> {
let _ = table;
todo!()
}
@ -24,7 +26,7 @@ impl RecipeDatabase for DatabaseMock {
fn serialize_vec_from_table_with_query<T>(
table: &str,
query: &str,
) -> Result<T, crate::error::EquipementError> {
) -> std::result::Result<Vec<T>, crate::error::EquipementError> {
let _ = table;
let _ = query;
todo!()