feat: added failsafe for pk overwriting

This commit is contained in:
Elias Renman
2023-08-14 10:45:27 +02:00
parent ccc49b241d
commit e1b0575a8a
2 changed files with 22 additions and 1 deletions

View File

@@ -1,7 +1,10 @@
use super::{index::Index, row::Row};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{hash_map::Entry, HashMap};
use std::{
borrow::Borrow,
collections::{hash_map::Entry, HashMap},
};
#[derive(Serialize, Deserialize)]
pub struct Table {
@@ -41,6 +44,10 @@ impl Table {
return Err("Primary key is not of type u64".to_string());
}
if self.rows.contains_key(row_primary_key.unwrap().borrow()) {
return Err("Primary key already exists".to_string());
}
// Insert row into database
self.rows.insert(row_primary_key.unwrap(), row.clone());

View File

@@ -29,4 +29,18 @@ mod table_test {
let row = table.find_by_pk(3u64);
assert_eq!(row.is_err(), true);
}
#[test]
fn should_fail_to_insert_row_with_same_id() {
let mut table: Table = Table::new("Cats", "id", None);
let _ = table.insert_row(row!["id" => 1, "name" => "Ozzy"]);
// Make sure the rows actually exists
let row = table.find_by_pk(1u64);
assert_eq!(row.unwrap().get("id").unwrap(), 1u64);
let result = table.insert_row(row!["id" => 1, "name" => "Simon"]);
assert_eq!(result.is_err(), true);
}
}