diff --git a/src/cargobase/errors/errors.rs b/src/cargobase/errors/errors.rs index 37e2396..b42c0e9 100644 --- a/src/cargobase/errors/errors.rs +++ b/src/cargobase/errors/errors.rs @@ -29,4 +29,7 @@ pub enum DatabaseError { #[error("Column `{0}` is required")] ColumnRequiredError(String), + + #[error("")] // could expand to specify serialization/deserialization error + JSONError(#[from] serde_json::Error), } diff --git a/src/cargobase/query.rs b/src/cargobase/query.rs index 765ead8..6f2177f 100644 --- a/src/cargobase/query.rs +++ b/src/cargobase/query.rs @@ -41,23 +41,25 @@ impl Query { self, key: &str, value: &str, - ) -> Result, String> { + ) -> Result, DatabaseError> { // Load the database let mut db = Database::load_from_file(&self.db_file_name) - .map_err(|e| format!("Failed to load database: {}", e))?; + .map_err(|e| DatabaseError::LoadError(e))?; // Clone table_name to avoid moving self let table_name = self .table_name .clone() - .ok_or_else(|| "Table name not specified.".to_string())?; + .ok_or_else(|| DatabaseError::TableNotFound("Table name not specified.".to_string()))?; // Find the index of the table let table_index = db .tables .iter() .position(|t| t.name == table_name) - .ok_or_else(|| format!("Table '{}' not found.", table_name))?; + .ok_or_else(|| { + DatabaseError::TableNotFound(format!("Table '{}' not found.", table_name)) + })?; // Borrow the table by index let table = &mut db.tables[table_index]; @@ -67,14 +69,18 @@ impl Query { Operation::Read => self.execute_select(table, key, value), Operation::Update => { let result = self.execute_update(table, key, value); - db.save_to_file() - .map_err(|e| format!("Failed to save database: {}", e))?; + if let Err(e) = db.save_to_file().map_err(DatabaseError::SaveError) { + tracing::error!("Failed to save database: {}", e); + return Err(e); + } result } Operation::Delete => { let result = self.execute_delete(table, key, value); - db.save_to_file() - .map_err(|e| format!("Failed to save database: {}", e))?; + if let Err(e) = db.save_to_file().map_err(DatabaseError::SaveError) { + tracing::error!("Failed to save database: {}", e); + return Err(e); + } result } Operation::Create => unreachable!(), @@ -83,15 +89,13 @@ impl Query { // pub fn execute_add(self) -> Result<(), String> { pub fn execute_add(self) -> Result<(), DatabaseError> { - let mut db = Database::load_from_file(&self.db_file_name) - .map_err(DatabaseError::LoadError)?; - // .map_err(|e| format!("Failed to load database: {}", e))?; + let mut db = + Database::load_from_file(&self.db_file_name).map_err(DatabaseError::LoadError)?; let table_name = self .table_name .clone() .ok_or_else(|| DatabaseError::InvalidData("Table name not specified.".to_string()))?; - // .ok_or_else(|| "Table name not specified.".to_string())?; // Find the table let table = db @@ -99,7 +103,6 @@ impl Query { .iter_mut() .find(|t| t.name == table_name) .ok_or_else(|| DatabaseError::TableNotFound(table_name.clone()))?; - // .ok_or_else(|| format!("Table '{}' not found.", table_name))?; // Validate and add the row if let Some(row_data) = self.row_data { @@ -107,12 +110,13 @@ impl Query { table.rows.push(Row::new(row_data)); db.save_to_file().map_err(DatabaseError::SaveError)?; - // .map_err(|e| format!("Failed to save database: {}", e))?; - println!("Row added successfully to '{}'.", table_name); + tracing::info!("Row added successfully to '{}'.", table_name); Ok(()) } else { - // Err("No data provided for the new row.".to_string()) - Err(DatabaseError::InvalidData("No data provided for the new row.".to_string())) + tracing::error!("No data provided for the new row."); + Err(DatabaseError::InvalidData( + "No data provided for the new row.".to_string(), + )) } } @@ -121,13 +125,15 @@ impl Query { table: &Table, key: &str, value: &str, - ) -> Result, String> { + ) -> Result, DatabaseError> { for row in &table.rows { if let Some(field_value) = row.data.get(key) { if field_value.as_str() == Some(value) { return serde_json::from_value(row.data.clone()) .map(Some) - .map_err(|e| format!("Deserialization error: {}", e)); + .map_err(|e| { + DatabaseError::InvalidData(format!("Deserialization error: {}", e)) + }); } } } @@ -139,7 +145,7 @@ impl Query { table: &mut Table, key: &str, value: &str, - ) -> Result, String> { + ) -> Result, DatabaseError> { for row in &mut table.rows { if let Some(field_value) = row.data.get(key) { if field_value.as_str() == Some(value) { @@ -150,18 +156,29 @@ impl Query { row_map.insert(k.clone(), v.clone()); } } else { - return Err("Row data is not a JSON object.".to_string()); + return Err(DatabaseError::InvalidData( + "Row data is not a JSON object.".to_string(), + )); } - println!("Record updated successfully."); - return serde_json::from_value(row.data.clone()) - .map(Some) - .map_err(|e| format!("Deserialization error: {}", e)); + tracing::info!("Record updated successfully."); + return serde_json::from_value(row.data.clone()).map(Some).map_err( + |e| { + DatabaseError::InvalidData(format!( + "Deserialization error: {}", + e + )) + }, + ); } else { - return Err("Invalid update data format.".to_string()); + return Err(DatabaseError::InvalidData( + "Invalid update data format.".to_string(), + )); } } else { - return Err("No update data provided.".to_string()); + return Err(DatabaseError::InvalidData( + "No update data provided.".to_string(), + )); } } } @@ -174,15 +191,15 @@ impl Query { table: &mut Table, key: &str, value: &str, - ) -> Result, String> { + ) -> Result, DatabaseError> { for (i, row) in table.rows.iter().enumerate() { if let Some(field_value) = row.data.get(key) { if field_value.as_str() == Some(value) { let record = serde_json::from_value(row.data.clone()) - .map_err(|e| format!("Deserialization error: {}", e))?; + .map_err(|e| DatabaseError::JSONError(e))?; table.rows.remove(i); - println!("Record deleted successfully."); + tracing::info!("Record deleted successfully."); return Ok(Some(record)); } } @@ -192,7 +209,7 @@ impl Query { } pub fn all(&self) -> Vec { let db = Database::load_from_file(&self.db_file_name).unwrap_or_else(|e| { - eprintln!("Failed to load database from file: {}", e); + tracing::error!("Failed to load database from file: {}", e); Database { name: String::new(), file_name: self.db_file_name.clone(), @@ -208,11 +225,11 @@ impl Query { .filter_map(|row| serde_json::from_value(row.data.clone()).ok()) .collect() } else { - eprintln!("Table {} not found", table_name); + tracing::error!("Table {} not found", table_name); Vec::new() } } else { - eprintln!("Table name not provided"); + tracing::error!("Table name not provided"); Vec::new() } }