common/direct_access/use_cases/
set_relationship.rs1use super::traits::WriteRelUoWFactory;
4use crate::types::EntityId;
5use crate::undo_redo::UndoRedoCommand;
6use anyhow::Result;
7use std::any::Any;
8use std::collections::VecDeque;
9
10pub struct SetRelationshipUseCase<RF, F: WriteRelUoWFactory<RF>> {
15 uow_factory: F,
16 _phantom: std::marker::PhantomData<RF>,
17}
18
19impl<RF, F: WriteRelUoWFactory<RF>> SetRelationshipUseCase<RF, F> {
20 pub fn new(uow_factory: F) -> Self {
21 SetRelationshipUseCase {
22 uow_factory,
23 _phantom: std::marker::PhantomData,
24 }
25 }
26
27 pub fn execute(&mut self, id: &EntityId, field: &RF, right_ids: &[EntityId]) -> Result<()> {
28 let mut uow = self.uow_factory.create();
29 uow.begin_transaction()?;
30 uow.set_relationship(id, field, right_ids)?;
31 uow.commit()?;
32 Ok(())
33 }
34}
35
36pub struct UndoableSetRelationshipUseCase<RF: Clone, F: WriteRelUoWFactory<RF>> {
41 uow_factory: F,
42 undo_stack: VecDeque<(EntityId, RF, Vec<EntityId>)>,
46 redo_stack: VecDeque<(EntityId, RF, Vec<EntityId>)>,
47}
48
49impl<RF: Clone, F: WriteRelUoWFactory<RF>> UndoableSetRelationshipUseCase<RF, F> {
50 pub fn new(uow_factory: F) -> Self {
51 UndoableSetRelationshipUseCase {
52 uow_factory,
53 undo_stack: VecDeque::new(),
54 redo_stack: VecDeque::new(),
55 }
56 }
57
58 pub fn execute(&mut self, id: &EntityId, field: &RF, right_ids: &[EntityId]) -> Result<()> {
59 let mut uow = self.uow_factory.create();
60 uow.begin_transaction()?;
61 let before = uow.get_relationship(id, field)?;
62 uow.set_relationship(id, field, right_ids)?;
63 uow.commit()?;
64 self.undo_stack.push_back((*id, field.clone(), before));
65 self.redo_stack.clear();
67 Ok(())
68 }
69}
70
71impl<RF: Clone + Send + 'static, F: WriteRelUoWFactory<RF> + Send + 'static> UndoRedoCommand
72 for UndoableSetRelationshipUseCase<RF, F>
73{
74 fn undo(&mut self) -> Result<()> {
75 if let Some((id, field, before)) = self.undo_stack.pop_back() {
76 let mut uow = self.uow_factory.create();
77 uow.begin_transaction()?;
78 let current = uow.get_relationship(&id, &field)?;
80 uow.set_relationship(&id, &field, &before)?;
81 uow.commit()?;
82 self.redo_stack.push_back((id, field, current));
83 }
84 Ok(())
85 }
86
87 fn redo(&mut self) -> Result<()> {
88 if let Some((id, field, right_ids)) = self.redo_stack.pop_back() {
89 let mut uow = self.uow_factory.create();
90 uow.begin_transaction()?;
91 let before = uow.get_relationship(&id, &field)?;
92 uow.set_relationship(&id, &field, &right_ids)?;
93 uow.commit()?;
94 self.undo_stack.push_back((id, field, before));
95 }
96 Ok(())
97 }
98
99 fn as_any(&self) -> &dyn Any {
100 self
101 }
102}