mirror of
https://github.com/eliasrenman/r-database.git
synced 2026-03-16 20:46:08 +01:00
feat: added failsafe for pk overwriting
This commit is contained in:
@@ -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());
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user