Skip to content

Commit

Permalink
update where eq error handling when calling crud methods
Browse files Browse the repository at this point in the history
  • Loading branch information
giuseppe-g-gelardi committed Nov 27, 2024
1 parent 372a879 commit 3956e1c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 33 deletions.
3 changes: 3 additions & 0 deletions src/cargobase/errors/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
83 changes: 50 additions & 33 deletions src/cargobase/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,23 +41,25 @@ impl Query {
self,
key: &str,
value: &str,
) -> Result<Option<T>, String> {
) -> Result<Option<T>, 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];
Expand All @@ -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!(),
Expand All @@ -83,36 +89,34 @@ 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
.tables
.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 {
table.columns.validate(row_data.clone())?; // optional schema validation
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(),
))
}
}

Expand All @@ -121,13 +125,15 @@ impl Query {
table: &Table,
key: &str,
value: &str,
) -> Result<Option<T>, String> {
) -> Result<Option<T>, 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))
});
}
}
}
Expand All @@ -139,7 +145,7 @@ impl Query {
table: &mut Table,
key: &str,
value: &str,
) -> Result<Option<T>, String> {
) -> Result<Option<T>, DatabaseError> {
for row in &mut table.rows {
if let Some(field_value) = row.data.get(key) {
if field_value.as_str() == Some(value) {
Expand All @@ -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(),
));
}
}
}
Expand All @@ -174,15 +191,15 @@ impl Query {
table: &mut Table,
key: &str,
value: &str,
) -> Result<Option<T>, String> {
) -> Result<Option<T>, 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));
}
}
Expand All @@ -192,7 +209,7 @@ impl Query {
}
pub fn all<T: DeserializeOwned>(&self) -> Vec<T> {
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(),
Expand All @@ -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()
}
}
Expand Down

0 comments on commit 3956e1c

Please sign in to comment.