text-document-common 1.4.1

Shared entities, database, events, and undo/redo infrastructure for text-document
Documentation
// Generated by Qleany v1.7.3 from common_entity_table.tera

// ═══════════════════════════════════════════════════════════════════════
// Entity WITH forward relationships — explicit struct implementation
// ═══════════════════════════════════════════════════════════════════════

use crate::database::hashmap_store::{HashMapStore, junction_get, junction_remove, junction_set};
use crate::entities::Root;
use crate::error::RepositoryError;
use crate::types::EntityId;
use crate::{impl_relationship_methods, impl_write_relationship_methods};
use im::HashMap;
use std::sync::RwLock;

use super::root_repository::RootRelationshipField;
use super::root_repository::RootTable;
use super::root_repository::RootTableRO;

pub struct RootHashMapTable<'a> {
    store: &'a HashMapStore,
}

impl<'a> RootHashMapTable<'a> {
    pub fn new(store: &'a HashMapStore) -> Self {
        Self { store }
    }

    fn resolve_junction(
        &self,
        field: &RootRelationshipField,
    ) -> &RwLock<HashMap<EntityId, Vec<EntityId>>> {
        match field {
            RootRelationshipField::Document => &self.store.jn_document_from_root_document,
        }
    }

    fn hydrate(&self, entity: &mut Root) {
        if let Some(val) = junction_get(&self.store.jn_document_from_root_document, &entity.id)
            .into_iter()
            .next()
        {
            entity.document = val;
        }
    }
}

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()
            };

            // one-to-one constraint check: ensure document is not already referenced by another root
            {
                let jn = self.store.jn_document_from_root_document.read().unwrap();
                for (&existing_id, right_ids) in jn.iter() {
                    if existing_id != new_entity.id && right_ids.contains(&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());

            junction_set(
                &self.store.jn_document_from_root_document,
                new_entity.id,
                vec![new_entity.document],
            );

            created.push(new_entity);
        }
        Ok(created)
    }

    fn get(&self, id: &EntityId) -> Result<Option<Root>, RepositoryError> {
        let root_map = self.store.roots.read().unwrap();
        match root_map.get(id) {
            Some(entity) => {
                let mut e = entity.clone();
                drop(root_map);
                self.hydrate(&mut e);
                Ok(Some(e))
            }
            None => Ok(None),
        }
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Root>>, RepositoryError> {
        let mut result = Vec::with_capacity(ids.len());
        for id in ids {
            result.push(self.get(id)?);
        }
        Ok(result)
    }

    fn get_all(&self) -> Result<Vec<Root>, RepositoryError> {
        let root_map = self.store.roots.read().unwrap();
        let entries: Vec<Root> = root_map.values().cloned().collect();
        drop(root_map);
        let mut result = Vec::with_capacity(entries.len());
        for mut entity in entries {
            self.hydrate(&mut entity);
            result.push(entity);
        }
        Ok(result)
    }

    fn update(&mut self, entity: &Root) -> Result<Root, RepositoryError> {
        self.update_multi(std::slice::from_ref(entity))
            .map(|v| v.into_iter().next().unwrap())
    }

    // Scalar-only update: writes entity data but does NOT touch junction tables.
    fn update_multi(&mut self, entities: &[Root]) -> Result<Vec<Root>, RepositoryError> {
        let mut root_map = self.store.roots.write().unwrap();
        for entity in entities {
            root_map.insert(entity.id, entity.clone());
        }
        drop(root_map);
        let ids: Vec<EntityId> = entities.iter().map(|e| e.id).collect();
        let result = self.get_multi(&ids)?;
        Ok(result.into_iter().flatten().collect())
    }

    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> {
        let mut root_map = self.store.roots.write().unwrap();
        for entity in entities {
            // one-to-one constraint check: ensure document is not already referenced by another root
            {
                let jn = self.store.jn_document_from_root_document.read().unwrap();
                for (&existing_id, right_ids) in jn.iter() {
                    if existing_id != entity.id && right_ids.contains(&entity.document) {
                        return Err(RepositoryError::ConstraintViolation(format!(
                            "One-to-one constraint violation: Document {} is already referenced by Root {}",
                            entity.document, existing_id
                        )));
                    }
                }
            }
            root_map.insert(entity.id, entity.clone());

            junction_set(
                &self.store.jn_document_from_root_document,
                entity.id,
                vec![entity.document],
            );
        }
        drop(root_map);
        let ids: Vec<EntityId> = entities.iter().map(|e| e.id).collect();
        let result = self.get_multi(&ids)?;
        Ok(result.into_iter().flatten().collect())
    }

    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);

            // Remove forward junction entries

            junction_remove(&self.store.jn_document_from_root_document, id);

            // Clean up backward references (uses the owning entity's forward junction)
        }
        Ok(())
    }

    impl_write_relationship_methods!(RootHashMapTable<'a>, RootRelationshipField);
}

pub struct RootHashMapTableRO<'a> {
    store: &'a HashMapStore,
}

impl<'a> RootHashMapTableRO<'a> {
    pub fn new(store: &'a HashMapStore) -> Self {
        Self { store }
    }

    fn resolve_junction(
        &self,
        field: &RootRelationshipField,
    ) -> &RwLock<HashMap<EntityId, Vec<EntityId>>> {
        match field {
            RootRelationshipField::Document => &self.store.jn_document_from_root_document,
        }
    }

    fn hydrate(&self, entity: &mut Root) {
        if let Some(val) = junction_get(&self.store.jn_document_from_root_document, &entity.id)
            .into_iter()
            .next()
        {
            entity.document = val;
        }
    }
}

impl<'a> RootTableRO for RootHashMapTableRO<'a> {
    fn get(&self, id: &EntityId) -> Result<Option<Root>, RepositoryError> {
        let root_map = self.store.roots.read().unwrap();
        match root_map.get(id) {
            Some(entity) => {
                let mut e = entity.clone();
                drop(root_map);
                self.hydrate(&mut e);
                Ok(Some(e))
            }
            None => Ok(None),
        }
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Root>>, RepositoryError> {
        let mut result = Vec::with_capacity(ids.len());
        for id in ids {
            result.push(self.get(id)?);
        }
        Ok(result)
    }

    fn get_all(&self) -> Result<Vec<Root>, RepositoryError> {
        let root_map = self.store.roots.read().unwrap();
        let entries: Vec<Root> = root_map.values().cloned().collect();
        drop(root_map);
        let mut result = Vec::with_capacity(entries.len());
        for mut entity in entries {
            self.hydrate(&mut entity);
            result.push(entity);
        }
        Ok(result)
    }

    impl_relationship_methods!(RootHashMapTableRO<'a>, RootRelationshipField);
}