text-document-direct-access 1.4.0

Entity CRUD controllers and DTOs for text-document
Documentation
// Generated by Qleany v1.5.0 from entity_units_of_work.tera

use anyhow::{Ok, Result};
use common::database::{CommandUnitOfWork, QueryUnitOfWork};
use common::database::{db_context::DbContext, transactions::Transaction};
use common::direct_access::repository_factory;
use common::direct_access::use_cases;
use common::entities::List;
use common::event::{AllEvent, DirectAccessEntity, Event, EventBuffer, EventHub, Origin};
use common::snapshot::EntityTreeSnapshot;
use common::types;
use common::types::EntityId;
use std::cell::RefCell;
use std::sync::Arc;

// ===========================================================================
// Write UoW
// ===========================================================================

pub struct ListWriteUoW {
    context: DbContext,
    transaction: Option<Transaction>,
    event_hub: Arc<EventHub>,
    event_buffer: RefCell<EventBuffer>,
}

impl ListWriteUoW {
    pub fn new(db_context: &DbContext, event_hub: &Arc<EventHub>) -> Self {
        ListWriteUoW {
            context: db_context.clone(),
            transaction: None,
            event_hub: event_hub.clone(),
            event_buffer: RefCell::new(EventBuffer::new()),
        }
    }
}

impl CommandUnitOfWork for ListWriteUoW {
    fn begin_transaction(&mut self) -> Result<()> {
        self.transaction = Some(Transaction::begin_write_transaction(&self.context)?);
        self.event_buffer.get_mut().begin_buffering();
        Ok(())
    }

    fn commit(&mut self) -> Result<()> {
        self.transaction.take().unwrap().commit()?;
        for event in self.event_buffer.get_mut().flush() {
            self.event_hub.send_event(event);
        }
        Ok(())
    }

    fn rollback(&mut self) -> Result<()> {
        self.transaction.take().unwrap().rollback()?;
        self.event_buffer.get_mut().discard();
        Ok(())
    }

    fn create_savepoint(&self) -> Result<types::Savepoint> {
        self.transaction.as_ref().unwrap().create_savepoint()
    }

    fn restore_to_savepoint(&mut self, savepoint: types::Savepoint) -> Result<()> {
        let mut transaction = self.transaction.take().unwrap();
        transaction.restore_to_savepoint(savepoint)?;

        // Discard buffered events — savepoint restore invalidated them
        self.event_buffer.get_mut().discard();

        // Send Reset immediately (not buffered — UI must refresh now)
        self.event_hub.send_event(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::All(AllEvent::Reset)),
            ids: vec![],
            data: None,
        });

        // Recreate the transaction after restoring to savepoint
        self.transaction = Some(transaction);

        Ok(())
    }
}

impl use_cases::WriteUoW for ListWriteUoW {
    type Entity = List;

    fn get(&self, id: &EntityId) -> Result<Option<List>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let repo = repository_factory::write::create_list_repository(transaction);
        Ok(repo.get(id)?)
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<List>>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let repo = repository_factory::write::create_list_repository(transaction);
        Ok(repo.get_multi(ids)?)
    }

    fn get_all(&self) -> Result<Vec<List>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let repo = repository_factory::write::create_list_repository(transaction);
        Ok(repo.get_all()?)
    }

    fn create_orphan_multi(&self, entities: &[List]) -> Result<Vec<List>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_list_repository(transaction);
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.create_orphan_multi(&mut event_buffer, entities)?)
    }

    fn update_multi(&self, entities: &[List]) -> Result<Vec<List>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_list_repository(transaction);
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.update_multi(&mut event_buffer, entities)?)
    }

    fn update_with_relationships_multi(&self, entities: &[List]) -> Result<Vec<List>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_list_repository(transaction);
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.update_with_relationships_multi(&mut event_buffer, entities)?)
    }

    fn remove(&self, id: &EntityId) -> Result<()> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_list_repository(transaction);
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.remove(&mut event_buffer, id)?)
    }

    fn remove_multi(&self, ids: &[EntityId]) -> Result<()> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_list_repository(transaction);
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.remove_multi(&mut event_buffer, ids)?)
    }

    fn snapshot(&self, ids: &[EntityId]) -> Result<EntityTreeSnapshot> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let repo = repository_factory::write::create_list_repository(transaction);
        Ok(repo.snapshot(ids)?)
    }

    fn restore(&self, snap: &EntityTreeSnapshot) -> Result<()> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_list_repository(transaction);
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.restore(&mut event_buffer, snap)?)
    }
}

impl use_cases::OwnedWriteUoW for ListWriteUoW {
    fn create_multi(&self, entities: &[List], owner_id: EntityId, index: i32) -> Result<Vec<List>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_list_repository(transaction);
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.create_multi(&mut event_buffer, entities, owner_id, index)?)
    }

    fn get_relationships_from_owner(&self, owner_id: &EntityId) -> Result<Vec<EntityId>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let repo = repository_factory::write::create_list_repository(transaction);
        Ok(repo.get_relationships_from_owner(owner_id)?)
    }

    fn set_relationships_in_owner(&self, owner_id: &EntityId, ids: &[EntityId]) -> Result<()> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_list_repository(transaction);
        let mut event_buffer = self.event_buffer.borrow_mut();
        repo.set_relationships_in_owner(&mut event_buffer, owner_id, ids)?;
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Write UoW Factory
// ---------------------------------------------------------------------------

pub struct ListWriteUoWFactory {
    context: DbContext,
    event_hub: Arc<EventHub>,
}

impl ListWriteUoWFactory {
    pub fn new(db_context: &DbContext, event_hub: &Arc<EventHub>) -> Self {
        ListWriteUoWFactory {
            context: db_context.clone(),
            event_hub: event_hub.clone(),
        }
    }
}

impl use_cases::WriteUoWFactory for ListWriteUoWFactory {
    type Entity = List;
    fn create(&self) -> Box<dyn use_cases::WriteUoW<Entity = List>> {
        Box::new(ListWriteUoW::new(&self.context, &self.event_hub))
    }
}

impl use_cases::OwnedWriteUoWFactory for ListWriteUoWFactory {
    type Entity = List;
    fn create(&self) -> Box<dyn use_cases::OwnedWriteUoW<Entity = List>> {
        Box::new(ListWriteUoW::new(&self.context, &self.event_hub))
    }
}

// ===========================================================================
// Read-Only UoW
// ===========================================================================

pub struct ListReadUoW {
    context: DbContext,
    transaction: RefCell<Option<Transaction>>,
}

impl ListReadUoW {
    pub fn new(db_context: &DbContext) -> Self {
        ListReadUoW {
            context: db_context.clone(),
            transaction: RefCell::new(None),
        }
    }
}

impl QueryUnitOfWork for ListReadUoW {
    fn begin_transaction(&self) -> Result<()> {
        self.transaction
            .replace(Some(Transaction::begin_read_transaction(&self.context)?));
        Ok(())
    }

    fn end_transaction(&self) -> Result<()> {
        self.transaction.take().unwrap().end_read_transaction()?;
        Ok(())
    }
}

impl use_cases::ReadUoW for ListReadUoW {
    type Entity = List;

    fn get(&self, id: &EntityId) -> Result<Option<List>> {
        let transaction = self.transaction.borrow();
        let repo = repository_factory::read::create_list_repository(transaction.as_ref().unwrap());
        Ok(repo.get(id)?)
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<List>>> {
        let transaction = self.transaction.borrow();
        let repo = repository_factory::read::create_list_repository(transaction.as_ref().unwrap());
        Ok(repo.get_multi(ids)?)
    }

    fn get_all(&self) -> Result<Vec<List>> {
        let transaction = self.transaction.borrow();
        let repo = repository_factory::read::create_list_repository(transaction.as_ref().unwrap());
        Ok(repo.get_all()?)
    }
}

// ---------------------------------------------------------------------------
// Read-Only UoW Factory
// ---------------------------------------------------------------------------

pub struct ListReadUoWFactory {
    context: DbContext,
}

impl ListReadUoWFactory {
    pub fn new(db_context: &DbContext) -> Self {
        ListReadUoWFactory {
            context: db_context.clone(),
        }
    }
}

impl use_cases::ReadUoWFactory for ListReadUoWFactory {
    type Entity = List;
    fn create(&self) -> Box<dyn use_cases::ReadUoW<Entity = List>> {
        Box::new(ListReadUoW::new(&self.context))
    }
}