qleany-common 1.7.4

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::System;
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::system_repository::SystemRelationshipField;
use super::system_repository::SystemTable;
use super::system_repository::SystemTableRO;

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

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

    fn resolve_junction(
        &self,
        field: &SystemRelationshipField,
    ) -> &RwLock<HashMap<EntityId, Vec<EntityId>>> {
        match field {
            SystemRelationshipField::Files => &self.store.jn_file_from_system_files,
        }
    }

    fn hydrate(&self, entity: &mut System) {
        entity.files = junction_get(&self.store.jn_file_from_system_files, &entity.id);
    }
}

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

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

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

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

            junction_set(
                &self.store.jn_file_from_system_files,
                new_entity.id,
                new_entity.files.clone(),
            );

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

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

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

            junction_set(
                &self.store.jn_file_from_system_files,
                entity.id,
                entity.files.clone(),
            );
        }
        drop(system_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 system_map = self.store.systems.write().unwrap();
        for id in ids {
            system_map.remove(id);

            // Remove forward junction entries

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

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

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

    impl_write_relationship_methods!(SystemHashMapTable<'a>, SystemRelationshipField);
}

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

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

    fn resolve_junction(
        &self,
        field: &SystemRelationshipField,
    ) -> &RwLock<HashMap<EntityId, Vec<EntityId>>> {
        match field {
            SystemRelationshipField::Files => &self.store.jn_file_from_system_files,
        }
    }

    fn hydrate(&self, entity: &mut System) {
        entity.files = junction_get(&self.store.jn_file_from_system_files, &entity.id);
    }
}

impl<'a> SystemTableRO for SystemHashMapTableRO<'a> {
    fn get(&self, id: &EntityId) -> Result<Option<System>, RepositoryError> {
        let system_map = self.store.systems.read().unwrap();
        match system_map.get(id) {
            Some(entity) => {
                let mut e = entity.clone();
                drop(system_map);
                self.hydrate(&mut e);
                Ok(Some(e))
            }
            None => Ok(None),
        }
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<System>>, 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<System>, RepositoryError> {
        let system_map = self.store.systems.read().unwrap();
        let entries: Vec<System> = system_map.values().cloned().collect();
        drop(system_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!(SystemHashMapTableRO<'a>, SystemRelationshipField);
}