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::File;
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::file_repository::FileRelationshipField;
use super::file_repository::FileTable;
use super::file_repository::FileTableRO;

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

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

    fn resolve_junction(
        &self,
        field: &FileRelationshipField,
    ) -> &RwLock<HashMap<EntityId, Vec<EntityId>>> {
        match field {
            FileRelationshipField::Entity => &self.store.jn_entity_from_file_entity,
            FileRelationshipField::Feature => &self.store.jn_feature_from_file_feature,
            FileRelationshipField::Field => &self.store.jn_field_from_file_field,
            FileRelationshipField::UseCase => &self.store.jn_use_case_from_file_use_case,
        }
    }

    fn hydrate(&self, entity: &mut File) {
        entity.feature = junction_get(&self.store.jn_feature_from_file_feature, &entity.id)
            .into_iter()
            .next();
        entity.entity = junction_get(&self.store.jn_entity_from_file_entity, &entity.id)
            .into_iter()
            .next();
        entity.use_case = junction_get(&self.store.jn_use_case_from_file_use_case, &entity.id)
            .into_iter()
            .next();
        entity.field = junction_get(&self.store.jn_field_from_file_field, &entity.id)
            .into_iter()
            .next();
    }
}

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

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

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

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

            junction_set(
                &self.store.jn_entity_from_file_entity,
                new_entity.id,
                new_entity.entity.into_iter().collect::<Vec<EntityId>>(),
            );
            junction_set(
                &self.store.jn_feature_from_file_feature,
                new_entity.id,
                new_entity.feature.into_iter().collect::<Vec<EntityId>>(),
            );
            junction_set(
                &self.store.jn_field_from_file_field,
                new_entity.id,
                new_entity.field.into_iter().collect::<Vec<EntityId>>(),
            );
            junction_set(
                &self.store.jn_use_case_from_file_use_case,
                new_entity.id,
                new_entity.use_case.into_iter().collect::<Vec<EntityId>>(),
            );

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

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

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

            junction_set(
                &self.store.jn_feature_from_file_feature,
                entity.id,
                entity.feature.into_iter().collect::<Vec<EntityId>>(),
            );
            junction_set(
                &self.store.jn_entity_from_file_entity,
                entity.id,
                entity.entity.into_iter().collect::<Vec<EntityId>>(),
            );
            junction_set(
                &self.store.jn_use_case_from_file_use_case,
                entity.id,
                entity.use_case.into_iter().collect::<Vec<EntityId>>(),
            );
            junction_set(
                &self.store.jn_field_from_file_field,
                entity.id,
                entity.field.into_iter().collect::<Vec<EntityId>>(),
            );
        }
        drop(file_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 file_map = self.store.files.write().unwrap();
        for id in ids {
            file_map.remove(id);

            // Remove forward junction entries

            junction_remove(&self.store.jn_feature_from_file_feature, id);
            junction_remove(&self.store.jn_entity_from_file_entity, id);
            junction_remove(&self.store.jn_use_case_from_file_use_case, id);
            junction_remove(&self.store.jn_field_from_file_field, id);

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

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

    impl_write_relationship_methods!(FileHashMapTable<'a>, FileRelationshipField);
}

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

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

    fn resolve_junction(
        &self,
        field: &FileRelationshipField,
    ) -> &RwLock<HashMap<EntityId, Vec<EntityId>>> {
        match field {
            FileRelationshipField::Entity => &self.store.jn_entity_from_file_entity,
            FileRelationshipField::Feature => &self.store.jn_feature_from_file_feature,
            FileRelationshipField::Field => &self.store.jn_field_from_file_field,
            FileRelationshipField::UseCase => &self.store.jn_use_case_from_file_use_case,
        }
    }

    fn hydrate(&self, entity: &mut File) {
        entity.feature = junction_get(&self.store.jn_feature_from_file_feature, &entity.id)
            .into_iter()
            .next();
        entity.entity = junction_get(&self.store.jn_entity_from_file_entity, &entity.id)
            .into_iter()
            .next();
        entity.use_case = junction_get(&self.store.jn_use_case_from_file_use_case, &entity.id)
            .into_iter()
            .next();
        entity.field = junction_get(&self.store.jn_field_from_file_field, &entity.id)
            .into_iter()
            .next();
    }
}

impl<'a> FileTableRO for FileHashMapTableRO<'a> {
    fn get(&self, id: &EntityId) -> Result<Option<File>, RepositoryError> {
        let file_map = self.store.files.read().unwrap();
        match file_map.get(id) {
            Some(entity) => {
                let mut e = entity.clone();
                drop(file_map);
                self.hydrate(&mut e);
                Ok(Some(e))
            }
            None => Ok(None),
        }
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<File>>, 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<File>, RepositoryError> {
        let file_map = self.store.files.read().unwrap();
        let entries: Vec<File> = file_map.values().cloned().collect();
        drop(file_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!(FileHashMapTableRO<'a>, FileRelationshipField);
}