text-document-common 1.5.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
// Generated by Qleany v1.7.3 from common_entity_table.tera
// Phase 2 step 6: junction-free. `Root.document` is the source of
// truth; the previous jn_document_from_root_document table and the
// `hydrate()` re-population step are gone.

use crate::database::Store;
use crate::entities::Root;
use crate::error::RepositoryError;
use crate::types::EntityId;
use std::collections::HashMap as StdHashMap;

use super::root_repository::RootRelationshipField;
use super::root_repository::RootTable;
use super::root_repository::RootTableRO;

// ── Field accessor helpers ──────────────────────────────────────────

/// Read `root.document` as a 0-or-1 element Vec.
///
/// Empty when the Root has no document yet (`root.document` is
/// `EntityId::default()` = 0). This departs from the legacy junction
/// behaviour, which unconditionally returned `[0]` for an
/// uninitialised Root — that was a generator artifact (junction set
/// happened on every create regardless of value), and no real caller
/// relies on it: use cases that pattern-match `doc_ids.first()` would
/// either treat the `[0]` as a valid id (passing 0 downstream and
/// failing on `get_document(0)`) or get the cleaner empty-list error
/// here. Only two controller unit tests asserted the quirk; they're
/// updated alongside this change.
fn read_field(root: &Root, field: &RootRelationshipField) -> Vec<EntityId> {
    match field {
        RootRelationshipField::Document => {
            if root.document == EntityId::default() {
                Vec::new()
            } else {
                vec![root.document]
            }
        }
    }
}

fn write_field(root: &mut Root, field: &RootRelationshipField, ids: Vec<EntityId>) {
    match field {
        RootRelationshipField::Document => {
            root.document = ids.first().copied().unwrap_or_default();
        }
    }
}

/// One-to-one constraint: no other Root may reference the same Document.
fn check_one_to_one(
    store: &Store,
    self_id: EntityId,
    document_id: EntityId,
) -> Result<(), RepositoryError> {
    if document_id == EntityId::default() {
        return Ok(());
    }
    let roots = store.roots.read().unwrap();
    for (existing_id, existing) in roots.iter() {
        if *existing_id != self_id && existing.document == document_id {
            return Err(RepositoryError::ConstraintViolation(format!(
                "One-to-one constraint violation: Document {} is already referenced by Root {}",
                document_id, existing_id
            )));
        }
    }
    Ok(())
}

pub struct RootHashMapTable<'a> {
    store: &'a Store,
}

impl<'a> RootHashMapTable<'a> {
    pub fn new(store: &'a Store) -> Self {
        Self { store }
    }
}

impl<'a> RootTable for RootHashMapTable<'a> {
    fn create(&mut self, entity: &Root) -> Result<Root, RepositoryError> {
        self.create_multi(std::slice::from_ref(entity))
            .map(|v| v.into_iter().next().unwrap())
    }

    fn create_multi(&mut self, entities: &[Root]) -> Result<Vec<Root>, RepositoryError> {
        let mut created = Vec::with_capacity(entities.len());
        let mut root_map = self.store.roots.write().unwrap();

        for entity in entities {
            let new_entity = if entity.id == EntityId::default() {
                let id = self.store.next_id("root");
                Root {
                    id,
                    ..entity.clone()
                }
            } else {
                if root_map.contains_key(&entity.id) {
                    return Err(RepositoryError::DuplicateId {
                        entity: "Root",
                        id: entity.id,
                    });
                }
                entity.clone()
            };

            // One-to-one constraint: must check against current map state.
            if new_entity.document != EntityId::default() {
                for (existing_id, existing) in root_map.iter() {
                    if *existing_id != new_entity.id && existing.document == new_entity.document {
                        return Err(RepositoryError::ConstraintViolation(format!(
                            "One-to-one constraint violation: Document {} is already referenced by Root {}",
                            new_entity.document, existing_id
                        )));
                    }
                }
            }

            root_map.insert(new_entity.id, new_entity.clone());
            created.push(new_entity);
        }
        Ok(created)
    }

    fn get(&self, id: &EntityId) -> Result<Option<Root>, RepositoryError> {
        Ok(self.store.roots.read().unwrap().get(id).cloned())
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Root>>, RepositoryError> {
        let map = self.store.roots.read().unwrap();
        Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
    }

    fn get_all(&self) -> Result<Vec<Root>, RepositoryError> {
        Ok(self.store.roots.read().unwrap().values().cloned().collect())
    }

    fn update(&mut self, entity: &Root) -> Result<Root, RepositoryError> {
        self.update_multi(std::slice::from_ref(entity))
            .map(|v| v.into_iter().next().unwrap())
    }

    /// Scalar-only: preserve in-store `document` so a stale Root
    /// passed in doesn't accidentally revert the relationship.
    fn update_multi(&mut self, entities: &[Root]) -> Result<Vec<Root>, RepositoryError> {
        let mut root_map = self.store.roots.write().unwrap();
        let mut result = Vec::with_capacity(entities.len());
        for entity in entities {
            let mut to_write = entity.clone();
            if let Some(existing) = root_map.get(&entity.id) {
                to_write.document = existing.document;
            }
            root_map.insert(entity.id, to_write.clone());
            result.push(to_write);
        }
        Ok(result)
    }

    fn update_with_relationships(&mut self, entity: &Root) -> Result<Root, RepositoryError> {
        self.update_with_relationships_multi(std::slice::from_ref(entity))
            .map(|v| v.into_iter().next().unwrap())
    }

    fn update_with_relationships_multi(
        &mut self,
        entities: &[Root],
    ) -> Result<Vec<Root>, RepositoryError> {
        // Constraint check first (no write held).
        for entity in entities {
            check_one_to_one(self.store, entity.id, entity.document)?;
        }
        let mut root_map = self.store.roots.write().unwrap();
        let mut result = Vec::with_capacity(entities.len());
        for entity in entities {
            root_map.insert(entity.id, entity.clone());
            result.push(entity.clone());
        }
        Ok(result)
    }

    fn remove(&mut self, id: &EntityId) -> Result<(), RepositoryError> {
        self.remove_multi(std::slice::from_ref(id))
    }

    fn remove_multi(&mut self, ids: &[EntityId]) -> Result<(), RepositoryError> {
        let mut root_map = self.store.roots.write().unwrap();
        for id in ids {
            root_map.remove(id);
        }
        // Root has no backward references (top-level entity); nothing
        // else points at a Root.
        Ok(())
    }

    fn get_relationship(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
    ) -> Result<Vec<EntityId>, RepositoryError> {
        Ok(self
            .store
            .roots
            .read()
            .unwrap()
            .get(id)
            .map(|r| read_field(r, field))
            .unwrap_or_default())
    }

    fn get_relationship_many(
        &self,
        ids: &[EntityId],
        field: &RootRelationshipField,
    ) -> Result<StdHashMap<EntityId, Vec<EntityId>>, RepositoryError> {
        let map = self.store.roots.read().unwrap();
        let mut out = StdHashMap::new();
        for id in ids {
            out.insert(
                *id,
                map.get(id)
                    .map(|r| read_field(r, field))
                    .unwrap_or_default(),
            );
        }
        Ok(out)
    }

    fn get_relationship_count(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
    ) -> Result<usize, RepositoryError> {
        Ok(self
            .store
            .roots
            .read()
            .unwrap()
            .get(id)
            .map(|r| read_field(r, field).len())
            .unwrap_or(0))
    }

    fn get_relationship_in_range(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
        offset: usize,
        limit: usize,
    ) -> Result<Vec<EntityId>, RepositoryError> {
        Ok(self
            .store
            .roots
            .read()
            .unwrap()
            .get(id)
            .map(|r| {
                read_field(r, field)
                    .into_iter()
                    .skip(offset)
                    .take(limit)
                    .collect()
            })
            .unwrap_or_default())
    }

    fn get_relationships_from_right_ids(
        &self,
        field: &RootRelationshipField,
        right_ids: &[EntityId],
    ) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
        let map = self.store.roots.read().unwrap();
        let mut out = Vec::new();
        for (id, root) in map.iter() {
            let list = read_field(root, field);
            if right_ids.iter().any(|rid| list.contains(rid)) {
                out.push((*id, list));
            }
        }
        Ok(out)
    }

    fn set_relationship_multi(
        &mut self,
        field: &RootRelationshipField,
        relationships: Vec<(EntityId, Vec<EntityId>)>,
    ) -> Result<(), RepositoryError> {
        // Constraint check before write.
        for (id, ids) in &relationships {
            if let RootRelationshipField::Document = field
                && let Some(&doc_id) = ids.first()
            {
                check_one_to_one(self.store, *id, doc_id)?;
            }
        }
        let mut map = self.store.roots.write().unwrap();
        for (id, ids) in relationships {
            if let Some(root) = map.get_mut(&id) {
                write_field(root, field, ids);
            }
        }
        Ok(())
    }

    fn set_relationship(
        &mut self,
        id: &EntityId,
        field: &RootRelationshipField,
        right_ids: &[EntityId],
    ) -> Result<(), RepositoryError> {
        if let RootRelationshipField::Document = field
            && let Some(&doc_id) = right_ids.first()
        {
            check_one_to_one(self.store, *id, doc_id)?;
        }
        let mut map = self.store.roots.write().unwrap();
        if let Some(root) = map.get_mut(id) {
            write_field(root, field, right_ids.to_vec());
        }
        Ok(())
    }

    fn move_relationship_ids(
        &mut self,
        id: &EntityId,
        field: &RootRelationshipField,
        ids_to_move: &[EntityId],
        new_index: i32,
    ) -> Result<Vec<EntityId>, RepositoryError> {
        // Root.document is single-valued; "move" is essentially "set".
        let mut map = self.store.roots.write().unwrap();
        let Some(root) = map.get_mut(id) else {
            return Ok(Vec::new());
        };
        let current = read_field(root, field);
        let moved = reorder(current, ids_to_move, new_index);
        write_field(root, field, moved.clone());
        Ok(moved)
    }
}

pub struct RootHashMapTableRO<'a> {
    store: &'a Store,
}

impl<'a> RootHashMapTableRO<'a> {
    pub fn new(store: &'a Store) -> Self {
        Self { store }
    }
}

impl<'a> RootTableRO for RootHashMapTableRO<'a> {
    fn get(&self, id: &EntityId) -> Result<Option<Root>, RepositoryError> {
        Ok(self.store.roots.read().unwrap().get(id).cloned())
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Root>>, RepositoryError> {
        let map = self.store.roots.read().unwrap();
        Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
    }

    fn get_all(&self) -> Result<Vec<Root>, RepositoryError> {
        Ok(self.store.roots.read().unwrap().values().cloned().collect())
    }

    fn get_relationship(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
    ) -> Result<Vec<EntityId>, RepositoryError> {
        Ok(self
            .store
            .roots
            .read()
            .unwrap()
            .get(id)
            .map(|r| read_field(r, field))
            .unwrap_or_default())
    }

    fn get_relationship_many(
        &self,
        ids: &[EntityId],
        field: &RootRelationshipField,
    ) -> Result<StdHashMap<EntityId, Vec<EntityId>>, RepositoryError> {
        let map = self.store.roots.read().unwrap();
        let mut out = StdHashMap::new();
        for id in ids {
            out.insert(
                *id,
                map.get(id)
                    .map(|r| read_field(r, field))
                    .unwrap_or_default(),
            );
        }
        Ok(out)
    }

    fn get_relationship_count(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
    ) -> Result<usize, RepositoryError> {
        Ok(self
            .store
            .roots
            .read()
            .unwrap()
            .get(id)
            .map(|r| read_field(r, field).len())
            .unwrap_or(0))
    }

    fn get_relationship_in_range(
        &self,
        id: &EntityId,
        field: &RootRelationshipField,
        offset: usize,
        limit: usize,
    ) -> Result<Vec<EntityId>, RepositoryError> {
        Ok(self
            .store
            .roots
            .read()
            .unwrap()
            .get(id)
            .map(|r| {
                read_field(r, field)
                    .into_iter()
                    .skip(offset)
                    .take(limit)
                    .collect()
            })
            .unwrap_or_default())
    }

    fn get_relationships_from_right_ids(
        &self,
        field: &RootRelationshipField,
        right_ids: &[EntityId],
    ) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
        let map = self.store.roots.read().unwrap();
        let mut out = Vec::new();
        for (id, root) in map.iter() {
            let list = read_field(root, field);
            if right_ids.iter().any(|rid| list.contains(rid)) {
                out.push((*id, list));
            }
        }
        Ok(out)
    }
}

/// Mirror the legacy `junction_move_ids` semantic for entities with
/// inline list-style relationships (here trivially since Root.document
/// is single-valued).
fn reorder(current: Vec<EntityId>, ids_to_move: &[EntityId], new_index: i32) -> Vec<EntityId> {
    if ids_to_move.is_empty() {
        return current;
    }
    let move_set: std::collections::HashSet<EntityId> = ids_to_move.iter().copied().collect();
    let mut remaining: Vec<EntityId> = current
        .into_iter()
        .filter(|eid| !move_set.contains(eid))
        .collect();
    let insert_pos = if new_index < 0 || (new_index as usize) > remaining.len() {
        remaining.len()
    } else {
        new_index as usize
    };
    for (i, &eid) in ids_to_move.iter().enumerate() {
        remaining.insert(insert_pos + i, eid);
    }
    remaining
}