use crate::database::Store;
use crate::entities::Document;
use crate::error::RepositoryError;
use crate::types::EntityId;
use std::collections::HashMap as StdHashMap;
use super::document_repository::DocumentRelationshipField;
use super::document_repository::DocumentTable;
use super::document_repository::DocumentTableRO;
fn read_field(doc: &Document, field: &DocumentRelationshipField) -> Vec<EntityId> {
match field {
DocumentRelationshipField::Frames => doc.frames.clone(),
DocumentRelationshipField::Lists => doc.lists.clone(),
DocumentRelationshipField::Resources => doc.resources.clone(),
DocumentRelationshipField::Tables => doc.tables.clone(),
}
}
fn write_field(doc: &mut Document, field: &DocumentRelationshipField, ids: Vec<EntityId>) {
match field {
DocumentRelationshipField::Frames => doc.frames = ids,
DocumentRelationshipField::Lists => doc.lists = ids,
DocumentRelationshipField::Resources => doc.resources = ids,
DocumentRelationshipField::Tables => doc.tables = ids,
}
}
pub struct DocumentHashMapTable<'a> {
store: &'a Store,
}
impl<'a> DocumentHashMapTable<'a> {
pub fn new(store: &'a Store) -> Self {
Self { store }
}
}
impl<'a> DocumentTable for DocumentHashMapTable<'a> {
fn create(&mut self, entity: &Document) -> Result<Document, RepositoryError> {
self.create_multi(std::slice::from_ref(entity))
.map(|v| v.into_iter().next().unwrap())
}
fn create_multi(&mut self, entities: &[Document]) -> Result<Vec<Document>, RepositoryError> {
let mut created = Vec::with_capacity(entities.len());
let mut document_map = self.store.documents.write().unwrap();
for entity in entities {
let new_entity = if entity.id == EntityId::default() {
let id = self.store.next_id("document");
Document {
id,
..entity.clone()
}
} else {
if document_map.contains_key(&entity.id) {
return Err(RepositoryError::DuplicateId {
entity: "Document",
id: entity.id,
});
}
entity.clone()
};
document_map.insert(new_entity.id, new_entity.clone());
created.push(new_entity);
}
Ok(created)
}
fn get(&self, id: &EntityId) -> Result<Option<Document>, RepositoryError> {
Ok(self.store.documents.read().unwrap().get(id).cloned())
}
fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Document>>, RepositoryError> {
let map = self.store.documents.read().unwrap();
Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
}
fn get_all(&self) -> Result<Vec<Document>, RepositoryError> {
Ok(self
.store
.documents
.read()
.unwrap()
.values()
.cloned()
.collect())
}
fn update(&mut self, entity: &Document) -> Result<Document, RepositoryError> {
self.update_multi(std::slice::from_ref(entity))
.map(|v| v.into_iter().next().unwrap())
}
fn update_multi(&mut self, entities: &[Document]) -> Result<Vec<Document>, RepositoryError> {
let mut document_map = self.store.documents.write().unwrap();
let mut result = Vec::with_capacity(entities.len());
for entity in entities {
let mut to_write = entity.clone();
if let Some(existing) = document_map.get(&entity.id) {
to_write.frames = existing.frames.clone();
to_write.lists = existing.lists.clone();
to_write.resources = existing.resources.clone();
to_write.tables = existing.tables.clone();
}
document_map.insert(entity.id, to_write.clone());
result.push(to_write);
}
Ok(result)
}
fn update_with_relationships(
&mut self,
entity: &Document,
) -> Result<Document, 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: &[Document],
) -> Result<Vec<Document>, RepositoryError> {
let mut document_map = self.store.documents.write().unwrap();
let mut result = Vec::with_capacity(entities.len());
for entity in entities {
document_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 document_map = self.store.documents.write().unwrap();
for id in ids {
document_map.remove(id);
}
drop(document_map);
let mut roots = self.store.roots.write().unwrap();
let to_clear: Vec<EntityId> = roots
.iter()
.filter_map(|(rid, r)| ids.contains(&r.document).then_some(*rid))
.collect();
for rid in to_clear {
if let Some(root) = roots.get_mut(&rid) {
root.document = EntityId::default();
}
}
Ok(())
}
fn get_relationship(
&self,
id: &EntityId,
field: &DocumentRelationshipField,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.documents
.read()
.unwrap()
.get(id)
.map(|d| read_field(d, field))
.unwrap_or_default())
}
fn get_relationship_many(
&self,
ids: &[EntityId],
field: &DocumentRelationshipField,
) -> Result<StdHashMap<EntityId, Vec<EntityId>>, RepositoryError> {
let map = self.store.documents.read().unwrap();
let mut out = StdHashMap::new();
for id in ids {
out.insert(
*id,
map.get(id)
.map(|d| read_field(d, field))
.unwrap_or_default(),
);
}
Ok(out)
}
fn get_relationship_count(
&self,
id: &EntityId,
field: &DocumentRelationshipField,
) -> Result<usize, RepositoryError> {
Ok(self
.store
.documents
.read()
.unwrap()
.get(id)
.map(|d| read_field(d, field).len())
.unwrap_or(0))
}
fn get_relationship_in_range(
&self,
id: &EntityId,
field: &DocumentRelationshipField,
offset: usize,
limit: usize,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.documents
.read()
.unwrap()
.get(id)
.map(|d| {
read_field(d, field)
.into_iter()
.skip(offset)
.take(limit)
.collect()
})
.unwrap_or_default())
}
fn get_relationships_from_right_ids(
&self,
field: &DocumentRelationshipField,
right_ids: &[EntityId],
) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
let map = self.store.documents.read().unwrap();
let mut out = Vec::new();
for (id, doc) in map.iter() {
let list = read_field(doc, field);
if right_ids.iter().any(|rid| list.contains(rid)) {
out.push((*id, list));
}
}
Ok(out)
}
fn set_relationship_multi(
&mut self,
field: &DocumentRelationshipField,
relationships: Vec<(EntityId, Vec<EntityId>)>,
) -> Result<(), RepositoryError> {
let mut map = self.store.documents.write().unwrap();
for (id, ids) in relationships {
if let Some(doc) = map.get_mut(&id) {
write_field(doc, field, ids);
}
}
Ok(())
}
fn set_relationship(
&mut self,
id: &EntityId,
field: &DocumentRelationshipField,
right_ids: &[EntityId],
) -> Result<(), RepositoryError> {
let mut map = self.store.documents.write().unwrap();
if let Some(doc) = map.get_mut(id) {
write_field(doc, field, right_ids.to_vec());
}
Ok(())
}
fn move_relationship_ids(
&mut self,
id: &EntityId,
field: &DocumentRelationshipField,
ids_to_move: &[EntityId],
new_index: i32,
) -> Result<Vec<EntityId>, RepositoryError> {
let mut map = self.store.documents.write().unwrap();
let Some(doc) = map.get_mut(id) else {
return Ok(Vec::new());
};
let current = read_field(doc, field);
let moved = reorder(current, ids_to_move, new_index);
write_field(doc, field, moved.clone());
Ok(moved)
}
}
pub struct DocumentHashMapTableRO<'a> {
store: &'a Store,
}
impl<'a> DocumentHashMapTableRO<'a> {
pub fn new(store: &'a Store) -> Self {
Self { store }
}
}
impl<'a> DocumentTableRO for DocumentHashMapTableRO<'a> {
fn get(&self, id: &EntityId) -> Result<Option<Document>, RepositoryError> {
Ok(self.store.documents.read().unwrap().get(id).cloned())
}
fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Document>>, RepositoryError> {
let map = self.store.documents.read().unwrap();
Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
}
fn get_all(&self) -> Result<Vec<Document>, RepositoryError> {
Ok(self
.store
.documents
.read()
.unwrap()
.values()
.cloned()
.collect())
}
fn get_relationship(
&self,
id: &EntityId,
field: &DocumentRelationshipField,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.documents
.read()
.unwrap()
.get(id)
.map(|d| read_field(d, field))
.unwrap_or_default())
}
fn get_relationship_many(
&self,
ids: &[EntityId],
field: &DocumentRelationshipField,
) -> Result<StdHashMap<EntityId, Vec<EntityId>>, RepositoryError> {
let map = self.store.documents.read().unwrap();
let mut out = StdHashMap::new();
for id in ids {
out.insert(
*id,
map.get(id)
.map(|d| read_field(d, field))
.unwrap_or_default(),
);
}
Ok(out)
}
fn get_relationship_count(
&self,
id: &EntityId,
field: &DocumentRelationshipField,
) -> Result<usize, RepositoryError> {
Ok(self
.store
.documents
.read()
.unwrap()
.get(id)
.map(|d| read_field(d, field).len())
.unwrap_or(0))
}
fn get_relationship_in_range(
&self,
id: &EntityId,
field: &DocumentRelationshipField,
offset: usize,
limit: usize,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.documents
.read()
.unwrap()
.get(id)
.map(|d| {
read_field(d, field)
.into_iter()
.skip(offset)
.take(limit)
.collect()
})
.unwrap_or_default())
}
fn get_relationships_from_right_ids(
&self,
field: &DocumentRelationshipField,
right_ids: &[EntityId],
) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
let map = self.store.documents.read().unwrap();
let mut out = Vec::new();
for (id, doc) in map.iter() {
let list = read_field(doc, 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
}