use crate::database::Store;
use crate::entities::Root;
use crate::error::RepositoryError;
use crate::types::EntityId;
use std::collections::HashMap as StdHashMap;
use super::root_repository::RootRelationshipField;
use super::root_repository::RootTable;
use super::root_repository::RootTableRO;
fn read_field(root: &Root, field: &RootRelationshipField) -> Vec<EntityId> {
match field {
RootRelationshipField::Document => {
if root.document == EntityId::default() {
Vec::new()
} else {
vec![root.document]
}
}
}
}
fn write_field(root: &mut Root, field: &RootRelationshipField, ids: Vec<EntityId>) {
match field {
RootRelationshipField::Document => {
root.document = ids.first().copied().unwrap_or_default();
}
}
}
fn check_one_to_one(
store: &Store,
self_id: EntityId,
document_id: EntityId,
) -> Result<(), RepositoryError> {
if document_id == EntityId::default() {
return Ok(());
}
let roots = store.roots.read().unwrap();
for (existing_id, existing) in roots.iter() {
if *existing_id != self_id && existing.document == document_id {
return Err(RepositoryError::ConstraintViolation(format!(
"One-to-one constraint violation: Document {} is already referenced by Root {}",
document_id, existing_id
)));
}
}
Ok(())
}
pub struct RootHashMapTable<'a> {
store: &'a Store,
}
impl<'a> RootHashMapTable<'a> {
pub fn new(store: &'a Store) -> Self {
Self { store }
}
}
impl<'a> RootTable for RootHashMapTable<'a> {
fn create(&mut self, entity: &Root) -> Result<Root, RepositoryError> {
self.create_multi(std::slice::from_ref(entity))
.map(|v| v.into_iter().next().unwrap())
}
fn create_multi(&mut self, entities: &[Root]) -> Result<Vec<Root>, RepositoryError> {
let mut created = Vec::with_capacity(entities.len());
let mut root_map = self.store.roots.write().unwrap();
for entity in entities {
let new_entity = if entity.id == EntityId::default() {
let id = self.store.next_id("root");
Root {
id,
..entity.clone()
}
} else {
if root_map.contains_key(&entity.id) {
return Err(RepositoryError::DuplicateId {
entity: "Root",
id: entity.id,
});
}
entity.clone()
};
if new_entity.document != EntityId::default() {
for (existing_id, existing) in root_map.iter() {
if *existing_id != new_entity.id && existing.document == new_entity.document {
return Err(RepositoryError::ConstraintViolation(format!(
"One-to-one constraint violation: Document {} is already referenced by Root {}",
new_entity.document, existing_id
)));
}
}
}
root_map.insert(new_entity.id, new_entity.clone());
created.push(new_entity);
}
Ok(created)
}
fn get(&self, id: &EntityId) -> Result<Option<Root>, RepositoryError> {
Ok(self.store.roots.read().unwrap().get(id).cloned())
}
fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Root>>, RepositoryError> {
let map = self.store.roots.read().unwrap();
Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
}
fn get_all(&self) -> Result<Vec<Root>, RepositoryError> {
Ok(self.store.roots.read().unwrap().values().cloned().collect())
}
fn update(&mut self, entity: &Root) -> Result<Root, RepositoryError> {
self.update_multi(std::slice::from_ref(entity))
.map(|v| v.into_iter().next().unwrap())
}
fn update_multi(&mut self, entities: &[Root]) -> Result<Vec<Root>, RepositoryError> {
let mut root_map = self.store.roots.write().unwrap();
let mut result = Vec::with_capacity(entities.len());
for entity in entities {
let mut to_write = entity.clone();
if let Some(existing) = root_map.get(&entity.id) {
to_write.document = existing.document;
}
root_map.insert(entity.id, to_write.clone());
result.push(to_write);
}
Ok(result)
}
fn update_with_relationships(&mut self, entity: &Root) -> Result<Root, RepositoryError> {
self.update_with_relationships_multi(std::slice::from_ref(entity))
.map(|v| v.into_iter().next().unwrap())
}
fn update_with_relationships_multi(
&mut self,
entities: &[Root],
) -> Result<Vec<Root>, RepositoryError> {
for entity in entities {
check_one_to_one(self.store, entity.id, entity.document)?;
}
let mut root_map = self.store.roots.write().unwrap();
let mut result = Vec::with_capacity(entities.len());
for entity in entities {
root_map.insert(entity.id, entity.clone());
result.push(entity.clone());
}
Ok(result)
}
fn remove(&mut self, id: &EntityId) -> Result<(), RepositoryError> {
self.remove_multi(std::slice::from_ref(id))
}
fn remove_multi(&mut self, ids: &[EntityId]) -> Result<(), RepositoryError> {
let mut root_map = self.store.roots.write().unwrap();
for id in ids {
root_map.remove(id);
}
Ok(())
}
fn get_relationship(
&self,
id: &EntityId,
field: &RootRelationshipField,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.roots
.read()
.unwrap()
.get(id)
.map(|r| read_field(r, field))
.unwrap_or_default())
}
fn get_relationship_many(
&self,
ids: &[EntityId],
field: &RootRelationshipField,
) -> Result<StdHashMap<EntityId, Vec<EntityId>>, RepositoryError> {
let map = self.store.roots.read().unwrap();
let mut out = StdHashMap::new();
for id in ids {
out.insert(
*id,
map.get(id)
.map(|r| read_field(r, field))
.unwrap_or_default(),
);
}
Ok(out)
}
fn get_relationship_count(
&self,
id: &EntityId,
field: &RootRelationshipField,
) -> Result<usize, RepositoryError> {
Ok(self
.store
.roots
.read()
.unwrap()
.get(id)
.map(|r| read_field(r, field).len())
.unwrap_or(0))
}
fn get_relationship_in_range(
&self,
id: &EntityId,
field: &RootRelationshipField,
offset: usize,
limit: usize,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.roots
.read()
.unwrap()
.get(id)
.map(|r| {
read_field(r, field)
.into_iter()
.skip(offset)
.take(limit)
.collect()
})
.unwrap_or_default())
}
fn get_relationships_from_right_ids(
&self,
field: &RootRelationshipField,
right_ids: &[EntityId],
) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
let map = self.store.roots.read().unwrap();
let mut out = Vec::new();
for (id, root) in map.iter() {
let list = read_field(root, field);
if right_ids.iter().any(|rid| list.contains(rid)) {
out.push((*id, list));
}
}
Ok(out)
}
fn set_relationship_multi(
&mut self,
field: &RootRelationshipField,
relationships: Vec<(EntityId, Vec<EntityId>)>,
) -> Result<(), RepositoryError> {
for (id, ids) in &relationships {
if let RootRelationshipField::Document = field
&& let Some(&doc_id) = ids.first()
{
check_one_to_one(self.store, *id, doc_id)?;
}
}
let mut map = self.store.roots.write().unwrap();
for (id, ids) in relationships {
if let Some(root) = map.get_mut(&id) {
write_field(root, field, ids);
}
}
Ok(())
}
fn set_relationship(
&mut self,
id: &EntityId,
field: &RootRelationshipField,
right_ids: &[EntityId],
) -> Result<(), RepositoryError> {
if let RootRelationshipField::Document = field
&& let Some(&doc_id) = right_ids.first()
{
check_one_to_one(self.store, *id, doc_id)?;
}
let mut map = self.store.roots.write().unwrap();
if let Some(root) = map.get_mut(id) {
write_field(root, field, right_ids.to_vec());
}
Ok(())
}
fn move_relationship_ids(
&mut self,
id: &EntityId,
field: &RootRelationshipField,
ids_to_move: &[EntityId],
new_index: i32,
) -> Result<Vec<EntityId>, RepositoryError> {
let mut map = self.store.roots.write().unwrap();
let Some(root) = map.get_mut(id) else {
return Ok(Vec::new());
};
let current = read_field(root, field);
let moved = reorder(current, ids_to_move, new_index);
write_field(root, field, moved.clone());
Ok(moved)
}
}
pub struct RootHashMapTableRO<'a> {
store: &'a Store,
}
impl<'a> RootHashMapTableRO<'a> {
pub fn new(store: &'a Store) -> Self {
Self { store }
}
}
impl<'a> RootTableRO for RootHashMapTableRO<'a> {
fn get(&self, id: &EntityId) -> Result<Option<Root>, RepositoryError> {
Ok(self.store.roots.read().unwrap().get(id).cloned())
}
fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Root>>, RepositoryError> {
let map = self.store.roots.read().unwrap();
Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
}
fn get_all(&self) -> Result<Vec<Root>, RepositoryError> {
Ok(self.store.roots.read().unwrap().values().cloned().collect())
}
fn get_relationship(
&self,
id: &EntityId,
field: &RootRelationshipField,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.roots
.read()
.unwrap()
.get(id)
.map(|r| read_field(r, field))
.unwrap_or_default())
}
fn get_relationship_many(
&self,
ids: &[EntityId],
field: &RootRelationshipField,
) -> Result<StdHashMap<EntityId, Vec<EntityId>>, RepositoryError> {
let map = self.store.roots.read().unwrap();
let mut out = StdHashMap::new();
for id in ids {
out.insert(
*id,
map.get(id)
.map(|r| read_field(r, field))
.unwrap_or_default(),
);
}
Ok(out)
}
fn get_relationship_count(
&self,
id: &EntityId,
field: &RootRelationshipField,
) -> Result<usize, RepositoryError> {
Ok(self
.store
.roots
.read()
.unwrap()
.get(id)
.map(|r| read_field(r, field).len())
.unwrap_or(0))
}
fn get_relationship_in_range(
&self,
id: &EntityId,
field: &RootRelationshipField,
offset: usize,
limit: usize,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.roots
.read()
.unwrap()
.get(id)
.map(|r| {
read_field(r, field)
.into_iter()
.skip(offset)
.take(limit)
.collect()
})
.unwrap_or_default())
}
fn get_relationships_from_right_ids(
&self,
field: &RootRelationshipField,
right_ids: &[EntityId],
) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
let map = self.store.roots.read().unwrap();
let mut out = Vec::new();
for (id, root) in map.iter() {
let list = read_field(root, field);
if right_ids.iter().any(|rid| list.contains(rid)) {
out.push((*id, list));
}
}
Ok(out)
}
}
fn reorder(current: Vec<EntityId>, ids_to_move: &[EntityId], new_index: i32) -> Vec<EntityId> {
if ids_to_move.is_empty() {
return current;
}
let move_set: std::collections::HashSet<EntityId> = ids_to_move.iter().copied().collect();
let mut remaining: Vec<EntityId> = current
.into_iter()
.filter(|eid| !move_set.contains(eid))
.collect();
let insert_pos = if new_index < 0 || (new_index as usize) > remaining.len() {
remaining.len()
} else {
new_index as usize
};
for (i, &eid) in ids_to_move.iter().enumerate() {
remaining.insert(insert_pos + i, eid);
}
remaining
}