qleany-direct-access 1.8.0

Entity CRUD access for Qleany
Documentation
// Generated by Qleany v1.7.0 from entity_controller.tera

use super::{
    dtos::{CreateSystemDto, SystemDto, UpdateSystemDto},
    units_of_work::{SystemReadUoWFactory, SystemWriteUoWFactory},
};
use crate::SystemRelationshipDto;
use anyhow::{Ok, Result};
use common::direct_access::system::SystemRelationshipField;
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: &CreateSystemDto,
) -> Result<SystemDto> {
    let uow_factory = SystemWriteUoWFactory::new(db_context, event_hub);
    let mut uc = use_cases::CreateOrphanUseCase::new(uow_factory);
    let entity_in: common::entities::System = entity.into();
    let result = uc.execute(&entity_in)?;
    Ok(result.into())
}

pub fn create_orphan_multi(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    entities: &[CreateSystemDto],
) -> Result<Vec<SystemDto>> {
    let uow_factory = SystemWriteUoWFactory::new(db_context, event_hub);
    let entities_in: Vec<common::entities::System> =
        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 create(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    entity: &CreateSystemDto,
    owner_id: EntityId,
    index: i32,
) -> Result<SystemDto> {
    let uow_factory = SystemWriteUoWFactory::new(db_context, event_hub);
    let entity_in: common::entities::System = entity.into();
    let mut uc = use_cases::CreateUseCase::new(uow_factory);
    let result = uc.execute(&entity_in, owner_id, index)?;
    Ok(result.into())
}

pub fn create_multi(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    entities: &[CreateSystemDto],
    owner_id: EntityId,
    index: i32,
) -> Result<Vec<SystemDto>> {
    let uow_factory = SystemWriteUoWFactory::new(db_context, event_hub);
    let entities_in: Vec<common::entities::System> =
        entities.iter().map(|dto| dto.into()).collect();
    let mut uc = use_cases::CreateUseCase::new(uow_factory);
    let result = uc.execute_multi(&entities_in, owner_id, index)?;
    Ok(result.into_iter().map(|e| e.into()).collect())
}

pub fn get(db_context: &DbContext, id: &EntityId) -> Result<Option<SystemDto>> {
    let uow_factory = SystemReadUoWFactory::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<SystemDto>> {
    let uow_factory = SystemReadUoWFactory::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<SystemDto>>> {
    let uow_factory = SystemReadUoWFactory::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: &UpdateSystemDto,
) -> Result<SystemDto> {
    let uow_factory = SystemWriteUoWFactory::new(db_context, event_hub);
    let entity_in: common::entities::System = 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: &[UpdateSystemDto],
) -> Result<Vec<SystemDto>> {
    let uow_factory = SystemWriteUoWFactory::new(db_context, event_hub);
    let entities_in: Vec<common::entities::System> =
        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: &SystemDto,
) -> Result<SystemDto> {
    let uow_factory = SystemWriteUoWFactory::new(db_context, event_hub);
    let entity_in: common::entities::System = 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: &[SystemDto],
) -> Result<Vec<SystemDto>> {
    let uow_factory = SystemWriteUoWFactory::new(db_context, event_hub);
    let entities_in: Vec<common::entities::System> =
        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 = SystemWriteUoWFactory::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 = SystemWriteUoWFactory::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: &SystemRelationshipField,
) -> Result<Vec<EntityId>> {
    let uow_factory = SystemReadUoWFactory::new(db_context);
    let uc = use_cases::GetRelationshipUseCase::<SystemRelationshipField, _>::new(uow_factory);
    uc.execute(id, field)
}

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

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

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

pub fn set_relationship(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    dto: &SystemRelationshipDto,
) -> Result<()> {
    let uow_factory = SystemWriteUoWFactory::new(db_context, event_hub);
    let mut uc = use_cases::SetRelationshipUseCase::<SystemRelationshipField, _>::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: &SystemRelationshipField,
    ids_to_move: &[EntityId],
    new_index: i32,
) -> Result<Vec<EntityId>> {
    let uow_factory = SystemWriteUoWFactory::new(db_context, event_hub);
    let mut uc = use_cases::MoveRelationshipUseCase::<SystemRelationshipField, _>::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 crate::root::dtos::CreateRootDto;
    use crate::root::root_controller;
    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 }
        }
    }

    /// Build the ownership chain and return the direct owner's id.
    fn create_owner_chain(ctx: &mut TestContext) -> EntityId {
        let root =
            root_controller::create_orphan(&ctx.db, &ctx.hub, &CreateRootDto::default()).unwrap();
        root.id
    }

    /// Create an entity using create_orphan.
    fn create_one(ctx: &mut TestContext) -> SystemDto {
        create_orphan(&ctx.db, &ctx.hub, &CreateSystemDto::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: UpdateSystemDto = 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());
    }

    // -----------------------------------------------------------------------
    // create with owner
    // -----------------------------------------------------------------------

    #[test]
    fn test_create_with_owner() {
        let mut ctx = TestContext::new();
        let owner_id = create_owner_chain(&mut ctx);
        let created = create(&ctx.db, &ctx.hub, &CreateSystemDto::default(), owner_id, -1).unwrap();
        assert!(created.id > 0);
        let fetched = get(&ctx.db, &created.id).unwrap();
        assert!(fetched.is_some());
    }

    // -----------------------------------------------------------------------
    // relationship: get default
    // -----------------------------------------------------------------------

    #[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, &SystemRelationshipField::Files).unwrap();
        assert!(rel_ids.is_empty());
    }

    // -----------------------------------------------------------------------
    // relationship: count 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, &SystemRelationshipField::Files).unwrap();
        assert_eq!(count, 0);
    }
}