qleany-common 1.8.0

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

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

use crate::database::hashmap_store::{
    HashMapStore, delete_from_backward_junction, junction_get, junction_remove, junction_set,
};
use crate::entities::Relationship;
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::relationship_repository::RelationshipRelationshipField;
use super::relationship_repository::RelationshipTable;
use super::relationship_repository::RelationshipTableRO;

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

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

    fn resolve_junction(
        &self,
        field: &RelationshipRelationshipField,
    ) -> &RwLock<HashMap<EntityId, Vec<EntityId>>> {
        match field {
            RelationshipRelationshipField::LeftEntity => {
                &self.store.jn_entity_from_relationship_left_entity
            }
            RelationshipRelationshipField::RightEntity => {
                &self.store.jn_entity_from_relationship_right_entity
            }
        }
    }

    fn hydrate(&self, entity: &mut Relationship) {
        entity.left_entity = junction_get(
            &self.store.jn_entity_from_relationship_left_entity,
            &entity.id,
        )
        .into_iter()
        .next();
        entity.right_entity = junction_get(
            &self.store.jn_entity_from_relationship_right_entity,
            &entity.id,
        )
        .into_iter()
        .next();
    }
}

impl<'a> RelationshipTable for RelationshipHashMapTable<'a> {
    fn create(&mut self, entity: &Relationship) -> Result<Relationship, RepositoryError> {
        self.create_multi(std::slice::from_ref(entity))
            .map(|v| v.into_iter().next().unwrap())
    }

    fn create_multi(
        &mut self,
        entities: &[Relationship],
    ) -> Result<Vec<Relationship>, RepositoryError> {
        let mut created = Vec::with_capacity(entities.len());
        let mut relationship_map = self.store.relationships.write().unwrap();

        for entity in entities {
            let new_entity = if entity.id == EntityId::default() {
                let id = self.store.next_id("relationship");
                Relationship {
                    id,
                    ..entity.clone()
                }
            } else {
                if relationship_map.contains_key(&entity.id) {
                    return Err(RepositoryError::DuplicateId {
                        entity: "Relationship",
                        id: entity.id,
                    });
                }
                entity.clone()
            };

            relationship_map.insert(new_entity.id, new_entity.clone());

            junction_set(
                &self.store.jn_entity_from_relationship_left_entity,
                new_entity.id,
                new_entity
                    .left_entity
                    .into_iter()
                    .collect::<Vec<EntityId>>(),
            );
            junction_set(
                &self.store.jn_entity_from_relationship_right_entity,
                new_entity.id,
                new_entity
                    .right_entity
                    .into_iter()
                    .collect::<Vec<EntityId>>(),
            );

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

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

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Relationship>>, 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<Relationship>, RepositoryError> {
        let relationship_map = self.store.relationships.read().unwrap();
        let entries: Vec<Relationship> = relationship_map.values().cloned().collect();
        drop(relationship_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: &Relationship) -> Result<Relationship, 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: &[Relationship],
    ) -> Result<Vec<Relationship>, RepositoryError> {
        let mut relationship_map = self.store.relationships.write().unwrap();
        for entity in entities {
            relationship_map.insert(entity.id, entity.clone());
        }
        drop(relationship_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: &Relationship,
    ) -> Result<Relationship, 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: &[Relationship],
    ) -> Result<Vec<Relationship>, RepositoryError> {
        let mut relationship_map = self.store.relationships.write().unwrap();
        for entity in entities {
            relationship_map.insert(entity.id, entity.clone());

            junction_set(
                &self.store.jn_entity_from_relationship_left_entity,
                entity.id,
                entity.left_entity.into_iter().collect::<Vec<EntityId>>(),
            );
            junction_set(
                &self.store.jn_entity_from_relationship_right_entity,
                entity.id,
                entity.right_entity.into_iter().collect::<Vec<EntityId>>(),
            );
        }
        drop(relationship_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 relationship_map = self.store.relationships.write().unwrap();
        for id in ids {
            relationship_map.remove(id);

            // Remove forward junction entries

            junction_remove(&self.store.jn_entity_from_relationship_left_entity, id);
            junction_remove(&self.store.jn_entity_from_relationship_right_entity, id);

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

            delete_from_backward_junction(
                &self.store.jn_relationship_from_entity_relationships,
                id,
            );
        }
        Ok(())
    }

    impl_write_relationship_methods!(RelationshipHashMapTable<'a>, RelationshipRelationshipField);
}

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

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

    fn resolve_junction(
        &self,
        field: &RelationshipRelationshipField,
    ) -> &RwLock<HashMap<EntityId, Vec<EntityId>>> {
        match field {
            RelationshipRelationshipField::LeftEntity => {
                &self.store.jn_entity_from_relationship_left_entity
            }
            RelationshipRelationshipField::RightEntity => {
                &self.store.jn_entity_from_relationship_right_entity
            }
        }
    }

    fn hydrate(&self, entity: &mut Relationship) {
        entity.left_entity = junction_get(
            &self.store.jn_entity_from_relationship_left_entity,
            &entity.id,
        )
        .into_iter()
        .next();
        entity.right_entity = junction_get(
            &self.store.jn_entity_from_relationship_right_entity,
            &entity.id,
        )
        .into_iter()
        .next();
    }
}

impl<'a> RelationshipTableRO for RelationshipHashMapTableRO<'a> {
    fn get(&self, id: &EntityId) -> Result<Option<Relationship>, RepositoryError> {
        let relationship_map = self.store.relationships.read().unwrap();
        match relationship_map.get(id) {
            Some(entity) => {
                let mut e = entity.clone();
                drop(relationship_map);
                self.hydrate(&mut e);
                Ok(Some(e))
            }
            None => Ok(None),
        }
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Relationship>>, 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<Relationship>, RepositoryError> {
        let relationship_map = self.store.relationships.read().unwrap();
        let entries: Vec<Relationship> = relationship_map.values().cloned().collect();
        drop(relationship_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!(
        RelationshipHashMapTableRO<'a>,
        RelationshipRelationshipField
    );
}