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::Feature;
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::feature_repository::FeatureRelationshipField;
use super::feature_repository::FeatureTable;
use super::feature_repository::FeatureTableRO;

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

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

    fn resolve_junction(
        &self,
        field: &FeatureRelationshipField,
    ) -> &RwLock<HashMap<EntityId, Vec<EntityId>>> {
        match field {
            FeatureRelationshipField::UseCases => &self.store.jn_use_case_from_feature_use_cases,
        }
    }

    fn hydrate(&self, entity: &mut Feature) {
        entity.use_cases = junction_get(&self.store.jn_use_case_from_feature_use_cases, &entity.id);
    }
}

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

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

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

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

            junction_set(
                &self.store.jn_use_case_from_feature_use_cases,
                new_entity.id,
                new_entity.use_cases.clone(),
            );

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

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

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

            junction_set(
                &self.store.jn_use_case_from_feature_use_cases,
                entity.id,
                entity.use_cases.clone(),
            );
        }
        drop(feature_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 feature_map = self.store.features.write().unwrap();
        for id in ids {
            feature_map.remove(id);

            // Remove forward junction entries

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

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

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

    impl_write_relationship_methods!(FeatureHashMapTable<'a>, FeatureRelationshipField);
}

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

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

    fn resolve_junction(
        &self,
        field: &FeatureRelationshipField,
    ) -> &RwLock<HashMap<EntityId, Vec<EntityId>>> {
        match field {
            FeatureRelationshipField::UseCases => &self.store.jn_use_case_from_feature_use_cases,
        }
    }

    fn hydrate(&self, entity: &mut Feature) {
        entity.use_cases = junction_get(&self.store.jn_use_case_from_feature_use_cases, &entity.id);
    }
}

impl<'a> FeatureTableRO for FeatureHashMapTableRO<'a> {
    fn get(&self, id: &EntityId) -> Result<Option<Feature>, RepositoryError> {
        let feature_map = self.store.features.read().unwrap();
        match feature_map.get(id) {
            Some(entity) => {
                let mut e = entity.clone();
                drop(feature_map);
                self.hydrate(&mut e);
                Ok(Some(e))
            }
            None => Ok(None),
        }
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Feature>>, 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<Feature>, RepositoryError> {
        let feature_map = self.store.features.read().unwrap();
        let entries: Vec<Feature> = feature_map.values().cloned().collect();
        drop(feature_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!(FeatureHashMapTableRO<'a>, FeatureRelationshipField);
}