qleany-common 2.0.0

Shared entities, database, events, and undo/redo infrastructure for Qleany
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
// Generated by Qleany v1.12.0 from common_entity_table.tera

// ═══════════════════════════════════════════════════════════════════════
// Entity WITH forward relationships — explicit struct implementation
// ═══════════════════════════════════════════════════════════════════════
use crate::database::hashmap_store::{
    HashMapStore, delete_from_backward_junction, junction_get, junction_remove, junction_set,
    read_or_recover, write_or_recover,
};
use crate::entities::Workspace;
use crate::error::RepositoryError;
use crate::types::EntityId;
use crate::{impl_relationship_methods, impl_write_relationship_methods};
use im::HashMap;
use std::sync::RwLock;

use super::workspace_repository::WorkspaceRelationshipField;
use super::workspace_repository::WorkspaceTable;
use super::workspace_repository::WorkspaceTableRO;

pub struct WorkspaceHashMapTable<'a> {
    store: &'a HashMapStore,
}

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

    fn resolve_junction(
        &self,
        field: &WorkspaceRelationshipField,
    ) -> &RwLock<HashMap<EntityId, Vec<EntityId>>> {
        match field {
            WorkspaceRelationshipField::Entities => &self.store.jn_entity_from_workspace_entities,
            WorkspaceRelationshipField::Features => &self.store.jn_feature_from_workspace_features,
            WorkspaceRelationshipField::Global => &self.store.jn_global_from_workspace_global,
            WorkspaceRelationshipField::UserInterface => {
                &self.store.jn_user_interface_from_workspace_user_interface
            }
        }
    }

    fn relationship_source_exists(&self, id: &EntityId) -> bool {
        read_or_recover(&self.store.workspaces).contains_key(id)
    }

    fn relationship_is_ordered(&self, field: &WorkspaceRelationshipField) -> bool {
        match field {
            WorkspaceRelationshipField::Entities => true,
            WorkspaceRelationshipField::Features => true,
            WorkspaceRelationshipField::Global => false,
            WorkspaceRelationshipField::UserInterface => false,
        }
    }

    fn validate_relationship_updates(
        &self,
        field: &WorkspaceRelationshipField,
        rows: &[(EntityId, Vec<EntityId>)],
        _creating_ids: &[EntityId],
    ) -> Result<(), RepositoryError> {
        let (exclusive, scalar) = match field {
            WorkspaceRelationshipField::Entities => {
                let targets = read_or_recover(&self.store.entities);
                let missing: Vec<_> = rows
                    .iter()
                    .flat_map(|(_, ids)| ids)
                    .copied()
                    .filter(|id| !targets.contains_key(id))
                    .collect();
                if !missing.is_empty() {
                    return Err(RepositoryError::MissingRelationshipTarget {
                        operation: "relationship update",
                        ids: missing,
                    });
                }
                (true, false)
            }
            WorkspaceRelationshipField::Features => {
                let targets = read_or_recover(&self.store.features);
                let missing: Vec<_> = rows
                    .iter()
                    .flat_map(|(_, ids)| ids)
                    .copied()
                    .filter(|id| !targets.contains_key(id))
                    .collect();
                if !missing.is_empty() {
                    return Err(RepositoryError::MissingRelationshipTarget {
                        operation: "relationship update",
                        ids: missing,
                    });
                }
                (true, false)
            }
            WorkspaceRelationshipField::Global => {
                let targets = read_or_recover(&self.store.globals);
                let missing: Vec<_> = rows
                    .iter()
                    .flat_map(|(_, ids)| ids)
                    .copied()
                    .filter(|id| !targets.contains_key(id))
                    .collect();
                if !missing.is_empty() {
                    return Err(RepositoryError::MissingRelationshipTarget {
                        operation: "relationship update",
                        ids: missing,
                    });
                }
                (true, true)
            }
            WorkspaceRelationshipField::UserInterface => {
                let targets = read_or_recover(&self.store.user_interfaces);
                let missing: Vec<_> = rows
                    .iter()
                    .flat_map(|(_, ids)| ids)
                    .copied()
                    .filter(|id| !targets.contains_key(id))
                    .collect();
                if !missing.is_empty() {
                    return Err(RepositoryError::MissingRelationshipTarget {
                        operation: "relationship update",
                        ids: missing,
                    });
                }
                (true, true)
            }
        };
        crate::database::hashmap_store::validate_junction_updates(
            self.resolve_junction(field),
            rows,
            exclusive,
            scalar,
        )
    }

    fn hydrate(&self, entity: &mut Workspace) {
        if let Some(val) = junction_get(&self.store.jn_global_from_workspace_global, &entity.id)
            .into_iter()
            .next()
        {
            entity.global = val;
        }
        entity.entities = junction_get(&self.store.jn_entity_from_workspace_entities, &entity.id);
        entity.features = junction_get(&self.store.jn_feature_from_workspace_features, &entity.id);
        if let Some(val) = junction_get(
            &self.store.jn_user_interface_from_workspace_user_interface,
            &entity.id,
        )
        .into_iter()
        .next()
        {
            entity.user_interface = val;
        }
    }
}

impl<'a> WorkspaceTable for WorkspaceHashMapTable<'a> {
    fn create(&mut self, entity: &Workspace) -> Result<Workspace, RepositoryError> {
        self.create_multi(std::slice::from_ref(entity))
            .and_then(|v| {
                // `create_multi` is contracted to return one row per input, so this
                // is unreachable — but it used to be `.unwrap()`, and a store that
                // ever broke that contract would take the whole process down rather
                // than fail the one call that noticed.
                v.into_iter().next().ok_or_else(|| {
                    RepositoryError::Other(anyhow::anyhow!(
                        "create: the store returned no row for the entity it was given"
                    ))
                })
            })
    }

    fn create_multi(&mut self, entities: &[Workspace]) -> Result<Vec<Workspace>, RepositoryError> {
        // Assign identities first, then validate the whole batch without holding
        // the source table lock (self-referential relationships read that table).
        let entities: Vec<_> = entities
            .iter()
            .map(|entity| {
                let mut entity = entity.clone();
                if entity.id == EntityId::default() {
                    entity.id = self.store.next_id("workspace");
                }
                entity
            })
            .collect();

        self.validate_relationship_updates(
            &WorkspaceRelationshipField::Entities,
            &entities
                .iter()
                .map(|e| (e.id, e.entities.clone()))
                .collect::<Vec<_>>(),
            &entities.iter().map(|e| e.id).collect::<Vec<_>>(),
        )?;
        self.validate_relationship_updates(
            &WorkspaceRelationshipField::Features,
            &entities
                .iter()
                .map(|e| (e.id, e.features.clone()))
                .collect::<Vec<_>>(),
            &entities.iter().map(|e| e.id).collect::<Vec<_>>(),
        )?;
        let mut created = Vec::with_capacity(entities.len());
        let mut workspace_map = write_or_recover(&self.store.workspaces);

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

            // one-to-one constraint check: ensure global is not already referenced by another workspace
            {
                let jn = read_or_recover(&self.store.jn_global_from_workspace_global);
                for (&existing_id, right_ids) in jn.iter() {
                    if existing_id != new_entity.id && right_ids.contains(&new_entity.global) {
                        return Err(RepositoryError::ConstraintViolation(format!(
                            "One-to-one constraint violation: Global {} is already referenced by Workspace {}",
                            new_entity.global, existing_id
                        )));
                    }
                }
            }
            // one-to-one constraint check: ensure user_interface is not already referenced by another workspace
            {
                let jn =
                    read_or_recover(&self.store.jn_user_interface_from_workspace_user_interface);
                for (&existing_id, right_ids) in jn.iter() {
                    if existing_id != new_entity.id
                        && right_ids.contains(&new_entity.user_interface)
                    {
                        return Err(RepositoryError::ConstraintViolation(format!(
                            "One-to-one constraint violation: UserInterface {} is already referenced by Workspace {}",
                            new_entity.user_interface, existing_id
                        )));
                    }
                }
            }

            workspace_map.insert(new_entity.id, new_entity.clone());

            junction_set(
                &self.store.jn_entity_from_workspace_entities,
                new_entity.id,
                new_entity.entities.clone(),
            );
            junction_set(
                &self.store.jn_feature_from_workspace_features,
                new_entity.id,
                new_entity.features.clone(),
            );
            junction_set(
                &self.store.jn_global_from_workspace_global,
                new_entity.id,
                vec![new_entity.global],
            );
            junction_set(
                &self.store.jn_user_interface_from_workspace_user_interface,
                new_entity.id,
                vec![new_entity.user_interface],
            );

            created.push(new_entity);
        }
        Ok(created)
    }

    fn get(&self, id: &EntityId) -> Result<Option<Workspace>, RepositoryError> {
        let workspace_map = read_or_recover(&self.store.workspaces);
        match workspace_map.get(id) {
            Some(entity) => {
                let mut e = entity.clone();
                drop(workspace_map);
                self.hydrate(&mut e);
                Ok(Some(e))
            }
            None => Ok(None),
        }
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Workspace>>, RepositoryError> {
        let mut result = Vec::with_capacity(ids.len());
        for id in ids {
            result.push(self.get(id)?);
        }
        Ok(result)
    }

    fn get_all(&self) -> Result<Vec<Workspace>, RepositoryError> {
        let workspace_map = read_or_recover(&self.store.workspaces);
        let entries: Vec<Workspace> = workspace_map.values().cloned().collect();
        drop(workspace_map);
        let mut result = Vec::with_capacity(entries.len());
        for mut entity in entries {
            self.hydrate(&mut entity);
            result.push(entity);
        }
        Ok(result)
    }

    fn update(&mut self, entity: &Workspace) -> Result<Workspace, RepositoryError> {
        self.update_multi(std::slice::from_ref(entity))
            .and_then(|v| {
                // `update_multi` is contracted to return one row per input, so this
                // is unreachable — but it used to be `.unwrap()`, and a store that
                // ever broke that contract would take the whole process down rather
                // than fail the one call that noticed.
                v.into_iter().next().ok_or_else(|| {
                    RepositoryError::Other(anyhow::anyhow!(
                        "update: the store returned no row for the entity it was given"
                    ))
                })
            })
    }

    // Scalar-only update: writes entity data but does NOT touch junction tables.
    fn update_multi(&mut self, entities: &[Workspace]) -> Result<Vec<Workspace>, RepositoryError> {
        let mut workspace_map = write_or_recover(&self.store.workspaces);
        for entity in entities {
            workspace_map.insert(entity.id, entity.clone());
        }
        drop(workspace_map);
        let ids: Vec<EntityId> = entities.iter().map(|e| e.id).collect();
        let result = self.get_multi(&ids)?;
        Ok(result.into_iter().flatten().collect())
    }

    fn update_with_relationships(
        &mut self,
        entity: &Workspace,
    ) -> Result<Workspace, RepositoryError> {
        self.update_with_relationships_multi(std::slice::from_ref(entity))
            .and_then(|v| {
                // `update_with_relationships_multi` is contracted to return one row per input, so this
                // is unreachable — but it used to be `.unwrap()`, and a store that
                // ever broke that contract would take the whole process down rather
                // than fail the one call that noticed.
                v.into_iter().next().ok_or_else(|| {
                    RepositoryError::Other(anyhow::anyhow!(
                        "update_with_relationships: the store returned no row for the entity it was given"
                    ))
                })
            })
    }

    fn update_with_relationships_multi(
        &mut self,
        entities: &[Workspace],
    ) -> Result<Vec<Workspace>, RepositoryError> {
        self.validate_relationship_updates(
            &WorkspaceRelationshipField::Entities,
            &entities
                .iter()
                .map(|e| (e.id, e.entities.clone()))
                .collect::<Vec<_>>(),
            &[],
        )?;
        self.validate_relationship_updates(
            &WorkspaceRelationshipField::Features,
            &entities
                .iter()
                .map(|e| (e.id, e.features.clone()))
                .collect::<Vec<_>>(),
            &[],
        )?;
        let mut workspace_map = write_or_recover(&self.store.workspaces);
        for entity in entities {
            // one-to-one constraint check: ensure global is not already referenced by another workspace
            {
                let jn = read_or_recover(&self.store.jn_global_from_workspace_global);
                for (&existing_id, right_ids) in jn.iter() {
                    if existing_id != entity.id && right_ids.contains(&entity.global) {
                        return Err(RepositoryError::ConstraintViolation(format!(
                            "One-to-one constraint violation: Global {} is already referenced by Workspace {}",
                            entity.global, existing_id
                        )));
                    }
                }
            }
            // one-to-one constraint check: ensure user_interface is not already referenced by another workspace
            {
                let jn =
                    read_or_recover(&self.store.jn_user_interface_from_workspace_user_interface);
                for (&existing_id, right_ids) in jn.iter() {
                    if existing_id != entity.id && right_ids.contains(&entity.user_interface) {
                        return Err(RepositoryError::ConstraintViolation(format!(
                            "One-to-one constraint violation: UserInterface {} is already referenced by Workspace {}",
                            entity.user_interface, existing_id
                        )));
                    }
                }
            }
            workspace_map.insert(entity.id, entity.clone());

            junction_set(
                &self.store.jn_global_from_workspace_global,
                entity.id,
                vec![entity.global],
            );
            junction_set(
                &self.store.jn_entity_from_workspace_entities,
                entity.id,
                entity.entities.clone(),
            );
            junction_set(
                &self.store.jn_feature_from_workspace_features,
                entity.id,
                entity.features.clone(),
            );
            junction_set(
                &self.store.jn_user_interface_from_workspace_user_interface,
                entity.id,
                vec![entity.user_interface],
            );
        }
        drop(workspace_map);
        let ids: Vec<EntityId> = entities.iter().map(|e| e.id).collect();
        let result = self.get_multi(&ids)?;
        Ok(result.into_iter().flatten().collect())
    }

    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 workspace_map = write_or_recover(&self.store.workspaces);
        for id in ids {
            workspace_map.remove(id);

            // Remove forward junction entries

            junction_remove(&self.store.jn_global_from_workspace_global, id);
            junction_remove(&self.store.jn_entity_from_workspace_entities, id);
            junction_remove(&self.store.jn_feature_from_workspace_features, id);
            junction_remove(
                &self.store.jn_user_interface_from_workspace_user_interface,
                id,
            );

            // Clean up backward references (uses the owning entity's forward junction)

            delete_from_backward_junction(&self.store.jn_workspace_from_root_workspace, id);
        }
        Ok(())
    }

    impl_write_relationship_methods!(WorkspaceHashMapTable<'a>, WorkspaceRelationshipField);
}

pub struct WorkspaceHashMapTableRO<'a> {
    store: &'a HashMapStore,
}

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

    fn resolve_junction(
        &self,
        field: &WorkspaceRelationshipField,
    ) -> &RwLock<HashMap<EntityId, Vec<EntityId>>> {
        match field {
            WorkspaceRelationshipField::Entities => &self.store.jn_entity_from_workspace_entities,
            WorkspaceRelationshipField::Features => &self.store.jn_feature_from_workspace_features,
            WorkspaceRelationshipField::Global => &self.store.jn_global_from_workspace_global,
            WorkspaceRelationshipField::UserInterface => {
                &self.store.jn_user_interface_from_workspace_user_interface
            }
        }
    }

    fn hydrate(&self, entity: &mut Workspace) {
        if let Some(val) = junction_get(&self.store.jn_global_from_workspace_global, &entity.id)
            .into_iter()
            .next()
        {
            entity.global = val;
        }
        entity.entities = junction_get(&self.store.jn_entity_from_workspace_entities, &entity.id);
        entity.features = junction_get(&self.store.jn_feature_from_workspace_features, &entity.id);
        if let Some(val) = junction_get(
            &self.store.jn_user_interface_from_workspace_user_interface,
            &entity.id,
        )
        .into_iter()
        .next()
        {
            entity.user_interface = val;
        }
    }
}

impl<'a> WorkspaceTableRO for WorkspaceHashMapTableRO<'a> {
    fn get(&self, id: &EntityId) -> Result<Option<Workspace>, RepositoryError> {
        let workspace_map = read_or_recover(&self.store.workspaces);
        match workspace_map.get(id) {
            Some(entity) => {
                let mut e = entity.clone();
                drop(workspace_map);
                self.hydrate(&mut e);
                Ok(Some(e))
            }
            None => Ok(None),
        }
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Workspace>>, RepositoryError> {
        let mut result = Vec::with_capacity(ids.len());
        for id in ids {
            result.push(self.get(id)?);
        }
        Ok(result)
    }

    fn get_all(&self) -> Result<Vec<Workspace>, RepositoryError> {
        let workspace_map = read_or_recover(&self.store.workspaces);
        let entries: Vec<Workspace> = workspace_map.values().cloned().collect();
        drop(workspace_map);
        let mut result = Vec::with_capacity(entries.len());
        for mut entity in entries {
            self.hydrate(&mut entity);
            result.push(entity);
        }
        Ok(result)
    }

    impl_relationship_methods!(WorkspaceHashMapTableRO<'a>, WorkspaceRelationshipField);
}