Skip to content

Commit

Permalink
update path and io operations to user pathbuf instead of string
Browse files Browse the repository at this point in the history
  • Loading branch information
giuseppe-g-gelardi committed Dec 18, 2024
1 parent f8e13f6 commit b94948b
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 17 deletions.
31 changes: 20 additions & 11 deletions src/database.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use tracing;
Expand All @@ -8,8 +9,8 @@ use crate::{query::Operation, DatabaseError, Query, Table, View};
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct Database {
pub(crate) name: String,
pub(crate) file_name: String,
pub(crate) tables: HashMap<String, Table>, // pub(crate) tables: Vec<Table>,
pub(crate) file_name: PathBuf,
pub(crate) tables: HashMap<String, Table>,
}

impl Database {
Expand Down Expand Up @@ -37,7 +38,7 @@ impl Database {

Database {
name,
file_name,
file_name: file_name.into(),
tables: HashMap::new(), // tables: Vec::new(),
}
}
Expand Down Expand Up @@ -92,14 +93,19 @@ impl Database {
pub(crate) async fn save_to_file(&self) -> Result<(), tokio::io::Error> {
let json_data = serde_json::to_string_pretty(&self)?;
tokio::fs::write(&self.file_name, json_data).await?;
tracing::info!("Database saved to file: {}", self.file_name);
tracing::info!("Database saved to file: {:?}", self.file_name);
Ok(())
}

pub(crate) async fn load_from_file(file_name: &str) -> Result<Self, tokio::io::Error> {
let json_data = tokio::fs::read_to_string(file_name).await?;
pub(crate) async fn load_from_file<P: AsRef<Path>>(
file_name: P,
) -> Result<Self, tokio::io::Error> {
let json_data = tokio::fs::read_to_string(file_name.as_ref()).await?;
let db: Database = serde_json::from_str(&json_data)?;
tracing::info!("Database loaded from file: {}", file_name);
tracing::info!(
"Database loaded from file: {:?}",
file_name.as_ref().display()
);
Ok(db)
}

Expand Down Expand Up @@ -244,7 +250,7 @@ mod tests {
let fnn = format!("{db_name}.json");

assert_eq!(db.name, db_name.to_string());
assert_eq!(db.file_name, fnn);
assert_eq!(db.file_name.to_string_lossy(), fnn);
assert_eq!(db.tables.len(), 1); // the setup_temp_db function adds a table
}

Expand Down Expand Up @@ -329,7 +335,8 @@ mod tests {
use tempfile::NamedTempFile;

let temp_file = NamedTempFile::new().expect("Failed to create a temporary file");
let db_path = temp_file.path().to_str().unwrap().to_string();
let db_path = temp_file.path().to_path_buf();
// let db_path = temp_file.path().to_str().unwrap().to_string();

let db = Database {
name: "test_db".to_string(),
Expand All @@ -349,11 +356,13 @@ mod tests {
use tempfile::NamedTempFile;

let temp_file = NamedTempFile::new().expect("Failed to create a temporary file");
let db_path = temp_file.path().to_str().unwrap().to_string();
let db_path = temp_file.path().to_path_buf();
// let db_path = temp_file.path().to_str().unwrap().to_string();

let db = Database {
name: "test_db".to_string(),
file_name: db_path.to_string(),
file_name: db_path.clone(),
// file_name: db_path.to_string(),
tables: HashMap::new(),
};

Expand Down
11 changes: 6 additions & 5 deletions src/query.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::collections::HashMap;
use std::path::PathBuf;

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
Expand All @@ -16,7 +17,7 @@ pub enum Operation {

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct Query {
pub db_file_name: String,
pub db_file_name: PathBuf,
pub table_name: Option<String>,
pub operation: Operation,
pub update_data: Option<Value>,
Expand Down Expand Up @@ -283,7 +284,7 @@ mod tests {
#[test]
fn test_query_from() {
let query = Query {
db_file_name: "test_db.json".to_string(),
db_file_name: "test_db.json".into(),
table_name: None,
operation: Operation::Read,
update_data: None,
Expand All @@ -297,7 +298,7 @@ mod tests {
#[test]
fn test_query_data() {
let query = Query {
db_file_name: "test_db.json".to_string(),
db_file_name: "test_db.json".into(),
table_name: Some("TestTable".to_string()),
operation: Operation::Update,
update_data: None,
Expand All @@ -314,7 +315,7 @@ mod tests {
fn test_query_data_from_struct() {
std::fs::remove_file("test_db.json").ok();
let query = Query {
db_file_name: "test_db.json".to_string(),
db_file_name: "test_db.json".into(),
table_name: Some("TestTable".to_string()),
operation: Operation::Create,
update_data: None,
Expand Down Expand Up @@ -371,7 +372,7 @@ mod tests {
#[test]
fn test_query_set() {
let query = Query {
db_file_name: "test_db.json".to_string(),
db_file_name: "test_db.json".into(),
table_name: Some("TestTable".to_string()),
operation: Operation::Update,
update_data: None,
Expand Down
3 changes: 2 additions & 1 deletion src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,8 @@ mod tests {
db.add_table(&mut table).await.unwrap();

// Simulate failure in saving
db.file_name = "/invalid/path.json".to_string();
db.file_name = "/invalid/path.json".into();

let row_data = json!({"id": "1", "name": "John Doe"});
table.add_row(&mut db, row_data).await;

Expand Down

0 comments on commit b94948b

Please sign in to comment.