text-document-common 1.4.0

Shared entities, database, events, and undo/redo infrastructure for text-document
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
// Generated by Qleany v1.5.1 from common_entity_repository.tera

use std::fmt::Display;

use crate::{
    database::transactions::Transaction,
    direct_access::repository_factory,
    entities::Root,
    event::{DirectAccessEntity, EntityEvent, Event, EventBuffer, Origin},
    snapshot::EntityTreeSnapshot,
    types::EntityId,
};

use crate::error::RepositoryError;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RootRelationshipField {
    Document,
}

impl Display for RootRelationshipField {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

pub trait RootTable {
    fn create(&mut self, entity: &Root) -> Result<Root, RepositoryError>;
    fn create_multi(&mut self, entities: &[Root]) -> Result<Vec<Root>, RepositoryError>;
    fn get(&self, id: &EntityId) -> Result<Option<Root>, RepositoryError>;
    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Root>>, RepositoryError>;
    fn get_all(&self) -> Result<Vec<Root>, RepositoryError>;
    fn update(&mut self, entity: &Root) -> Result<Root, RepositoryError>;
    fn update_multi(&mut self, entities: &[Root]) -> Result<Vec<Root>, RepositoryError>;
    fn update_with_relationships(&mut self, entity: &Root) -> Result<Root, RepositoryError>;
    fn update_with_relationships_multi(
        &mut self,
        entities: &[Root],
    ) -> Result<Vec<Root>, RepositoryError>;
    fn remove(&mut self, id: &EntityId) -> Result<(), RepositoryError>;
    fn remove_multi(&mut self, ids: &[EntityId]) -> Result<(), RepositoryError>;
    fn get_relationship(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
    ) -> Result<Vec<EntityId>, RepositoryError>;
    fn get_relationship_many(
        &self,
        ids: &[EntityId],
        field: &RootRelationshipField,
    ) -> Result<std::collections::HashMap<EntityId, Vec<EntityId>>, RepositoryError>;
    fn get_relationship_count(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
    ) -> Result<usize, RepositoryError>;
    fn get_relationship_in_range(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
        offset: usize,
        limit: usize,
    ) -> Result<Vec<EntityId>, RepositoryError>;
    fn get_relationships_from_right_ids(
        &self,
        field: &RootRelationshipField,
        right_ids: &[EntityId],
    ) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError>;
    fn set_relationship_multi(
        &mut self,
        field: &RootRelationshipField,
        relationships: Vec<(EntityId, Vec<EntityId>)>,
    ) -> Result<(), RepositoryError>;
    fn set_relationship(
        &mut self,
        id: &EntityId,
        field: &RootRelationshipField,
        right_ids: &[EntityId],
    ) -> Result<(), RepositoryError>;
    fn move_relationship_ids(
        &mut self,
        id: &EntityId,
        field: &RootRelationshipField,
        ids_to_move: &[EntityId],
        new_index: i32,
    ) -> Result<Vec<EntityId>, RepositoryError>;
}

pub trait RootTableRO {
    fn get(&self, id: &EntityId) -> Result<Option<Root>, RepositoryError>;
    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Root>>, RepositoryError>;
    fn get_all(&self) -> Result<Vec<Root>, RepositoryError>;
    fn get_relationship(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
    ) -> Result<Vec<EntityId>, RepositoryError>;
    fn get_relationship_many(
        &self,
        ids: &[EntityId],
        field: &RootRelationshipField,
    ) -> Result<std::collections::HashMap<EntityId, Vec<EntityId>>, RepositoryError>;
    fn get_relationship_count(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
    ) -> Result<usize, RepositoryError>;
    fn get_relationship_in_range(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
        offset: usize,
        limit: usize,
    ) -> Result<Vec<EntityId>, RepositoryError>;
    fn get_relationships_from_right_ids(
        &self,
        field: &RootRelationshipField,
        right_ids: &[EntityId],
    ) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError>;
}

pub struct RootRepository<'a> {
    redb_table: Box<dyn RootTable + 'a>,
    transaction: &'a Transaction,
}

impl<'a> RootRepository<'a> {
    pub fn new(redb_table: Box<dyn RootTable + 'a>, transaction: &'a Transaction) -> Self {
        RootRepository {
            redb_table,
            transaction,
        }
    }

    pub fn create_orphan(
        &mut self,
        event_buffer: &mut EventBuffer,
        entity: &Root,
    ) -> Result<Root, RepositoryError> {
        let new = self.redb_table.create(entity)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::Root(EntityEvent::Created)),
            ids: vec![new.id],
            data: None,
        });
        Ok(new)
    }

    pub fn create_orphan_multi(
        &mut self,
        event_buffer: &mut EventBuffer,
        entities: &[Root],
    ) -> Result<Vec<Root>, RepositoryError> {
        let new_entities = self.redb_table.create_multi(entities)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::Root(EntityEvent::Created)),
            ids: new_entities.iter().map(|e| e.id).collect(),
            data: None,
        });
        Ok(new_entities)
    }

    pub fn get(&self, id: &EntityId) -> Result<Option<Root>, RepositoryError> {
        self.redb_table.get(id)
    }
    pub fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Root>>, RepositoryError> {
        self.redb_table.get_multi(ids)
    }
    pub fn get_all(&self) -> Result<Vec<Root>, RepositoryError> {
        self.redb_table.get_all()
    }

    pub fn update(
        &mut self,
        event_buffer: &mut EventBuffer,
        entity: &Root,
    ) -> Result<Root, RepositoryError> {
        let updated = self.redb_table.update(entity)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::Root(EntityEvent::Updated)),
            ids: vec![updated.id],
            data: None,
        });
        Ok(updated)
    }

    pub fn update_multi(
        &mut self,
        event_buffer: &mut EventBuffer,
        entities: &[Root],
    ) -> Result<Vec<Root>, RepositoryError> {
        let updated = self.redb_table.update_multi(entities)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::Root(EntityEvent::Updated)),
            ids: updated.iter().map(|e| e.id).collect(),
            data: None,
        });
        Ok(updated)
    }

    pub fn update_with_relationships(
        &mut self,
        event_buffer: &mut EventBuffer,
        entity: &Root,
    ) -> Result<Root, RepositoryError> {
        let updated = self.redb_table.update_with_relationships(entity)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::Root(EntityEvent::Updated)),
            ids: vec![updated.id],
            data: None,
        });
        Ok(updated)
    }

    pub fn update_with_relationships_multi(
        &mut self,
        event_buffer: &mut EventBuffer,
        entities: &[Root],
    ) -> Result<Vec<Root>, RepositoryError> {
        let updated = self.redb_table.update_with_relationships_multi(entities)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::Root(EntityEvent::Updated)),
            ids: updated.iter().map(|e| e.id).collect(),
            data: None,
        });
        Ok(updated)
    }

    pub fn remove(
        &mut self,
        event_buffer: &mut EventBuffer,
        id: &EntityId,
    ) -> Result<(), RepositoryError> {
        let entity = match self.redb_table.get(id)? {
            Some(e) => e,
            None => return Ok(()),
        };
        // get all strong forward relationship fields

        let document = entity.document;

        // remove all strong relationships, initiating a cascade remove

        repository_factory::write::create_document_repository(self.transaction)
            .remove(event_buffer, &document)?;

        // remove entity
        self.redb_table.remove(id)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::Root(EntityEvent::Removed)),
            ids: vec![*id],
            data: None,
        });

        Ok(())
    }

    pub fn remove_multi(
        &mut self,
        event_buffer: &mut EventBuffer,
        ids: &[EntityId],
    ) -> Result<(), RepositoryError> {
        let entities = self.redb_table.get_multi(ids)?;
        if entities.is_empty() || entities.iter().all(|e| e.is_none()) {
            return Ok(());
        }

        // get all strong forward relationship fields

        let document_ids: Vec<EntityId> = entities
            .iter()
            .filter_map(|entity| entity.as_ref().map(|entity| entity.document))
            .collect();

        // remove all strong relationships, initiating a cascade remove

        repository_factory::write::create_document_repository(self.transaction)
            .remove_multi(event_buffer, &document_ids)?;

        self.redb_table.remove_multi(ids)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::Root(EntityEvent::Removed)),
            ids: ids.into(),
            data: None,
        });

        Ok(())
    }
    pub fn get_relationship(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
    ) -> Result<Vec<EntityId>, RepositoryError> {
        self.redb_table.get_relationship(id, field)
    }
    pub fn get_relationship_many(
        &self,
        ids: &[EntityId],
        field: &RootRelationshipField,
    ) -> Result<std::collections::HashMap<EntityId, Vec<EntityId>>, RepositoryError> {
        self.redb_table.get_relationship_many(ids, field)
    }
    pub fn get_relationship_count(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
    ) -> Result<usize, RepositoryError> {
        self.redb_table.get_relationship_count(id, field)
    }
    pub fn get_relationship_in_range(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
        offset: usize,
        limit: usize,
    ) -> Result<Vec<EntityId>, RepositoryError> {
        self.redb_table
            .get_relationship_in_range(id, field, offset, limit)
    }
    pub fn get_relationships_from_right_ids(
        &self,
        field: &RootRelationshipField,
        right_ids: &[EntityId],
    ) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
        self.redb_table
            .get_relationships_from_right_ids(field, right_ids)
    }

    pub fn set_relationship_multi(
        &mut self,
        event_buffer: &mut EventBuffer,
        field: &RootRelationshipField,
        relationships: Vec<(EntityId, Vec<EntityId>)>,
    ) -> Result<(), RepositoryError> {
        // Validate that all right_ids exist
        let all_right_ids: Vec<EntityId> = relationships
            .iter()
            .flat_map(|(_, ids)| ids.iter().copied())
            .collect();
        if !all_right_ids.is_empty() {
            match field {
                RootRelationshipField::Document => {
                    let child_repo =
                        repository_factory::write::create_document_repository(self.transaction);
                    let found = child_repo.get_multi(&all_right_ids)?;
                    let missing: Vec<_> = all_right_ids
                        .iter()
                        .zip(found.iter())
                        .filter(|(_, entity)| entity.is_none())
                        .map(|(id, _)| *id)
                        .collect();
                    if !missing.is_empty() {
                        return Err(RepositoryError::MissingRelationshipTarget {
                            operation: "set_relationship_multi",
                            ids: missing,
                        });
                    }
                }
            }
        }
        self.redb_table
            .set_relationship_multi(field, relationships.clone())?;
        for (left_id, right_ids) in relationships {
            event_buffer.push(Event {
                origin: Origin::DirectAccess(DirectAccessEntity::Root(EntityEvent::Updated)),
                ids: vec![left_id],
                data: Some(format!(
                    "{}:{}",
                    field,
                    right_ids
                        .iter()
                        .map(|id| id.to_string())
                        .collect::<Vec<_>>()
                        .join(",")
                )),
            });
        }
        Ok(())
    }

    pub fn set_relationship(
        &mut self,
        event_buffer: &mut EventBuffer,
        id: &EntityId,
        field: &RootRelationshipField,
        right_ids: &[EntityId],
    ) -> Result<(), RepositoryError> {
        // Validate that all right_ids exist
        if !right_ids.is_empty() {
            match field {
                RootRelationshipField::Document => {
                    let child_repo =
                        repository_factory::write::create_document_repository(self.transaction);
                    let found = child_repo.get_multi(right_ids)?;
                    let missing: Vec<_> = right_ids
                        .iter()
                        .zip(found.iter())
                        .filter(|(_, entity)| entity.is_none())
                        .map(|(id, _)| *id)
                        .collect();
                    if !missing.is_empty() {
                        return Err(RepositoryError::MissingRelationshipTarget {
                            operation: "set_relationship",
                            ids: missing,
                        });
                    }
                }
            }
        }
        self.redb_table.set_relationship(id, field, right_ids)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::Root(EntityEvent::Updated)),
            ids: vec![*id],
            data: Some(format!(
                "{}:{}",
                field,
                right_ids
                    .iter()
                    .map(|id| id.to_string())
                    .collect::<Vec<_>>()
                    .join(",")
            )),
        });
        Ok(())
    }

    pub fn move_relationship_ids(
        &mut self,
        event_buffer: &mut EventBuffer,
        id: &EntityId,
        field: &RootRelationshipField,
        ids_to_move: &[EntityId],
        new_index: i32,
    ) -> Result<Vec<EntityId>, RepositoryError> {
        let reordered = self
            .redb_table
            .move_relationship_ids(id, field, ids_to_move, new_index)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::Root(EntityEvent::Updated)),
            ids: vec![*id],
            data: Some(format!(
                "{}:{}",
                field,
                reordered
                    .iter()
                    .map(|id| id.to_string())
                    .collect::<Vec<_>>()
                    .join(",")
            )),
        });
        Ok(reordered)
    }

    pub fn snapshot(&self, _ids: &[EntityId]) -> Result<EntityTreeSnapshot, RepositoryError> {
        let store_snap = self.transaction.snapshot_store();
        Ok(EntityTreeSnapshot {
            store_snapshot: Some(store_snap),
        })
    }

    pub fn restore(
        &mut self,
        event_buffer: &mut EventBuffer,
        snap: &EntityTreeSnapshot,
    ) -> Result<(), RepositoryError> {
        let store_snap = snap
            .store_snapshot
            .as_ref()
            .ok_or_else(|| RepositoryError::Serialization("missing store snapshot".into()))?;
        self.transaction.restore_store(store_snap);

        let store = self.transaction.get_store();

        let mut emit = |entity: DirectAccessEntity, ids: Vec<EntityId>| {
            if !ids.is_empty() {
                event_buffer.push(Event {
                    origin: Origin::DirectAccess(entity),
                    ids,
                    data: None,
                });
            }
        };

        // Root: Created + Updated (has Document relationship)
        let root_ids: Vec<_> = store.roots.read().unwrap().keys().copied().collect();
        emit(
            DirectAccessEntity::Root(EntityEvent::Created),
            root_ids.clone(),
        );
        emit(DirectAccessEntity::Root(EntityEvent::Updated), root_ids);

        // Document: Created + Updated (strong child, has relationships)
        let doc_ids: Vec<_> = store.documents.read().unwrap().keys().copied().collect();
        emit(
            DirectAccessEntity::Document(EntityEvent::Created),
            doc_ids.clone(),
        );
        emit(DirectAccessEntity::Document(EntityEvent::Updated), doc_ids);

        // Frame: Created + Updated
        let frame_ids: Vec<_> = store.frames.read().unwrap().keys().copied().collect();
        emit(
            DirectAccessEntity::Frame(EntityEvent::Created),
            frame_ids.clone(),
        );
        emit(DirectAccessEntity::Frame(EntityEvent::Updated), frame_ids);

        // Block: Created + Updated
        let block_ids: Vec<_> = store.blocks.read().unwrap().keys().copied().collect();
        emit(
            DirectAccessEntity::Block(EntityEvent::Created),
            block_ids.clone(),
        );
        emit(DirectAccessEntity::Block(EntityEvent::Updated), block_ids);

        // InlineElement: Created only (leaf)
        let elem_ids: Vec<_> = store
            .inline_elements
            .read()
            .unwrap()
            .keys()
            .copied()
            .collect();
        emit(
            DirectAccessEntity::InlineElement(EntityEvent::Created),
            elem_ids,
        );

        // List: Created only (leaf)
        let list_ids: Vec<_> = store.lists.read().unwrap().keys().copied().collect();
        emit(DirectAccessEntity::List(EntityEvent::Created), list_ids);

        // Resource: Created only (leaf)
        let res_ids: Vec<_> = store.resources.read().unwrap().keys().copied().collect();
        emit(DirectAccessEntity::Resource(EntityEvent::Created), res_ids);

        // Table: Created + Updated
        let table_ids: Vec<_> = store.tables.read().unwrap().keys().copied().collect();
        emit(
            DirectAccessEntity::Table(EntityEvent::Created),
            table_ids.clone(),
        );
        emit(DirectAccessEntity::Table(EntityEvent::Updated), table_ids);

        // TableCell: Created + Updated
        let tc_ids: Vec<_> = store.table_cells.read().unwrap().keys().copied().collect();
        emit(
            DirectAccessEntity::TableCell(EntityEvent::Created),
            tc_ids.clone(),
        );
        emit(DirectAccessEntity::TableCell(EntityEvent::Updated), tc_ids);

        Ok(())
    }
}

pub struct RootRepositoryRO<'a> {
    redb_table: Box<dyn RootTableRO + 'a>,
}
impl<'a> RootRepositoryRO<'a> {
    pub fn new(redb_table: Box<dyn RootTableRO + 'a>) -> Self {
        RootRepositoryRO { redb_table }
    }
    pub fn get(&self, id: &EntityId) -> Result<Option<Root>, RepositoryError> {
        self.redb_table.get(id)
    }
    pub fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Root>>, RepositoryError> {
        self.redb_table.get_multi(ids)
    }
    pub fn get_all(&self) -> Result<Vec<Root>, RepositoryError> {
        self.redb_table.get_all()
    }
    pub fn get_relationship(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
    ) -> Result<Vec<EntityId>, RepositoryError> {
        self.redb_table.get_relationship(id, field)
    }
    pub fn get_relationship_many(
        &self,
        ids: &[EntityId],
        field: &RootRelationshipField,
    ) -> Result<std::collections::HashMap<EntityId, Vec<EntityId>>, RepositoryError> {
        self.redb_table.get_relationship_many(ids, field)
    }
    pub fn get_relationship_count(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
    ) -> Result<usize, RepositoryError> {
        self.redb_table.get_relationship_count(id, field)
    }
    pub fn get_relationship_in_range(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
        offset: usize,
        limit: usize,
    ) -> Result<Vec<EntityId>, RepositoryError> {
        self.redb_table
            .get_relationship_in_range(id, field, offset, limit)
    }
    pub fn get_relationships_from_right_ids(
        &self,
        field: &RootRelationshipField,
        right_ids: &[EntityId],
    ) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
        self.redb_table
            .get_relationships_from_right_ids(field, right_ids)
    }
}