Skip to main content

text_document_common/direct_access/block/
block_repository.rs

1// Generated by Qleany v1.5.0 from common_entity_repository.tera
2
3use std::fmt::Display;
4
5use crate::{
6    database::transactions::Transaction,
7    direct_access::repository_factory,
8    entities::Block,
9    event::{DirectAccessEntity, EntityEvent, Event, EventBuffer, Origin},
10    snapshot::{EntityTreeSnapshot, TableLevelSnapshot},
11    types::EntityId,
12};
13
14use crate::direct_access::frame::FrameRelationshipField;
15use crate::error::RepositoryError;
16use serde::{Deserialize, Serialize};
17
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub enum BlockRelationshipField {
20    Elements,
21    List,
22}
23
24impl Display for BlockRelationshipField {
25    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
26        write!(f, "{:?}", self)
27    }
28}
29
30pub trait BlockTable {
31    fn create(&mut self, entity: &Block) -> Result<Block, RepositoryError>;
32    fn create_multi(&mut self, entities: &[Block]) -> Result<Vec<Block>, RepositoryError>;
33    fn get(&self, id: &EntityId) -> Result<Option<Block>, RepositoryError>;
34    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Block>>, RepositoryError>;
35    fn get_all(&self) -> Result<Vec<Block>, RepositoryError>;
36    fn update(&mut self, entity: &Block) -> Result<Block, RepositoryError>;
37    fn update_multi(&mut self, entities: &[Block]) -> Result<Vec<Block>, RepositoryError>;
38    fn update_with_relationships(&mut self, entity: &Block) -> Result<Block, RepositoryError>;
39    fn update_with_relationships_multi(
40        &mut self,
41        entities: &[Block],
42    ) -> Result<Vec<Block>, RepositoryError>;
43    fn remove(&mut self, id: &EntityId) -> Result<(), RepositoryError>;
44    fn remove_multi(&mut self, ids: &[EntityId]) -> Result<(), RepositoryError>;
45    fn get_relationship(
46        &self,
47        id: &EntityId,
48        field: &BlockRelationshipField,
49    ) -> Result<Vec<EntityId>, RepositoryError>;
50    fn get_relationship_many(
51        &self,
52        ids: &[EntityId],
53        field: &BlockRelationshipField,
54    ) -> Result<std::collections::HashMap<EntityId, Vec<EntityId>>, RepositoryError>;
55    fn get_relationship_count(
56        &self,
57        id: &EntityId,
58        field: &BlockRelationshipField,
59    ) -> Result<usize, RepositoryError>;
60    fn get_relationship_in_range(
61        &self,
62        id: &EntityId,
63        field: &BlockRelationshipField,
64        offset: usize,
65        limit: usize,
66    ) -> Result<Vec<EntityId>, RepositoryError>;
67    fn get_relationships_from_right_ids(
68        &self,
69        field: &BlockRelationshipField,
70        right_ids: &[EntityId],
71    ) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError>;
72    fn set_relationship_multi(
73        &mut self,
74        field: &BlockRelationshipField,
75        relationships: Vec<(EntityId, Vec<EntityId>)>,
76    ) -> Result<(), RepositoryError>;
77    fn set_relationship(
78        &mut self,
79        id: &EntityId,
80        field: &BlockRelationshipField,
81        right_ids: &[EntityId],
82    ) -> Result<(), RepositoryError>;
83    fn move_relationship_ids(
84        &mut self,
85        id: &EntityId,
86        field: &BlockRelationshipField,
87        ids_to_move: &[EntityId],
88        new_index: i32,
89    ) -> Result<Vec<EntityId>, RepositoryError>;
90    fn snapshot_rows(&self, ids: &[EntityId]) -> Result<TableLevelSnapshot, RepositoryError>;
91    fn restore_rows(&mut self, snap: &TableLevelSnapshot) -> Result<(), RepositoryError>;
92}
93
94pub trait BlockTableRO {
95    fn get(&self, id: &EntityId) -> Result<Option<Block>, RepositoryError>;
96    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Block>>, RepositoryError>;
97    fn get_all(&self) -> Result<Vec<Block>, RepositoryError>;
98    fn get_relationship(
99        &self,
100        id: &EntityId,
101        field: &BlockRelationshipField,
102    ) -> Result<Vec<EntityId>, RepositoryError>;
103    fn get_relationship_many(
104        &self,
105        ids: &[EntityId],
106        field: &BlockRelationshipField,
107    ) -> Result<std::collections::HashMap<EntityId, Vec<EntityId>>, RepositoryError>;
108    fn get_relationship_count(
109        &self,
110        id: &EntityId,
111        field: &BlockRelationshipField,
112    ) -> Result<usize, RepositoryError>;
113    fn get_relationship_in_range(
114        &self,
115        id: &EntityId,
116        field: &BlockRelationshipField,
117        offset: usize,
118        limit: usize,
119    ) -> Result<Vec<EntityId>, RepositoryError>;
120    fn get_relationships_from_right_ids(
121        &self,
122        field: &BlockRelationshipField,
123        right_ids: &[EntityId],
124    ) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError>;
125}
126
127pub struct BlockRepository<'a> {
128    redb_table: Box<dyn BlockTable + 'a>,
129    transaction: &'a Transaction,
130}
131
132impl<'a> BlockRepository<'a> {
133    pub fn new(redb_table: Box<dyn BlockTable + 'a>, transaction: &'a Transaction) -> Self {
134        BlockRepository {
135            redb_table,
136            transaction,
137        }
138    }
139
140    pub fn create_orphan(
141        &mut self,
142        event_buffer: &mut EventBuffer,
143        entity: &Block,
144    ) -> Result<Block, RepositoryError> {
145        let new = self.redb_table.create(entity)?;
146        event_buffer.push(Event {
147            origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Created)),
148            ids: vec![new.id],
149            data: None,
150        });
151        Ok(new)
152    }
153
154    pub fn create_orphan_multi(
155        &mut self,
156        event_buffer: &mut EventBuffer,
157        entities: &[Block],
158    ) -> Result<Vec<Block>, RepositoryError> {
159        let new_entities = self.redb_table.create_multi(entities)?;
160        event_buffer.push(Event {
161            origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Created)),
162            ids: new_entities.iter().map(|e| e.id).collect(),
163            data: None,
164        });
165        Ok(new_entities)
166    }
167    pub fn create(
168        &mut self,
169        event_buffer: &mut EventBuffer,
170        entity: &Block,
171        owner_id: EntityId,
172        index: i32,
173    ) -> Result<Block, RepositoryError> {
174        let new = self.redb_table.create(entity)?;
175        let created_id = new.id;
176
177        let mut relationship_ids = self.get_relationships_from_owner(&owner_id)?;
178        // Insert at index
179        if index >= 0 && (index as usize) < relationship_ids.len() {
180            relationship_ids.insert(index as usize, created_id);
181        } else {
182            relationship_ids.push(created_id);
183        }
184
185        self.set_relationships_in_owner(event_buffer, &owner_id, &relationship_ids)?;
186        event_buffer.push(Event {
187            origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Created)),
188            ids: vec![created_id],
189            data: None,
190        });
191        Ok(new)
192    }
193
194    pub fn create_multi(
195        &mut self,
196        event_buffer: &mut EventBuffer,
197        entities: &[Block],
198        owner_id: EntityId,
199        index: i32,
200    ) -> Result<Vec<Block>, RepositoryError> {
201        let new_entities = self.redb_table.create_multi(entities)?;
202        let created_ids: Vec<EntityId> = new_entities.iter().map(|e| e.id).collect();
203
204        let mut relationship_ids = self.get_relationships_from_owner(&owner_id)?;
205        if index >= 0 && (index as usize) < relationship_ids.len() {
206            for (i, id) in created_ids.iter().enumerate() {
207                relationship_ids.insert(index as usize + i, *id);
208            }
209        } else {
210            relationship_ids.extend(created_ids.iter());
211        }
212
213        self.set_relationships_in_owner(event_buffer, &owner_id, &relationship_ids)?;
214        event_buffer.push(Event {
215            origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Created)),
216            ids: created_ids,
217            data: None,
218        });
219        Ok(new_entities)
220    }
221
222    pub fn get(&self, id: &EntityId) -> Result<Option<Block>, RepositoryError> {
223        self.redb_table.get(id)
224    }
225    pub fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Block>>, RepositoryError> {
226        self.redb_table.get_multi(ids)
227    }
228    pub fn get_all(&self) -> Result<Vec<Block>, RepositoryError> {
229        self.redb_table.get_all()
230    }
231
232    pub fn update(
233        &mut self,
234        event_buffer: &mut EventBuffer,
235        entity: &Block,
236    ) -> Result<Block, RepositoryError> {
237        let updated = self.redb_table.update(entity)?;
238        event_buffer.push(Event {
239            origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Updated)),
240            ids: vec![updated.id],
241            data: None,
242        });
243        Ok(updated)
244    }
245
246    pub fn update_multi(
247        &mut self,
248        event_buffer: &mut EventBuffer,
249        entities: &[Block],
250    ) -> Result<Vec<Block>, RepositoryError> {
251        let updated = self.redb_table.update_multi(entities)?;
252        event_buffer.push(Event {
253            origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Updated)),
254            ids: updated.iter().map(|e| e.id).collect(),
255            data: None,
256        });
257        Ok(updated)
258    }
259
260    pub fn update_with_relationships(
261        &mut self,
262        event_buffer: &mut EventBuffer,
263        entity: &Block,
264    ) -> Result<Block, RepositoryError> {
265        let updated = self.redb_table.update_with_relationships(entity)?;
266        event_buffer.push(Event {
267            origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Updated)),
268            ids: vec![updated.id],
269            data: None,
270        });
271        Ok(updated)
272    }
273
274    pub fn update_with_relationships_multi(
275        &mut self,
276        event_buffer: &mut EventBuffer,
277        entities: &[Block],
278    ) -> Result<Vec<Block>, RepositoryError> {
279        let updated = self.redb_table.update_with_relationships_multi(entities)?;
280        event_buffer.push(Event {
281            origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Updated)),
282            ids: updated.iter().map(|e| e.id).collect(),
283            data: None,
284        });
285        Ok(updated)
286    }
287
288    pub fn remove(
289        &mut self,
290        event_buffer: &mut EventBuffer,
291        id: &EntityId,
292    ) -> Result<(), RepositoryError> {
293        let entity = match self.redb_table.get(id)? {
294            Some(e) => e,
295            None => return Ok(()),
296        };
297        // get all strong forward relationship fields
298
299        let elements = entity.elements.clone();
300
301        // remove all strong relationships, initiating a cascade remove
302
303        repository_factory::write::create_inline_element_repository(self.transaction)
304            .remove_multi(event_buffer, &elements)?;
305        // Before removal, find which owner(s) reference this entity
306        let affected_owner_ids: Vec<EntityId> = {
307            let owner_repo = repository_factory::write::create_frame_repository(self.transaction);
308            owner_repo
309                .get_relationships_from_right_ids(&FrameRelationshipField::Blocks, &[*id])?
310                .into_iter()
311                .map(|(owner_id, _)| owner_id)
312                .collect()
313        };
314        // Save each owner's current relationship IDs (properly ordered via get_relationships_from_owner)
315        let mut owner_rel_before: std::collections::HashMap<EntityId, Vec<EntityId>> =
316            std::collections::HashMap::new();
317        for owner_id in &affected_owner_ids {
318            owner_rel_before.insert(*owner_id, self.get_relationships_from_owner(owner_id)?);
319        }
320
321        // remove entity
322        self.redb_table.remove(id)?;
323        event_buffer.push(Event {
324            origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Removed)),
325            ids: vec![*id],
326            data: None,
327        });
328        // Update each affected owner's relationship to exclude removed ID (emits Updated event)
329        for owner_id in &affected_owner_ids {
330            if let Some(rel_ids) = owner_rel_before.get(owner_id) {
331                let updated: Vec<EntityId> =
332                    rel_ids.iter().copied().filter(|rid| *rid != *id).collect();
333                self.set_relationships_in_owner(event_buffer, owner_id, &updated)?;
334            }
335        }
336
337        Ok(())
338    }
339
340    pub fn remove_multi(
341        &mut self,
342        event_buffer: &mut EventBuffer,
343        ids: &[EntityId],
344    ) -> Result<(), RepositoryError> {
345        let entities = self.redb_table.get_multi(ids)?;
346        if entities.is_empty() || entities.iter().all(|e| e.is_none()) {
347            return Ok(());
348        }
349
350        // get all strong forward relationship fields
351
352        let mut elements_ids: Vec<EntityId> = entities
353            .iter()
354            .flat_map(|entity| entity.as_ref().map(|entity| entity.elements.clone()))
355            .flatten()
356            .collect();
357        // remove duplicates
358        elements_ids.sort();
359        elements_ids.dedup();
360
361        // remove all strong relationships, initiating a cascade remove
362
363        repository_factory::write::create_inline_element_repository(self.transaction)
364            .remove_multi(event_buffer, &elements_ids)?;
365        // Before removal, find which owner(s) reference these entities
366        let affected_owner_ids: Vec<EntityId> = {
367            let owner_repo = repository_factory::write::create_frame_repository(self.transaction);
368            owner_repo
369                .get_relationships_from_right_ids(&FrameRelationshipField::Blocks, ids)?
370                .into_iter()
371                .map(|(owner_id, _)| owner_id)
372                .collect()
373        };
374        // Save each owner's current relationship IDs (properly ordered via get_relationships_from_owner)
375        let mut owner_rel_before: std::collections::HashMap<EntityId, Vec<EntityId>> =
376            std::collections::HashMap::new();
377        for owner_id in &affected_owner_ids {
378            owner_rel_before.insert(*owner_id, self.get_relationships_from_owner(owner_id)?);
379        }
380
381        self.redb_table.remove_multi(ids)?;
382        event_buffer.push(Event {
383            origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Removed)),
384            ids: ids.into(),
385            data: None,
386        });
387        // Update each affected owner's relationship to exclude removed IDs (emits Updated event)
388        {
389            let removed_set: std::collections::HashSet<EntityId> = ids.iter().copied().collect();
390            for owner_id in &affected_owner_ids {
391                if let Some(rel_ids) = owner_rel_before.get(owner_id) {
392                    let updated: Vec<EntityId> = rel_ids
393                        .iter()
394                        .copied()
395                        .filter(|rid| !removed_set.contains(rid))
396                        .collect();
397                    self.set_relationships_in_owner(event_buffer, owner_id, &updated)?;
398                }
399            }
400        }
401
402        Ok(())
403    }
404    pub fn get_relationship(
405        &self,
406        id: &EntityId,
407        field: &BlockRelationshipField,
408    ) -> Result<Vec<EntityId>, RepositoryError> {
409        self.redb_table.get_relationship(id, field)
410    }
411    pub fn get_relationship_many(
412        &self,
413        ids: &[EntityId],
414        field: &BlockRelationshipField,
415    ) -> Result<std::collections::HashMap<EntityId, Vec<EntityId>>, RepositoryError> {
416        self.redb_table.get_relationship_many(ids, field)
417    }
418    pub fn get_relationship_count(
419        &self,
420        id: &EntityId,
421        field: &BlockRelationshipField,
422    ) -> Result<usize, RepositoryError> {
423        self.redb_table.get_relationship_count(id, field)
424    }
425    pub fn get_relationship_in_range(
426        &self,
427        id: &EntityId,
428        field: &BlockRelationshipField,
429        offset: usize,
430        limit: usize,
431    ) -> Result<Vec<EntityId>, RepositoryError> {
432        self.redb_table
433            .get_relationship_in_range(id, field, offset, limit)
434    }
435    pub fn get_relationships_from_right_ids(
436        &self,
437        field: &BlockRelationshipField,
438        right_ids: &[EntityId],
439    ) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
440        self.redb_table
441            .get_relationships_from_right_ids(field, right_ids)
442    }
443
444    pub fn set_relationship_multi(
445        &mut self,
446        event_buffer: &mut EventBuffer,
447        field: &BlockRelationshipField,
448        relationships: Vec<(EntityId, Vec<EntityId>)>,
449    ) -> Result<(), RepositoryError> {
450        // Validate that all right_ids exist
451        let all_right_ids: Vec<EntityId> = relationships
452            .iter()
453            .flat_map(|(_, ids)| ids.iter().copied())
454            .collect();
455        if !all_right_ids.is_empty() {
456            match field {
457                BlockRelationshipField::Elements => {
458                    let child_repo = repository_factory::write::create_inline_element_repository(
459                        self.transaction,
460                    );
461                    let found = child_repo.get_multi(&all_right_ids)?;
462                    let missing: Vec<_> = all_right_ids
463                        .iter()
464                        .zip(found.iter())
465                        .filter(|(_, entity)| entity.is_none())
466                        .map(|(id, _)| *id)
467                        .collect();
468                    if !missing.is_empty() {
469                        return Err(RepositoryError::MissingRelationshipTarget {
470                            operation: "set_relationship_multi",
471                            ids: missing,
472                        });
473                    }
474                }
475                BlockRelationshipField::List => {
476                    let child_repo =
477                        repository_factory::write::create_list_repository(self.transaction);
478                    let found = child_repo.get_multi(&all_right_ids)?;
479                    let missing: Vec<_> = all_right_ids
480                        .iter()
481                        .zip(found.iter())
482                        .filter(|(_, entity)| entity.is_none())
483                        .map(|(id, _)| *id)
484                        .collect();
485                    if !missing.is_empty() {
486                        return Err(RepositoryError::MissingRelationshipTarget {
487                            operation: "set_relationship_multi",
488                            ids: missing,
489                        });
490                    }
491                }
492            }
493        }
494        self.redb_table
495            .set_relationship_multi(field, relationships.clone())?;
496        for (left_id, right_ids) in relationships {
497            event_buffer.push(Event {
498                origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Updated)),
499                ids: vec![left_id],
500                data: Some(format!(
501                    "{}:{}",
502                    field,
503                    right_ids
504                        .iter()
505                        .map(|id| id.to_string())
506                        .collect::<Vec<_>>()
507                        .join(",")
508                )),
509            });
510        }
511        Ok(())
512    }
513
514    pub fn set_relationship(
515        &mut self,
516        event_buffer: &mut EventBuffer,
517        id: &EntityId,
518        field: &BlockRelationshipField,
519        right_ids: &[EntityId],
520    ) -> Result<(), RepositoryError> {
521        // Validate that all right_ids exist
522        if !right_ids.is_empty() {
523            match field {
524                BlockRelationshipField::Elements => {
525                    let child_repo = repository_factory::write::create_inline_element_repository(
526                        self.transaction,
527                    );
528                    let found = child_repo.get_multi(right_ids)?;
529                    let missing: Vec<_> = right_ids
530                        .iter()
531                        .zip(found.iter())
532                        .filter(|(_, entity)| entity.is_none())
533                        .map(|(id, _)| *id)
534                        .collect();
535                    if !missing.is_empty() {
536                        return Err(RepositoryError::MissingRelationshipTarget {
537                            operation: "set_relationship",
538                            ids: missing,
539                        });
540                    }
541                }
542                BlockRelationshipField::List => {
543                    let child_repo =
544                        repository_factory::write::create_list_repository(self.transaction);
545                    let found = child_repo.get_multi(right_ids)?;
546                    let missing: Vec<_> = right_ids
547                        .iter()
548                        .zip(found.iter())
549                        .filter(|(_, entity)| entity.is_none())
550                        .map(|(id, _)| *id)
551                        .collect();
552                    if !missing.is_empty() {
553                        return Err(RepositoryError::MissingRelationshipTarget {
554                            operation: "set_relationship",
555                            ids: missing,
556                        });
557                    }
558                }
559            }
560        }
561        self.redb_table.set_relationship(id, field, right_ids)?;
562        event_buffer.push(Event {
563            origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Updated)),
564            ids: vec![*id],
565            data: Some(format!(
566                "{}:{}",
567                field,
568                right_ids
569                    .iter()
570                    .map(|id| id.to_string())
571                    .collect::<Vec<_>>()
572                    .join(",")
573            )),
574        });
575        Ok(())
576    }
577
578    pub fn move_relationship_ids(
579        &mut self,
580        event_buffer: &mut EventBuffer,
581        id: &EntityId,
582        field: &BlockRelationshipField,
583        ids_to_move: &[EntityId],
584        new_index: i32,
585    ) -> Result<Vec<EntityId>, RepositoryError> {
586        let reordered = self
587            .redb_table
588            .move_relationship_ids(id, field, ids_to_move, new_index)?;
589        event_buffer.push(Event {
590            origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Updated)),
591            ids: vec![*id],
592            data: Some(format!(
593                "{}:{}",
594                field,
595                reordered
596                    .iter()
597                    .map(|id| id.to_string())
598                    .collect::<Vec<_>>()
599                    .join(",")
600            )),
601        });
602        Ok(reordered)
603    }
604    pub fn get_relationships_from_owner(
605        &self,
606        owner_id: &EntityId,
607    ) -> Result<Vec<EntityId>, RepositoryError> {
608        let repo = repository_factory::write::create_frame_repository(self.transaction);
609        repo.get_relationship(owner_id, &FrameRelationshipField::Blocks)
610    }
611
612    pub fn set_relationships_in_owner(
613        &mut self,
614        event_buffer: &mut EventBuffer,
615        owner_id: &EntityId,
616        ids: &[EntityId],
617    ) -> Result<(), RepositoryError> {
618        let mut repo = repository_factory::write::create_frame_repository(self.transaction);
619        repo.set_relationship(event_buffer, owner_id, &FrameRelationshipField::Blocks, ids)
620    }
621
622    pub fn snapshot(&self, ids: &[EntityId]) -> Result<EntityTreeSnapshot, RepositoryError> {
623        let table_data = self.redb_table.snapshot_rows(ids)?;
624
625        // Recursively snapshot strong children
626        #[allow(unused_mut)]
627        let mut children = Vec::new();
628
629        {
630            // Extract child IDs from the forward junction snapshot for elements
631            let junction_name = "inline_element_from_block_elements_junction";
632            let child_ids: Vec<EntityId> = table_data
633                .forward_junctions
634                .iter()
635                .filter(|j| j.table_name == junction_name)
636                .flat_map(|j| {
637                    j.entries
638                        .iter()
639                        .flat_map(|(_, right_ids)| right_ids.iter().copied())
640                })
641                .collect();
642            if !child_ids.is_empty() {
643                let child_repo =
644                    repository_factory::write::create_inline_element_repository(self.transaction);
645                children.push(child_repo.snapshot(&child_ids)?);
646            }
647        }
648
649        Ok(EntityTreeSnapshot {
650            table_data,
651            children,
652        })
653    }
654
655    pub fn restore(
656        &mut self,
657        event_buffer: &mut EventBuffer,
658        snap: &EntityTreeSnapshot,
659    ) -> Result<(), RepositoryError> {
660        // Restore children first (bottom-up)
661
662        for child_snap in &snap.children {
663            if child_snap.table_data.entity_rows.table_name == "inline_element" {
664                repository_factory::write::create_inline_element_repository(self.transaction)
665                    .restore(event_buffer, child_snap)?;
666            }
667        }
668
669        // Restore this entity's rows
670        self.redb_table.restore_rows(&snap.table_data)?;
671
672        // Emit Created events for restored entity IDs
673        let restored_ids: Vec<EntityId> = snap
674            .table_data
675            .entity_rows
676            .rows
677            .iter()
678            .map(|(id, _)| *id)
679            .collect();
680        if !restored_ids.is_empty() {
681            event_buffer.push(Event {
682                origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Created)),
683                ids: restored_ids.clone(),
684                data: None,
685            });
686        }
687        // Emit Updated events for restored relationships
688        if !restored_ids.is_empty() {
689            event_buffer.push(Event {
690                origin: Origin::DirectAccess(DirectAccessEntity::Block(EntityEvent::Updated)),
691                ids: restored_ids,
692                data: None,
693            });
694        }
695        Ok(())
696    }
697}
698
699pub struct BlockRepositoryRO<'a> {
700    redb_table: Box<dyn BlockTableRO + 'a>,
701}
702impl<'a> BlockRepositoryRO<'a> {
703    pub fn new(redb_table: Box<dyn BlockTableRO + 'a>) -> Self {
704        BlockRepositoryRO { redb_table }
705    }
706    pub fn get(&self, id: &EntityId) -> Result<Option<Block>, RepositoryError> {
707        self.redb_table.get(id)
708    }
709    pub fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Block>>, RepositoryError> {
710        self.redb_table.get_multi(ids)
711    }
712    pub fn get_all(&self) -> Result<Vec<Block>, RepositoryError> {
713        self.redb_table.get_all()
714    }
715    pub fn get_relationship(
716        &self,
717        id: &EntityId,
718        field: &BlockRelationshipField,
719    ) -> Result<Vec<EntityId>, RepositoryError> {
720        self.redb_table.get_relationship(id, field)
721    }
722    pub fn get_relationship_many(
723        &self,
724        ids: &[EntityId],
725        field: &BlockRelationshipField,
726    ) -> Result<std::collections::HashMap<EntityId, Vec<EntityId>>, RepositoryError> {
727        self.redb_table.get_relationship_many(ids, field)
728    }
729    pub fn get_relationship_count(
730        &self,
731        id: &EntityId,
732        field: &BlockRelationshipField,
733    ) -> Result<usize, RepositoryError> {
734        self.redb_table.get_relationship_count(id, field)
735    }
736    pub fn get_relationship_in_range(
737        &self,
738        id: &EntityId,
739        field: &BlockRelationshipField,
740        offset: usize,
741        limit: usize,
742    ) -> Result<Vec<EntityId>, RepositoryError> {
743        self.redb_table
744            .get_relationship_in_range(id, field, offset, limit)
745    }
746    pub fn get_relationships_from_right_ids(
747        &self,
748        field: &BlockRelationshipField,
749        right_ids: &[EntityId],
750    ) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
751        self.redb_table
752            .get_relationships_from_right_ids(field, right_ids)
753    }
754}