Skip to content

Commit

Permalink
add some notes to narrow down whats next
Browse files Browse the repository at this point in the history
  • Loading branch information
giuseppe-g-gelardi committed Nov 26, 2024
1 parent acea68d commit 56fae55
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 8 deletions.
3 changes: 3 additions & 0 deletions src/cargobase/columns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ impl Columns {
Columns(columns)
}

// remove required ??
pub fn from_struct<T: Serialize + DeserializeOwned + Default>(required: bool) -> Self {
// Initialize the reflection tracer
let mut tracer = Tracer::new(TracerConfig::default());
Expand Down Expand Up @@ -252,6 +253,8 @@ mod tests {
location: String,
}
let columns = Columns::from_struct::<TestData>(true);
// testing the order of the Columns as the from_struct method will
// preserve the order of the struct fields as they are declared
assert_eq!(columns.0.len(), 7);
assert_eq!(columns.0[0].name.to_string(), "id".to_string());
assert_eq!(columns.0[1].name.to_string(), "first_name".to_string());
Expand Down
58 changes: 54 additions & 4 deletions src/cargobase/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ impl Database {
let name = name.to_string();
let file_name = format!("{name}.json");

// find a better way of logging this information for the end user
// -- they might not have tracing enabled

if std::path::Path::new(&file_name).exists() {
println!("Database already exists: {name}, loading database");

Expand Down Expand Up @@ -43,6 +46,11 @@ impl Database {
if self.tables.iter().any(|t| t.name == table.name) {
return Err(DatabaseError::TableAlreadyExists(table.name.clone()));
}
// IF the table does not exist, add it to the database
// IF the table exists:
// -- do NOT add a duplicate to the db
// -- let the user know that the table already exists
// -- do NOT crash the program, just return and move on

self.tables.push(table.clone());
self.save_to_file()
Expand All @@ -59,12 +67,21 @@ impl Database {
println!("Table `{}` dropped successfully", removed_table.name);
db.save_to_file().map_err(|e| DatabaseError::SaveError(e))?;

// IF the table does not exist:
// -- let the user know that the table does not exist
// -- do NOT crash the program, just return and move on
//
// IF the table exists:
// -- remove the table from the db
// -- save the db to file
// -- let the user know that the table was removed successfully

self.tables = db.tables;
Ok(())
} else {
eprintln!("{}", DatabaseError::TableNotFound(table_name.to_string()));
// Err(DatabaseError::TableNotFound(table_name.to_string()))
Ok(())
// eprintln!("{}", DatabaseError::TableNotFound(table_name.to_string()));
Err(DatabaseError::TableNotFound(table_name.to_string()))
// Ok(())
}
}

Expand All @@ -75,6 +92,39 @@ impl Database {
Ok(())
}

// pub(crate) fn save_to_file(&self) -> Result<(), std::io::Error> {
// // Serialize the overall structure with pretty formatting
// let mut json_data = serde_json::to_string_pretty(self)?;
//
// // Adjust the rows to be single-line JSON
// if let Some(index) = json_data.find("\"rows\": [") {
// let rows_start = index + "\"rows\": [".len();
// let rows_end = json_data[rows_start..].find(']').unwrap_or(0) + rows_start;
//
// // Extract and reformat rows
// let rows_json = &json_data[rows_start..rows_end];
// let formatted_rows = self
// .tables
// .iter()
// .flat_map(|table| {
// table
// .rows
// .iter()
// .map(|row| serde_json::to_string(row).unwrap())
// })
// .collect::<Vec<_>>()
// .join(",");
//
// // Replace rows in the JSON data
// json_data.replace_range(rows_start..rows_end, &formatted_rows);
// }
//
// // Save to file
// std::fs::write(&self.file_name, json_data)?;
// // tracing::info!(target: "cargobase", "Database saved to file: {}", self.file_name);
// Ok(())
// }

pub(crate) fn load_from_file(file_name: &str) -> Result<Self, std::io::Error> {
let json_data = std::fs::read_to_string(file_name)?;
let db: Database = serde_json::from_str(&json_data)?;
Expand Down Expand Up @@ -244,7 +294,7 @@ mod tests {
assert!(result.is_ok());
assert_eq!(db.tables.len(), 1);
assert_eq!(db.tables[0].name, "TestTable");
assert_eq!(db.tables[0].file_name, Some("test_db.json".to_string()));
// assert_eq!(db.tables[0].file_name, Some("test_db.json".to_string()));

// remove the test_db.json file after testing
std::fs::remove_file("test_db.json").ok();
Expand Down
2 changes: 2 additions & 0 deletions src/cargobase/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ impl Query {
self
}

// from and to are identical
pub fn to(mut self, table_name: &str) -> Self {
self.table_name = Some(table_name.to_string());
self
Expand Down Expand Up @@ -67,6 +68,7 @@ impl Query {
// Borrow the table by index
let table = &mut db.tables[table_index];

// consider thiserror for the error handling for these operations
match self.operation {
Operation::Read => self.execute_select(table, key, value),
Operation::Update => {
Expand Down
10 changes: 6 additions & 4 deletions src/cargobase/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub struct Table {
pub(crate) name: String,
pub rows: Vec<Row>,
pub columns: Columns,
pub(crate) file_name: Option<String>, // reference to the db file_name
// pub(crate) file_name: Option<String>, // reference to the db file_name
}

impl Table {
Expand All @@ -17,12 +17,14 @@ impl Table {
name,
rows: Vec::new(),
columns,
file_name: None,
// file_name: None,
}
}

// consider removing this. need to check what it is doing after removing the file name field
pub(crate) fn set_file_name(&mut self, file_name: String) {
self.file_name = Some(file_name);
// self.file_name = Some(file_name);
println!("File name set to: {}", file_name);
}

pub fn add_row(&mut self, db: &mut Database, data: Value) {
Expand Down Expand Up @@ -84,7 +86,7 @@ mod tests {
let columns = Columns::new(vec![Column::new("name", true), Column::new("age", false)]);
let mut table = Table::new("users".to_string(), columns.clone());
table.set_file_name("db.json".to_string());
assert_eq!(table.file_name, Some("db.json".to_string()));
// assert_eq!(table.file_name, Some("db.json".to_string()));
}
}

Expand Down

0 comments on commit 56fae55

Please sign in to comment.