1use std::fmt::Display;
4
5use crate::{
6 database::transactions::Transaction,
7 direct_access::repository_factory,
8 entities::UserInterface,
9 event::{DirectAccessEntity, EntityEvent, Event, EventBuffer, Origin},
10 snapshot::EntityTreeSnapshot,
11 types::EntityId,
12};
13
14use crate::direct_access::workspace::WorkspaceRelationshipField;
15use crate::error::RepositoryError;
16use serde::{Deserialize, Serialize};
17
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub enum UserInterfaceRelationshipField {}
20
21impl Display for UserInterfaceRelationshipField {
22 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
23 write!(f, "{:?}", self)
24 }
25}
26
27pub trait UserInterfaceTable {
28 fn create(&mut self, entity: &UserInterface) -> Result<UserInterface, RepositoryError>;
29 fn create_multi(
30 &mut self,
31 entities: &[UserInterface],
32 ) -> Result<Vec<UserInterface>, RepositoryError>;
33 fn get(&self, id: &EntityId) -> Result<Option<UserInterface>, RepositoryError>;
34 fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<UserInterface>>, RepositoryError>;
35 fn get_all(&self) -> Result<Vec<UserInterface>, RepositoryError>;
36 fn update(&mut self, entity: &UserInterface) -> Result<UserInterface, RepositoryError>;
37 fn update_multi(
38 &mut self,
39 entities: &[UserInterface],
40 ) -> Result<Vec<UserInterface>, RepositoryError>;
41 fn update_with_relationships(
42 &mut self,
43 entity: &UserInterface,
44 ) -> Result<UserInterface, RepositoryError>;
45 fn update_with_relationships_multi(
46 &mut self,
47 entities: &[UserInterface],
48 ) -> Result<Vec<UserInterface>, RepositoryError>;
49 fn remove(&mut self, id: &EntityId) -> Result<(), RepositoryError>;
50 fn remove_multi(&mut self, ids: &[EntityId]) -> Result<(), RepositoryError>;
51}
52
53pub trait UserInterfaceTableRO {
54 fn get(&self, id: &EntityId) -> Result<Option<UserInterface>, RepositoryError>;
55 fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<UserInterface>>, RepositoryError>;
56 fn get_all(&self) -> Result<Vec<UserInterface>, RepositoryError>;
57}
58
59pub struct UserInterfaceRepository<'a> {
60 table: Box<dyn UserInterfaceTable + 'a>,
61 transaction: &'a Transaction,
62}
63
64impl<'a> UserInterfaceRepository<'a> {
65 pub fn new(table: Box<dyn UserInterfaceTable + 'a>, transaction: &'a Transaction) -> Self {
66 UserInterfaceRepository { table, transaction }
67 }
68
69 pub fn create_orphan(
70 &mut self,
71 event_buffer: &mut EventBuffer,
72 entity: &UserInterface,
73 ) -> Result<UserInterface, RepositoryError> {
74 let new = self.table.create(entity)?;
75 event_buffer.push(Event {
76 origin: Origin::DirectAccess(DirectAccessEntity::UserInterface(EntityEvent::Created)),
77 ids: vec![new.id],
78 data: None,
79 });
80 Ok(new)
81 }
82
83 pub fn create_orphan_multi(
84 &mut self,
85 event_buffer: &mut EventBuffer,
86 entities: &[UserInterface],
87 ) -> Result<Vec<UserInterface>, RepositoryError> {
88 let new_entities = self.table.create_multi(entities)?;
89 event_buffer.push(Event {
90 origin: Origin::DirectAccess(DirectAccessEntity::UserInterface(EntityEvent::Created)),
91 ids: new_entities.iter().map(|e| e.id).collect(),
92 data: None,
93 });
94 Ok(new_entities)
95 }
96 pub fn create(
97 &mut self,
98 event_buffer: &mut EventBuffer,
99 entity: &UserInterface,
100 owner_id: EntityId,
101 _index: i32,
102 ) -> Result<UserInterface, RepositoryError> {
103 let new = self.table.create(entity)?;
104 let created_id = new.id;
105
106 let mut relationship_ids = self.get_relationships_from_owner(&owner_id)?;
107 if relationship_ids.is_empty() {
108 relationship_ids = vec![created_id];
109 } else {
110 self.remove_multi(event_buffer, &relationship_ids)?;
112 relationship_ids = vec![created_id];
113 }
114
115 self.set_relationships_in_owner(event_buffer, &owner_id, &relationship_ids)?;
116 event_buffer.push(Event {
117 origin: Origin::DirectAccess(DirectAccessEntity::UserInterface(EntityEvent::Created)),
118 ids: vec![created_id],
119 data: None,
120 });
121 Ok(new)
122 }
123
124 pub fn create_multi(
125 &mut self,
126 event_buffer: &mut EventBuffer,
127 entities: &[UserInterface],
128 owner_id: EntityId,
129 _index: i32,
130 ) -> Result<Vec<UserInterface>, RepositoryError> {
131 let new_entities = self.table.create_multi(entities)?;
132 let created_ids: Vec<EntityId> = new_entities.iter().map(|e| e.id).collect();
133
134 let mut relationship_ids = self.get_relationships_from_owner(&owner_id)?;
135 if relationship_ids.is_empty() {
136 relationship_ids = created_ids.clone();
137 } else {
138 self.remove_multi(event_buffer, &relationship_ids)?;
139 relationship_ids = created_ids.clone();
140 }
141
142 self.set_relationships_in_owner(event_buffer, &owner_id, &relationship_ids)?;
143 event_buffer.push(Event {
144 origin: Origin::DirectAccess(DirectAccessEntity::UserInterface(EntityEvent::Created)),
145 ids: created_ids,
146 data: None,
147 });
148 Ok(new_entities)
149 }
150
151 pub fn get(&self, id: &EntityId) -> Result<Option<UserInterface>, RepositoryError> {
152 self.table.get(id)
153 }
154 pub fn get_multi(
155 &self,
156 ids: &[EntityId],
157 ) -> Result<Vec<Option<UserInterface>>, RepositoryError> {
158 self.table.get_multi(ids)
159 }
160 pub fn get_all(&self) -> Result<Vec<UserInterface>, RepositoryError> {
161 self.table.get_all()
162 }
163
164 pub fn update(
165 &mut self,
166 event_buffer: &mut EventBuffer,
167 entity: &UserInterface,
168 ) -> Result<UserInterface, RepositoryError> {
169 let updated = self.table.update(entity)?;
170 event_buffer.push(Event {
171 origin: Origin::DirectAccess(DirectAccessEntity::UserInterface(EntityEvent::Updated)),
172 ids: vec![updated.id],
173 data: None,
174 });
175 Ok(updated)
176 }
177
178 pub fn update_multi(
179 &mut self,
180 event_buffer: &mut EventBuffer,
181 entities: &[UserInterface],
182 ) -> Result<Vec<UserInterface>, RepositoryError> {
183 let updated = self.table.update_multi(entities)?;
184 event_buffer.push(Event {
185 origin: Origin::DirectAccess(DirectAccessEntity::UserInterface(EntityEvent::Updated)),
186 ids: updated.iter().map(|e| e.id).collect(),
187 data: None,
188 });
189 Ok(updated)
190 }
191
192 pub fn update_with_relationships(
193 &mut self,
194 event_buffer: &mut EventBuffer,
195 entity: &UserInterface,
196 ) -> Result<UserInterface, RepositoryError> {
197 let updated = self.table.update_with_relationships(entity)?;
198 event_buffer.push(Event {
199 origin: Origin::DirectAccess(DirectAccessEntity::UserInterface(EntityEvent::Updated)),
200 ids: vec![updated.id],
201 data: None,
202 });
203 Ok(updated)
204 }
205
206 pub fn update_with_relationships_multi(
207 &mut self,
208 event_buffer: &mut EventBuffer,
209 entities: &[UserInterface],
210 ) -> Result<Vec<UserInterface>, RepositoryError> {
211 let updated = self.table.update_with_relationships_multi(entities)?;
212 event_buffer.push(Event {
213 origin: Origin::DirectAccess(DirectAccessEntity::UserInterface(EntityEvent::Updated)),
214 ids: updated.iter().map(|e| e.id).collect(),
215 data: None,
216 });
217 Ok(updated)
218 }
219
220 pub fn remove(
221 &mut self,
222 event_buffer: &mut EventBuffer,
223 id: &EntityId,
224 ) -> Result<(), RepositoryError> {
225 let _entity = match self.table.get(id)? {
226 Some(e) => e,
227 None => return Ok(()),
228 };
229 let affected_owner_ids: Vec<EntityId> = {
235 let owner_repo =
236 repository_factory::write::create_workspace_repository(self.transaction)?;
237 owner_repo
238 .get_relationships_from_right_ids(
239 &WorkspaceRelationshipField::UserInterface,
240 &[*id],
241 )?
242 .into_iter()
243 .map(|(owner_id, _)| owner_id)
244 .collect()
245 };
246 let mut owner_rel_before: std::collections::HashMap<EntityId, Vec<EntityId>> =
248 std::collections::HashMap::new();
249 for owner_id in &affected_owner_ids {
250 owner_rel_before.insert(*owner_id, self.get_relationships_from_owner(owner_id)?);
251 }
252
253 self.table.remove(id)?;
255 event_buffer.push(Event {
256 origin: Origin::DirectAccess(DirectAccessEntity::UserInterface(EntityEvent::Removed)),
257 ids: vec![*id],
258 data: None,
259 });
260 for owner_id in &affected_owner_ids {
262 if let Some(rel_ids) = owner_rel_before.get(owner_id) {
263 let updated: Vec<EntityId> =
264 rel_ids.iter().copied().filter(|rid| *rid != *id).collect();
265 self.set_relationships_in_owner(event_buffer, owner_id, &updated)?;
266 }
267 }
268
269 Ok(())
270 }
271
272 pub fn remove_multi(
273 &mut self,
274 event_buffer: &mut EventBuffer,
275 ids: &[EntityId],
276 ) -> Result<(), RepositoryError> {
277 let entities = self.table.get_multi(ids)?;
278 if entities.is_empty() || entities.iter().all(|e| e.is_none()) {
279 return Ok(());
280 }
281
282 let affected_owner_ids: Vec<EntityId> = {
288 let owner_repo =
289 repository_factory::write::create_workspace_repository(self.transaction)?;
290 owner_repo
291 .get_relationships_from_right_ids(&WorkspaceRelationshipField::UserInterface, ids)?
292 .into_iter()
293 .map(|(owner_id, _)| owner_id)
294 .collect()
295 };
296 let mut owner_rel_before: std::collections::HashMap<EntityId, Vec<EntityId>> =
298 std::collections::HashMap::new();
299 for owner_id in &affected_owner_ids {
300 owner_rel_before.insert(*owner_id, self.get_relationships_from_owner(owner_id)?);
301 }
302
303 self.table.remove_multi(ids)?;
304 event_buffer.push(Event {
305 origin: Origin::DirectAccess(DirectAccessEntity::UserInterface(EntityEvent::Removed)),
306 ids: ids.into(),
307 data: None,
308 });
309 {
311 let removed_set: std::collections::HashSet<EntityId> = ids.iter().copied().collect();
312 for owner_id in &affected_owner_ids {
313 if let Some(rel_ids) = owner_rel_before.get(owner_id) {
314 let updated: Vec<EntityId> = rel_ids
315 .iter()
316 .copied()
317 .filter(|rid| !removed_set.contains(rid))
318 .collect();
319 self.set_relationships_in_owner(event_buffer, owner_id, &updated)?;
320 }
321 }
322 }
323
324 Ok(())
325 }
326 pub fn get_relationships_from_owner(
327 &self,
328 owner_id: &EntityId,
329 ) -> Result<Vec<EntityId>, RepositoryError> {
330 let repo = repository_factory::write::create_workspace_repository(self.transaction)?;
331 repo.get_relationship(owner_id, &WorkspaceRelationshipField::UserInterface)
332 }
333
334 pub fn set_relationships_in_owner(
335 &mut self,
336 event_buffer: &mut EventBuffer,
337 owner_id: &EntityId,
338 ids: &[EntityId],
339 ) -> Result<(), RepositoryError> {
340 let mut repo = repository_factory::write::create_workspace_repository(self.transaction)?;
341 repo.set_relationship(
342 event_buffer,
343 owner_id,
344 &WorkspaceRelationshipField::UserInterface,
345 ids,
346 )
347 }
348
349 pub fn snapshot(&self, _ids: &[EntityId]) -> Result<EntityTreeSnapshot, RepositoryError> {
350 let store_snap = self.transaction.snapshot_store();
351 Ok(EntityTreeSnapshot {
352 store_snapshot: Some(store_snap),
353 })
354 }
355
356 pub fn restore(
357 &mut self,
358 event_buffer: &mut EventBuffer,
359 snap: &EntityTreeSnapshot,
360 ) -> Result<(), RepositoryError> {
361 let store_snap = snap
362 .store_snapshot
363 .as_ref()
364 .ok_or_else(|| RepositoryError::Serialization("missing store snapshot".into()))?;
365 self.transaction.restore_store(store_snap);
366
367 let store = self.transaction.get_store();
368
369 let mut emit = |entity: DirectAccessEntity, ids: Vec<EntityId>| {
370 if !ids.is_empty() {
371 event_buffer.push(Event {
372 origin: Origin::DirectAccess(entity),
373 ids,
374 data: None,
375 });
376 }
377 };
378
379 let user_interface_ids: Vec<_> = store
381 .user_interfaces
382 .read()
383 .unwrap()
384 .keys()
385 .copied()
386 .collect();
387 emit(
388 DirectAccessEntity::UserInterface(EntityEvent::Created),
389 user_interface_ids.clone(),
390 );
391
392 Ok(())
395 }
396}
397
398pub struct UserInterfaceRepositoryRO<'a> {
399 table: Box<dyn UserInterfaceTableRO + 'a>,
400}
401impl<'a> UserInterfaceRepositoryRO<'a> {
402 pub fn new(table: Box<dyn UserInterfaceTableRO + 'a>) -> Self {
403 UserInterfaceRepositoryRO { table }
404 }
405 pub fn get(&self, id: &EntityId) -> Result<Option<UserInterface>, RepositoryError> {
406 self.table.get(id)
407 }
408 pub fn get_multi(
409 &self,
410 ids: &[EntityId],
411 ) -> Result<Vec<Option<UserInterface>>, RepositoryError> {
412 self.table.get_multi(ids)
413 }
414 pub fn get_all(&self) -> Result<Vec<UserInterface>, RepositoryError> {
415 self.table.get_all()
416 }
417}