text-document-direct-access 1.4.0

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

use super::{
    dtos::{CreateRootDto, RootDto, UpdateRootDto},
    units_of_work::{RootReadUoWFactory, RootWriteUoWFactory},
};
use crate::RootRelationshipDto;
use anyhow::{Ok, Result};
use common::direct_access::root::RootRelationshipField;
use common::direct_access::use_cases;

use common::{database::db_context::DbContext, event::EventHub, types::EntityId};
use std::sync::Arc;

pub fn create_orphan(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    entity: &CreateRootDto,
) -> Result<RootDto> {
    let uow_factory = RootWriteUoWFactory::new(db_context, event_hub);
    let mut uc = use_cases::CreateOrphanUseCase::new(uow_factory);
    let entity_in: common::entities::Root = entity.into();
    let result = uc.execute(&entity_in)?;
    Ok(result.into())
}

pub fn create_orphan_multi(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    entities: &[CreateRootDto],
) -> Result<Vec<RootDto>> {
    let uow_factory = RootWriteUoWFactory::new(db_context, event_hub);
    let entities_in: Vec<common::entities::Root> = entities.iter().map(|dto| dto.into()).collect();
    let mut uc = use_cases::CreateOrphanUseCase::new(uow_factory);
    let result = uc.execute_multi(&entities_in)?;
    Ok(result.into_iter().map(|e| e.into()).collect())
}

pub fn get(db_context: &DbContext, id: &EntityId) -> Result<Option<RootDto>> {
    let uow_factory = RootReadUoWFactory::new(db_context);
    let uc = use_cases::GetUseCase::new(uow_factory);
    Ok(uc.execute(id)?.map(|e| e.into()))
}

pub fn get_all(db_context: &DbContext) -> Result<Vec<RootDto>> {
    let uow_factory = RootReadUoWFactory::new(db_context);
    let uc = use_cases::GetUseCase::new(uow_factory);
    Ok(uc.execute_all()?.into_iter().map(|e| e.into()).collect())
}

pub fn get_multi(db_context: &DbContext, ids: &[EntityId]) -> Result<Vec<Option<RootDto>>> {
    let uow_factory = RootReadUoWFactory::new(db_context);
    let uc = use_cases::GetUseCase::new(uow_factory);
    Ok(uc
        .execute_multi(ids)?
        .into_iter()
        .map(|o| o.map(|e| e.into()))
        .collect())
}

pub fn update(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    entity: &UpdateRootDto,
) -> Result<RootDto> {
    let uow_factory = RootWriteUoWFactory::new(db_context, event_hub);
    let entity_in: common::entities::Root = entity.into();
    let mut uc = use_cases::UpdateUseCase::new(uow_factory);
    let result = uc.execute(&entity_in)?;
    Ok(result.into())
}

pub fn update_multi(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    entities: &[UpdateRootDto],
) -> Result<Vec<RootDto>> {
    let uow_factory = RootWriteUoWFactory::new(db_context, event_hub);
    let entities_in: Vec<common::entities::Root> = entities.iter().map(|dto| dto.into()).collect();
    let mut uc = use_cases::UpdateUseCase::new(uow_factory);
    let result = uc.execute_multi(&entities_in)?;
    Ok(result.into_iter().map(|e| e.into()).collect())
}

pub fn update_with_relationships(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    entity: &RootDto,
) -> Result<RootDto> {
    let uow_factory = RootWriteUoWFactory::new(db_context, event_hub);
    let entity_in: common::entities::Root = entity.into();
    let mut uc = use_cases::UpdateWithRelationshipsUseCase::new(uow_factory);
    let result = uc.execute(&entity_in)?;
    Ok(result.into())
}

pub fn update_with_relationships_multi(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    entities: &[RootDto],
) -> Result<Vec<RootDto>> {
    let uow_factory = RootWriteUoWFactory::new(db_context, event_hub);
    let entities_in: Vec<common::entities::Root> = entities.iter().map(|dto| dto.into()).collect();
    let mut uc = use_cases::UpdateWithRelationshipsUseCase::new(uow_factory);
    let result = uc.execute_multi(&entities_in)?;
    Ok(result.into_iter().map(|e| e.into()).collect())
}

pub fn remove(db_context: &DbContext, event_hub: &Arc<EventHub>, id: &EntityId) -> Result<()> {
    let uow_factory = RootWriteUoWFactory::new(db_context, event_hub);
    let mut uc = use_cases::RemoveUseCase::new(uow_factory);
    uc.execute(id)?;
    Ok(())
}

pub fn remove_multi(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    ids: &[EntityId],
) -> Result<()> {
    let uow_factory = RootWriteUoWFactory::new(db_context, event_hub);
    let mut uc = use_cases::RemoveUseCase::new(uow_factory);
    uc.execute_multi(ids)?;
    Ok(())
}

pub fn get_relationship(
    db_context: &DbContext,
    id: &EntityId,
    field: &RootRelationshipField,
) -> Result<Vec<EntityId>> {
    let uow_factory = RootReadUoWFactory::new(db_context);
    let uc = use_cases::GetRelationshipUseCase::<RootRelationshipField, _>::new(uow_factory);
    uc.execute(id, field)
}

pub fn get_relationship_many(
    db_context: &DbContext,
    ids: &[EntityId],
    field: &RootRelationshipField,
) -> Result<std::collections::HashMap<EntityId, Vec<EntityId>>> {
    let uow_factory = RootReadUoWFactory::new(db_context);
    let uc = use_cases::GetRelationshipManyUseCase::<RootRelationshipField, _>::new(uow_factory);
    uc.execute(ids, field)
}

pub fn get_relationship_count(
    db_context: &DbContext,
    id: &EntityId,
    field: &RootRelationshipField,
) -> Result<usize> {
    let uow_factory = RootReadUoWFactory::new(db_context);
    let uc = use_cases::GetRelationshipCountUseCase::<RootRelationshipField, _>::new(uow_factory);
    uc.execute(id, field)
}

pub fn get_relationship_in_range(
    db_context: &DbContext,
    id: &EntityId,
    field: &RootRelationshipField,
    offset: usize,
    limit: usize,
) -> Result<Vec<EntityId>> {
    let uow_factory = RootReadUoWFactory::new(db_context);
    let uc = use_cases::GetRelationshipInRangeUseCase::<RootRelationshipField, _>::new(uow_factory);
    uc.execute(id, field, offset, limit)
}

pub fn set_relationship(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    dto: &RootRelationshipDto,
) -> Result<()> {
    let uow_factory = RootWriteUoWFactory::new(db_context, event_hub);
    let mut uc = use_cases::SetRelationshipUseCase::<RootRelationshipField, _>::new(uow_factory);
    uc.execute(&dto.id, &dto.field, dto.right_ids.as_slice())?;
    Ok(())
}

pub fn move_relationship(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    id: &EntityId,
    field: &RootRelationshipField,
    ids_to_move: &[EntityId],
    new_index: i32,
) -> Result<Vec<EntityId>> {
    let uow_factory = RootWriteUoWFactory::new(db_context, event_hub);
    let mut uc = use_cases::MoveRelationshipUseCase::<RootRelationshipField, _>::new(uow_factory);
    let result = uc.execute(id, field, ids_to_move, new_index)?;
    Ok(result)
}

#[cfg(test)]
mod tests {
    #![allow(dead_code)]
    #![allow(unused_imports)]

    use super::*;
    use common::database::db_context::DbContext;
    use common::event::EventHub;
    use common::types::EntityId;
    use common::undo_redo::UndoRedoManager;
    use std::sync::Arc;

    struct TestContext {
        db: DbContext,
        hub: Arc<EventHub>,
        undo: UndoRedoManager,
    }

    impl TestContext {
        fn new() -> Self {
            let db = DbContext::new().expect("Failed to create in-memory DB");
            let hub = Arc::new(EventHub::new());
            let mut undo = UndoRedoManager::new();
            undo.set_event_hub(&hub);
            TestContext { db, hub, undo }
        }
    }

    /// Create an entity using create_orphan.
    fn create_one(ctx: &mut TestContext) -> RootDto {
        create_orphan(&ctx.db, &ctx.hub, &CreateRootDto::default()).unwrap()
    }

    // -----------------------------------------------------------------------
    // create_orphan + get
    // -----------------------------------------------------------------------

    #[test]
    fn test_create_orphan_and_get() {
        let mut ctx = TestContext::new();
        let created = create_one(&mut ctx);
        assert!(created.id > 0);

        let fetched = get(&ctx.db, &created.id).unwrap();
        assert!(fetched.is_some());
        assert_eq!(fetched.unwrap().id, created.id);
    }

    // -----------------------------------------------------------------------
    // get nonexistent
    // -----------------------------------------------------------------------

    #[test]
    fn test_get_nonexistent() {
        let ctx = TestContext::new();
        assert!(get(&ctx.db, &999999).unwrap().is_none());
    }

    // -----------------------------------------------------------------------
    // get_all
    // -----------------------------------------------------------------------

    #[test]
    fn test_get_all() {
        let mut ctx = TestContext::new();
        create_one(&mut ctx);
        let all = get_all(&ctx.db).unwrap();
        assert!(!all.is_empty());
    }

    // -----------------------------------------------------------------------
    // get_multi
    // -----------------------------------------------------------------------

    #[test]
    fn test_get_multi() {
        let mut ctx = TestContext::new();
        let a = create_one(&mut ctx);
        let results = get_multi(&ctx.db, &[a.id, 999999]).unwrap();
        assert_eq!(results.len(), 2);
        assert!(results[0].is_some());
        assert!(results[1].is_none());
    }

    // -----------------------------------------------------------------------
    // update
    // -----------------------------------------------------------------------

    #[test]
    fn test_update() {
        let mut ctx = TestContext::new();
        let created = create_one(&mut ctx);
        let update_dto: UpdateRootDto = created.into();
        let updated = update(&ctx.db, &ctx.hub, &update_dto).unwrap();
        assert_eq!(updated.id, update_dto.id);
    }

    // -----------------------------------------------------------------------
    // remove
    // -----------------------------------------------------------------------

    #[test]
    fn test_remove() {
        let mut ctx = TestContext::new();
        let created = create_one(&mut ctx);
        remove(&ctx.db, &ctx.hub, &created.id).unwrap();
        assert!(get(&ctx.db, &created.id).unwrap().is_none());
    }

    // -----------------------------------------------------------------------
    // remove_multi
    // -----------------------------------------------------------------------

    #[test]
    fn test_remove_multi() {
        let mut ctx = TestContext::new();
        let a = create_one(&mut ctx);
        remove_multi(&ctx.db, &ctx.hub, &[a.id]).unwrap();
        assert!(get(&ctx.db, &a.id).unwrap().is_none());
    }

    // -----------------------------------------------------------------------
    // relationship: get empty
    // -----------------------------------------------------------------------

    #[test]
    fn test_get_relationship_default() {
        let mut ctx = TestContext::new();
        let created = create_one(&mut ctx);
        let rel_ids =
            get_relationship(&ctx.db, &created.id, &RootRelationshipField::Document).unwrap();
        // Root.document is a OneToOne strong relationship that defaults to EntityId 0
        assert_eq!(rel_ids.len(), 1);
    }

    // -----------------------------------------------------------------------
    // relationship: count with default
    // -----------------------------------------------------------------------

    #[test]
    fn test_get_relationship_count_default() {
        let mut ctx = TestContext::new();
        let created = create_one(&mut ctx);
        let count =
            get_relationship_count(&ctx.db, &created.id, &RootRelationshipField::Document).unwrap();
        // OneToOne relationship initialized with default EntityId
        assert_eq!(count, 1);
    }
}