qleany-common 2.0.1

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

// ═══════════════════════════════════════════════════════════════════════
// Entity WITH forward relationships — explicit struct implementation
// ═══════════════════════════════════════════════════════════════════════
use crate::database::hashmap_store::{
    HashMapJunction, HashMapStore, delete_from_backward_junction, junction_get, junction_remove,
    junction_set, read_or_recover, write_or_recover,
};
use crate::entities::Field;
use crate::error::RepositoryError;
use crate::types::EntityId;
use crate::{impl_relationship_methods, impl_write_relationship_methods};
use std::sync::RwLock;

use super::field_repository::FieldRelationshipField;
use super::field_repository::FieldTable;
use super::field_repository::FieldTableRO;

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

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

    fn resolve_junction(&self, field: &FieldRelationshipField) -> &RwLock<HashMapJunction> {
        match field {
            FieldRelationshipField::Entity => &self.store.jn_entity_from_field_entity,
        }
    }

    fn relationship_source_exists(&self, id: &EntityId) -> bool {
        read_or_recover(&self.store.fields).contains_key(id)
    }

    fn relationship_is_ordered(&self, field: &FieldRelationshipField) -> bool {
        match field {
            FieldRelationshipField::Entity => false,
        }
    }

    /// Validate a batch of row replacements for one relationship before any is
    /// written. Costs O(targets in `rows`): exclusivity is checked against the
    /// junction's reverse index, never by walking the relationship's other rows.
    fn validate_relationship_updates(
        &self,
        field: &FieldRelationshipField,
        rows: &[(EntityId, Vec<EntityId>)],
        _creating_ids: &[EntityId],
    ) -> Result<(), RepositoryError> {
        let scalar = match field {
            FieldRelationshipField::Entity => {
                let targets = read_or_recover(&self.store.entities);
                let missing: Vec<_> = rows
                    .iter()
                    .flat_map(|(_, ids)| ids)
                    .copied()
                    .filter(|id| !targets.contains_key(id))
                    .collect();
                if !missing.is_empty() {
                    return Err(RepositoryError::MissingRelationshipTarget {
                        operation: "relationship update",
                        ids: missing,
                    });
                }
                true
            }
        };
        crate::database::hashmap_store::validate_junction_updates(
            self.resolve_junction(field),
            rows,
            scalar,
        )
    }

    fn hydrate(&self, entity: &mut Field) {
        entity.entity = junction_get(&self.store.jn_entity_from_field_entity, &entity.id)
            .into_iter()
            .next();
    }
}

impl<'a> FieldTable for FieldHashMapTable<'a> {
    fn create(&mut self, entity: &Field) -> Result<Field, RepositoryError> {
        self.create_multi(std::slice::from_ref(entity))
            .and_then(|v| {
                // `create_multi` is contracted to return one row per input, so this
                // is unreachable — but it used to be `.unwrap()`, and a store that
                // ever broke that contract would take the whole process down rather
                // than fail the one call that noticed.
                v.into_iter().next().ok_or_else(|| {
                    RepositoryError::Other(anyhow::anyhow!(
                        "create: the store returned no row for the entity it was given"
                    ))
                })
            })
    }

    fn create_multi(&mut self, entities: &[Field]) -> Result<Vec<Field>, RepositoryError> {
        // Assign identities first, then validate the whole batch without holding
        // the source table lock (self-referential relationships read that table).
        let entities: Vec<_> = entities
            .iter()
            .map(|entity| {
                let mut entity = entity.clone();
                if entity.id == EntityId::default() {
                    entity.id = self.store.next_id("field");
                }
                entity
            })
            .collect();

        let mut created = Vec::with_capacity(entities.len());
        let mut field_map = write_or_recover(&self.store.fields);

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

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

            junction_set(
                &self.store.jn_entity_from_field_entity,
                new_entity.id,
                new_entity.entity.into_iter().collect::<Vec<EntityId>>(),
            );

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

    fn get(&self, id: &EntityId) -> Result<Option<Field>, RepositoryError> {
        let field_map = read_or_recover(&self.store.fields);
        match field_map.get(id) {
            Some(entity) => {
                let mut e = entity.clone();
                drop(field_map);
                self.hydrate(&mut e);
                Ok(Some(e))
            }
            None => Ok(None),
        }
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Field>>, 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<Field>, RepositoryError> {
        let field_map = read_or_recover(&self.store.fields);
        let entries: Vec<Field> = field_map.values().cloned().collect();
        drop(field_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: &Field) -> Result<Field, RepositoryError> {
        self.update_multi(std::slice::from_ref(entity))
            .and_then(|v| {
                // `update_multi` is contracted to return one row per input, so this
                // is unreachable — but it used to be `.unwrap()`, and a store that
                // ever broke that contract would take the whole process down rather
                // than fail the one call that noticed.
                v.into_iter().next().ok_or_else(|| {
                    RepositoryError::Other(anyhow::anyhow!(
                        "update: the store returned no row for the entity it was given"
                    ))
                })
            })
    }

    // Scalar-only update: writes entity data but does NOT touch junction tables.
    fn update_multi(&mut self, entities: &[Field]) -> Result<Vec<Field>, RepositoryError> {
        let mut field_map = write_or_recover(&self.store.fields);
        for entity in entities {
            field_map.insert(entity.id, entity.clone());
        }
        drop(field_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: &Field) -> Result<Field, RepositoryError> {
        self.update_with_relationships_multi(std::slice::from_ref(entity))
            .and_then(|v| {
                // `update_with_relationships_multi` is contracted to return one row per input, so this
                // is unreachable — but it used to be `.unwrap()`, and a store that
                // ever broke that contract would take the whole process down rather
                // than fail the one call that noticed.
                v.into_iter().next().ok_or_else(|| {
                    RepositoryError::Other(anyhow::anyhow!(
                        "update_with_relationships: the store returned no row for the entity it was given"
                    ))
                })
            })
    }

    fn update_with_relationships_multi(
        &mut self,
        entities: &[Field],
    ) -> Result<Vec<Field>, RepositoryError> {
        let mut field_map = write_or_recover(&self.store.fields);
        for entity in entities {
            field_map.insert(entity.id, entity.clone());

            junction_set(
                &self.store.jn_entity_from_field_entity,
                entity.id,
                entity.entity.into_iter().collect::<Vec<EntityId>>(),
            );
        }
        drop(field_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 field_map = write_or_recover(&self.store.fields);
        for id in ids {
            field_map.remove(id);

            // Remove forward junction entries

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

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

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

    impl_write_relationship_methods!(FieldHashMapTable<'a>, FieldRelationshipField);
}

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

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

    fn resolve_junction(&self, field: &FieldRelationshipField) -> &RwLock<HashMapJunction> {
        match field {
            FieldRelationshipField::Entity => &self.store.jn_entity_from_field_entity,
        }
    }

    fn hydrate(&self, entity: &mut Field) {
        entity.entity = junction_get(&self.store.jn_entity_from_field_entity, &entity.id)
            .into_iter()
            .next();
    }
}

impl<'a> FieldTableRO for FieldHashMapTableRO<'a> {
    fn get(&self, id: &EntityId) -> Result<Option<Field>, RepositoryError> {
        let field_map = read_or_recover(&self.store.fields);
        match field_map.get(id) {
            Some(entity) => {
                let mut e = entity.clone();
                drop(field_map);
                self.hydrate(&mut e);
                Ok(Some(e))
            }
            None => Ok(None),
        }
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Field>>, 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<Field>, RepositoryError> {
        let field_map = read_or_recover(&self.store.fields);
        let entries: Vec<Field> = field_map.values().cloned().collect();
        drop(field_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!(FieldHashMapTableRO<'a>, FieldRelationshipField);
}