qleany-common 1.12.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
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
// Generated by Qleany v1.11.0 from hashmap_store.tera

//! HashMap-based storage backend with O(1) snapshots.
//!
//! Uses `im::HashMap` (persistent/immutable data structure with structural sharing)
//! so that cloning the store for savepoints and undo is O(1).
//! The store uses `RwLock` for interior mutability and thread safety,
//! allowing `&HashMapStore` to be shared across threads via `Arc`.

use crate::entities::*;
use crate::snapshot::{StoreSnapshot, StoreSnapshotTrait};
use crate::types::EntityId;
use im::HashMap;
use std::sync::RwLock;

// ─────────────────────────────────────────────────────────────────────────────
// The Store
// ─────────────────────────────────────────────────────────────────────────────

#[derive(Debug, Default)]
pub struct HashMapStore {
    // ── Entity tables ──────────────────────────────────────────────────
    pub roots: RwLock<HashMap<EntityId, Root>>,
    pub workspaces: RwLock<HashMap<EntityId, Workspace>>,
    pub systems: RwLock<HashMap<EntityId, System>>,
    pub entities: RwLock<HashMap<EntityId, Entity>>,
    pub fields: RwLock<HashMap<EntityId, Field>>,
    pub features: RwLock<HashMap<EntityId, Feature>>,
    pub files: RwLock<HashMap<EntityId, File>>,
    pub use_cases: RwLock<HashMap<EntityId, UseCase>>,
    pub dtos: RwLock<HashMap<EntityId, Dto>>,
    pub dto_fields: RwLock<HashMap<EntityId, DtoField>>,
    pub globals: RwLock<HashMap<EntityId, Global>>,
    pub relationships: RwLock<HashMap<EntityId, Relationship>>,
    pub user_interfaces: RwLock<HashMap<EntityId, UserInterface>>,

    // ── Junction tables (one per forward relationship, shared for backward cleanup) ─
    pub jn_system_from_root_system: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_workspace_from_root_workspace: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_entity_from_workspace_entities: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_feature_from_workspace_features: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_global_from_workspace_global: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_user_interface_from_workspace_user_interface: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_file_from_system_files: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_field_from_entity_fields: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_entity_from_entity_inherits_from: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_relationship_from_entity_relationships: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_entity_from_field_entity: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_use_case_from_feature_use_cases: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_entity_from_file_entity: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_feature_from_file_feature: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_field_from_file_field: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_use_case_from_file_use_case: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_dto_from_use_case_dto_in: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_dto_from_use_case_dto_out: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_entity_from_use_case_entities: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_dto_field_from_dto_fields: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_entity_from_relationship_left_entity: RwLock<HashMap<EntityId, Vec<EntityId>>>,
    pub jn_entity_from_relationship_right_entity: RwLock<HashMap<EntityId, Vec<EntityId>>>,

    // ── ID counters (one per entity type) ──────────────────────────
    pub counters: RwLock<std::collections::HashMap<String, EntityId>>,

    // ── Savepoints ──────────────────────────────────────────────────
    savepoints: RwLock<std::collections::HashMap<u64, HashMapStoreSnapshot>>,
    next_savepoint_id: RwLock<u64>,
}

impl HashMapStore {
    pub fn new() -> Self {
        Self::default()
    }

    /// Clone the entire store for savepoint support. O(1) thanks to im::HashMap.
    /// (Poison-tolerant, but NOT atomic across tables — used for savepoints, which
    /// are taken on the single writer thread with no concurrent writer; use
    /// [`Self::freeze`] when an atomic cross-table snapshot is required.)
    pub fn snapshot(&self) -> HashMapStoreSnapshot {
        HashMapStoreSnapshot {
            roots: read_or_recover(&self.roots).clone(),
            workspaces: read_or_recover(&self.workspaces).clone(),
            systems: read_or_recover(&self.systems).clone(),
            entities: read_or_recover(&self.entities).clone(),
            fields: read_or_recover(&self.fields).clone(),
            features: read_or_recover(&self.features).clone(),
            files: read_or_recover(&self.files).clone(),
            use_cases: read_or_recover(&self.use_cases).clone(),
            dtos: read_or_recover(&self.dtos).clone(),
            dto_fields: read_or_recover(&self.dto_fields).clone(),
            globals: read_or_recover(&self.globals).clone(),
            relationships: read_or_recover(&self.relationships).clone(),
            user_interfaces: read_or_recover(&self.user_interfaces).clone(),
            jn_system_from_root_system: read_or_recover(&self.jn_system_from_root_system).clone(),
            jn_workspace_from_root_workspace: read_or_recover(
                &self.jn_workspace_from_root_workspace,
            )
            .clone(),
            jn_entity_from_workspace_entities: read_or_recover(
                &self.jn_entity_from_workspace_entities,
            )
            .clone(),
            jn_feature_from_workspace_features: read_or_recover(
                &self.jn_feature_from_workspace_features,
            )
            .clone(),
            jn_global_from_workspace_global: read_or_recover(&self.jn_global_from_workspace_global)
                .clone(),
            jn_user_interface_from_workspace_user_interface: read_or_recover(
                &self.jn_user_interface_from_workspace_user_interface,
            )
            .clone(),
            jn_file_from_system_files: read_or_recover(&self.jn_file_from_system_files).clone(),
            jn_field_from_entity_fields: read_or_recover(&self.jn_field_from_entity_fields).clone(),
            jn_entity_from_entity_inherits_from: read_or_recover(
                &self.jn_entity_from_entity_inherits_from,
            )
            .clone(),
            jn_relationship_from_entity_relationships: read_or_recover(
                &self.jn_relationship_from_entity_relationships,
            )
            .clone(),
            jn_entity_from_field_entity: read_or_recover(&self.jn_entity_from_field_entity).clone(),
            jn_use_case_from_feature_use_cases: read_or_recover(
                &self.jn_use_case_from_feature_use_cases,
            )
            .clone(),
            jn_entity_from_file_entity: read_or_recover(&self.jn_entity_from_file_entity).clone(),
            jn_feature_from_file_feature: read_or_recover(&self.jn_feature_from_file_feature)
                .clone(),
            jn_field_from_file_field: read_or_recover(&self.jn_field_from_file_field).clone(),
            jn_use_case_from_file_use_case: read_or_recover(&self.jn_use_case_from_file_use_case)
                .clone(),
            jn_dto_from_use_case_dto_in: read_or_recover(&self.jn_dto_from_use_case_dto_in).clone(),
            jn_dto_from_use_case_dto_out: read_or_recover(&self.jn_dto_from_use_case_dto_out)
                .clone(),
            jn_entity_from_use_case_entities: read_or_recover(
                &self.jn_entity_from_use_case_entities,
            )
            .clone(),
            jn_dto_field_from_dto_fields: read_or_recover(&self.jn_dto_field_from_dto_fields)
                .clone(),
            jn_entity_from_relationship_left_entity: read_or_recover(
                &self.jn_entity_from_relationship_left_entity,
            )
            .clone(),
            jn_entity_from_relationship_right_entity: read_or_recover(
                &self.jn_entity_from_relationship_right_entity,
            )
            .clone(),
            counters: read_or_recover(&self.counters).clone(),
        }
    }

    /// Atomically snapshot the whole store into a fresh, isolated `HashMapStore`.
    ///
    /// Unlike [`Self::snapshot`], this holds a read guard on **every** table, junction,
    /// and the counters *simultaneously* while cloning, so the result is a single
    /// consistent point-in-time view of the store *at the instant freeze runs*.
    /// O(1) clones (im::HashMap structural sharing); the lock hold is just the
    /// clones. The returned store carries no savepoints and is meant to back a
    /// read-only (frozen) transaction.
    ///
    /// Deadlock-freedom depends on an **invariant** (unenforced by the type
    /// system): guards are acquired in the struct's declared field order (all
    /// entity tables, then all junctions, then counters), and no writer ever
    /// holds two *entity-table* locks simultaneously — each writer takes at most
    /// one entity table, then its junctions, in table-before-junction order (see
    /// `remove_multi`). A future cascade that nested two entity-table locks would
    /// violate this and could deadlock against freeze; keep cascades single-table.
    ///
    /// SCOPE: freeze is atomic w.r.t. *itself*, not w.r.t. a writer's *multi-step*
    /// cascade. A write transaction is not one critical section — its per-repo
    /// calls each lock/unlock independently — so a cascading delete/create can
    /// leave a brief window (e.g. child rows removed but the parent's junction not
    /// yet cleared) into which freeze can land and capture a cross-table-torn
    /// snapshot (`gather` then hits "entity vanished mid-read", or silently omits
    /// a just-added-but-unlinked row). This shrinks the torn-read window from the
    /// whole read to a single instant, but does not eliminate it; a store-wide
    /// writer/reader gate would be required to fully close it.
    pub fn freeze(&self) -> HashMapStore {
        // Acquire ALL read guards first (declared order), then clone under that
        // one consistent lock set.
        let g_roots = read_or_recover(&self.roots);
        let g_workspaces = read_or_recover(&self.workspaces);
        let g_systems = read_or_recover(&self.systems);
        let g_entities = read_or_recover(&self.entities);
        let g_fields = read_or_recover(&self.fields);
        let g_features = read_or_recover(&self.features);
        let g_files = read_or_recover(&self.files);
        let g_use_cases = read_or_recover(&self.use_cases);
        let g_dtos = read_or_recover(&self.dtos);
        let g_dto_fields = read_or_recover(&self.dto_fields);
        let g_globals = read_or_recover(&self.globals);
        let g_relationships = read_or_recover(&self.relationships);
        let g_user_interfaces = read_or_recover(&self.user_interfaces);
        let g_jn_system_from_root_system = read_or_recover(&self.jn_system_from_root_system);
        let g_jn_workspace_from_root_workspace =
            read_or_recover(&self.jn_workspace_from_root_workspace);
        let g_jn_entity_from_workspace_entities =
            read_or_recover(&self.jn_entity_from_workspace_entities);
        let g_jn_feature_from_workspace_features =
            read_or_recover(&self.jn_feature_from_workspace_features);
        let g_jn_global_from_workspace_global =
            read_or_recover(&self.jn_global_from_workspace_global);
        let g_jn_user_interface_from_workspace_user_interface =
            read_or_recover(&self.jn_user_interface_from_workspace_user_interface);
        let g_jn_file_from_system_files = read_or_recover(&self.jn_file_from_system_files);
        let g_jn_field_from_entity_fields = read_or_recover(&self.jn_field_from_entity_fields);
        let g_jn_entity_from_entity_inherits_from =
            read_or_recover(&self.jn_entity_from_entity_inherits_from);
        let g_jn_relationship_from_entity_relationships =
            read_or_recover(&self.jn_relationship_from_entity_relationships);
        let g_jn_entity_from_field_entity = read_or_recover(&self.jn_entity_from_field_entity);
        let g_jn_use_case_from_feature_use_cases =
            read_or_recover(&self.jn_use_case_from_feature_use_cases);
        let g_jn_entity_from_file_entity = read_or_recover(&self.jn_entity_from_file_entity);
        let g_jn_feature_from_file_feature = read_or_recover(&self.jn_feature_from_file_feature);
        let g_jn_field_from_file_field = read_or_recover(&self.jn_field_from_file_field);
        let g_jn_use_case_from_file_use_case =
            read_or_recover(&self.jn_use_case_from_file_use_case);
        let g_jn_dto_from_use_case_dto_in = read_or_recover(&self.jn_dto_from_use_case_dto_in);
        let g_jn_dto_from_use_case_dto_out = read_or_recover(&self.jn_dto_from_use_case_dto_out);
        let g_jn_entity_from_use_case_entities =
            read_or_recover(&self.jn_entity_from_use_case_entities);
        let g_jn_dto_field_from_dto_fields = read_or_recover(&self.jn_dto_field_from_dto_fields);
        let g_jn_entity_from_relationship_left_entity =
            read_or_recover(&self.jn_entity_from_relationship_left_entity);
        let g_jn_entity_from_relationship_right_entity =
            read_or_recover(&self.jn_entity_from_relationship_right_entity);
        let g_counters = read_or_recover(&self.counters);

        HashMapStore {
            roots: RwLock::new(g_roots.clone()),
            workspaces: RwLock::new(g_workspaces.clone()),
            systems: RwLock::new(g_systems.clone()),
            entities: RwLock::new(g_entities.clone()),
            fields: RwLock::new(g_fields.clone()),
            features: RwLock::new(g_features.clone()),
            files: RwLock::new(g_files.clone()),
            use_cases: RwLock::new(g_use_cases.clone()),
            dtos: RwLock::new(g_dtos.clone()),
            dto_fields: RwLock::new(g_dto_fields.clone()),
            globals: RwLock::new(g_globals.clone()),
            relationships: RwLock::new(g_relationships.clone()),
            user_interfaces: RwLock::new(g_user_interfaces.clone()),
            jn_system_from_root_system: RwLock::new(g_jn_system_from_root_system.clone()),
            jn_workspace_from_root_workspace: RwLock::new(
                g_jn_workspace_from_root_workspace.clone(),
            ),
            jn_entity_from_workspace_entities: RwLock::new(
                g_jn_entity_from_workspace_entities.clone(),
            ),
            jn_feature_from_workspace_features: RwLock::new(
                g_jn_feature_from_workspace_features.clone(),
            ),
            jn_global_from_workspace_global: RwLock::new(g_jn_global_from_workspace_global.clone()),
            jn_user_interface_from_workspace_user_interface: RwLock::new(
                g_jn_user_interface_from_workspace_user_interface.clone(),
            ),
            jn_file_from_system_files: RwLock::new(g_jn_file_from_system_files.clone()),
            jn_field_from_entity_fields: RwLock::new(g_jn_field_from_entity_fields.clone()),
            jn_entity_from_entity_inherits_from: RwLock::new(
                g_jn_entity_from_entity_inherits_from.clone(),
            ),
            jn_relationship_from_entity_relationships: RwLock::new(
                g_jn_relationship_from_entity_relationships.clone(),
            ),
            jn_entity_from_field_entity: RwLock::new(g_jn_entity_from_field_entity.clone()),
            jn_use_case_from_feature_use_cases: RwLock::new(
                g_jn_use_case_from_feature_use_cases.clone(),
            ),
            jn_entity_from_file_entity: RwLock::new(g_jn_entity_from_file_entity.clone()),
            jn_feature_from_file_feature: RwLock::new(g_jn_feature_from_file_feature.clone()),
            jn_field_from_file_field: RwLock::new(g_jn_field_from_file_field.clone()),
            jn_use_case_from_file_use_case: RwLock::new(g_jn_use_case_from_file_use_case.clone()),
            jn_dto_from_use_case_dto_in: RwLock::new(g_jn_dto_from_use_case_dto_in.clone()),
            jn_dto_from_use_case_dto_out: RwLock::new(g_jn_dto_from_use_case_dto_out.clone()),
            jn_entity_from_use_case_entities: RwLock::new(
                g_jn_entity_from_use_case_entities.clone(),
            ),
            jn_dto_field_from_dto_fields: RwLock::new(g_jn_dto_field_from_dto_fields.clone()),
            jn_entity_from_relationship_left_entity: RwLock::new(
                g_jn_entity_from_relationship_left_entity.clone(),
            ),
            jn_entity_from_relationship_right_entity: RwLock::new(
                g_jn_entity_from_relationship_right_entity.clone(),
            ),
            counters: RwLock::new(g_counters.clone()),
            savepoints: RwLock::new(std::collections::HashMap::new()),
            next_savepoint_id: RwLock::new(0),
        }
    }

    /// Restore from a savepoint snapshot.
    pub fn restore(&self, snap: &HashMapStoreSnapshot) {
        *write_or_recover(&self.roots) = snap.roots.clone();
        *write_or_recover(&self.workspaces) = snap.workspaces.clone();
        *write_or_recover(&self.systems) = snap.systems.clone();
        *write_or_recover(&self.entities) = snap.entities.clone();
        *write_or_recover(&self.fields) = snap.fields.clone();
        *write_or_recover(&self.features) = snap.features.clone();
        *write_or_recover(&self.files) = snap.files.clone();
        *write_or_recover(&self.use_cases) = snap.use_cases.clone();
        *write_or_recover(&self.dtos) = snap.dtos.clone();
        *write_or_recover(&self.dto_fields) = snap.dto_fields.clone();
        *write_or_recover(&self.globals) = snap.globals.clone();
        *write_or_recover(&self.relationships) = snap.relationships.clone();
        *write_or_recover(&self.user_interfaces) = snap.user_interfaces.clone();
        *write_or_recover(&self.jn_system_from_root_system) =
            snap.jn_system_from_root_system.clone();
        *write_or_recover(&self.jn_workspace_from_root_workspace) =
            snap.jn_workspace_from_root_workspace.clone();
        *write_or_recover(&self.jn_entity_from_workspace_entities) =
            snap.jn_entity_from_workspace_entities.clone();
        *write_or_recover(&self.jn_feature_from_workspace_features) =
            snap.jn_feature_from_workspace_features.clone();
        *write_or_recover(&self.jn_global_from_workspace_global) =
            snap.jn_global_from_workspace_global.clone();
        *write_or_recover(&self.jn_user_interface_from_workspace_user_interface) =
            snap.jn_user_interface_from_workspace_user_interface.clone();
        *write_or_recover(&self.jn_file_from_system_files) = snap.jn_file_from_system_files.clone();
        *write_or_recover(&self.jn_field_from_entity_fields) =
            snap.jn_field_from_entity_fields.clone();
        *write_or_recover(&self.jn_entity_from_entity_inherits_from) =
            snap.jn_entity_from_entity_inherits_from.clone();
        *write_or_recover(&self.jn_relationship_from_entity_relationships) =
            snap.jn_relationship_from_entity_relationships.clone();
        *write_or_recover(&self.jn_entity_from_field_entity) =
            snap.jn_entity_from_field_entity.clone();
        *write_or_recover(&self.jn_use_case_from_feature_use_cases) =
            snap.jn_use_case_from_feature_use_cases.clone();
        *write_or_recover(&self.jn_entity_from_file_entity) =
            snap.jn_entity_from_file_entity.clone();
        *write_or_recover(&self.jn_feature_from_file_feature) =
            snap.jn_feature_from_file_feature.clone();
        *write_or_recover(&self.jn_field_from_file_field) = snap.jn_field_from_file_field.clone();
        *write_or_recover(&self.jn_use_case_from_file_use_case) =
            snap.jn_use_case_from_file_use_case.clone();
        *write_or_recover(&self.jn_dto_from_use_case_dto_in) =
            snap.jn_dto_from_use_case_dto_in.clone();
        *write_or_recover(&self.jn_dto_from_use_case_dto_out) =
            snap.jn_dto_from_use_case_dto_out.clone();
        *write_or_recover(&self.jn_entity_from_use_case_entities) =
            snap.jn_entity_from_use_case_entities.clone();
        *write_or_recover(&self.jn_dto_field_from_dto_fields) =
            snap.jn_dto_field_from_dto_fields.clone();
        *write_or_recover(&self.jn_entity_from_relationship_left_entity) =
            snap.jn_entity_from_relationship_left_entity.clone();
        *write_or_recover(&self.jn_entity_from_relationship_right_entity) =
            snap.jn_entity_from_relationship_right_entity.clone();
        *write_or_recover(&self.counters) = snap.counters.clone();
    }

    /// Create a savepoint by snapshotting the entire store. Returns a savepoint id.
    /// O(1) thanks to im::HashMap structural sharing.
    pub fn create_savepoint(&self) -> u64 {
        let snap = self.snapshot();
        let mut id_counter = write_or_recover(&self.next_savepoint_id);
        let id = *id_counter;
        *id_counter += 1;
        write_or_recover(&self.savepoints).insert(id, snap);
        id
    }

    /// Restore the store to a previously created savepoint.
    pub fn restore_savepoint(&self, savepoint_id: u64) {
        // A missing savepoint is a caller bug, but this is reached from
        // `Transaction`'s **`Drop`-time rollback** — and panicking in a `Drop`
        // that is itself running because of an earlier panic aborts the process
        // outright, no matter what the panic strategy is. That double-panic is
        // exactly what this module's poison recovery exists to avoid, so the
        // rollback must not be the thing that reintroduces it.
        //
        // Loud in a debug build, a no-op in a shipped one: nothing to restore
        // to means the store simply stays as it is.
        let Some(snap) = read_or_recover(&self.savepoints)
            .get(&savepoint_id)
            .cloned()
        else {
            debug_assert!(
                false,
                "restore_savepoint: savepoint {savepoint_id} does not exist — it was already \
                 restored, discarded, or never created"
            );
            return;
        };
        self.restore(&snap);
    }

    /// Discard a savepoint without restoring (used on successful commit, and
    /// after a rollback so a rolled-back transaction doesn't leak its snapshot).
    pub fn discard_savepoint(&self, savepoint_id: u64) {
        write_or_recover(&self.savepoints).remove(&savepoint_id);
    }

    /// Get-and-increment counter for an entity type.
    pub(crate) fn next_id(&self, entity_name: &str) -> EntityId {
        let mut counters = write_or_recover(&self.counters);
        let counter = counters.entry(entity_name.to_string()).or_insert(1);
        let id = *counter;
        *counter += 1;
        id
    }

    /// Restore entity and junction data but preserve current counters.
    /// Used for undo snapshots where IDs must remain monotonically increasing.
    pub fn restore_without_counters(&self, snap: &HashMapStoreSnapshot) {
        *write_or_recover(&self.roots) = snap.roots.clone();
        *write_or_recover(&self.workspaces) = snap.workspaces.clone();
        *write_or_recover(&self.systems) = snap.systems.clone();
        *write_or_recover(&self.entities) = snap.entities.clone();
        *write_or_recover(&self.fields) = snap.fields.clone();
        *write_or_recover(&self.features) = snap.features.clone();
        *write_or_recover(&self.files) = snap.files.clone();
        *write_or_recover(&self.use_cases) = snap.use_cases.clone();
        *write_or_recover(&self.dtos) = snap.dtos.clone();
        *write_or_recover(&self.dto_fields) = snap.dto_fields.clone();
        *write_or_recover(&self.globals) = snap.globals.clone();
        *write_or_recover(&self.relationships) = snap.relationships.clone();
        *write_or_recover(&self.user_interfaces) = snap.user_interfaces.clone();
        *write_or_recover(&self.jn_system_from_root_system) =
            snap.jn_system_from_root_system.clone();
        *write_or_recover(&self.jn_workspace_from_root_workspace) =
            snap.jn_workspace_from_root_workspace.clone();
        *write_or_recover(&self.jn_entity_from_workspace_entities) =
            snap.jn_entity_from_workspace_entities.clone();
        *write_or_recover(&self.jn_feature_from_workspace_features) =
            snap.jn_feature_from_workspace_features.clone();
        *write_or_recover(&self.jn_global_from_workspace_global) =
            snap.jn_global_from_workspace_global.clone();
        *write_or_recover(&self.jn_user_interface_from_workspace_user_interface) =
            snap.jn_user_interface_from_workspace_user_interface.clone();
        *write_or_recover(&self.jn_file_from_system_files) = snap.jn_file_from_system_files.clone();
        *write_or_recover(&self.jn_field_from_entity_fields) =
            snap.jn_field_from_entity_fields.clone();
        *write_or_recover(&self.jn_entity_from_entity_inherits_from) =
            snap.jn_entity_from_entity_inherits_from.clone();
        *write_or_recover(&self.jn_relationship_from_entity_relationships) =
            snap.jn_relationship_from_entity_relationships.clone();
        *write_or_recover(&self.jn_entity_from_field_entity) =
            snap.jn_entity_from_field_entity.clone();
        *write_or_recover(&self.jn_use_case_from_feature_use_cases) =
            snap.jn_use_case_from_feature_use_cases.clone();
        *write_or_recover(&self.jn_entity_from_file_entity) =
            snap.jn_entity_from_file_entity.clone();
        *write_or_recover(&self.jn_feature_from_file_feature) =
            snap.jn_feature_from_file_feature.clone();
        *write_or_recover(&self.jn_field_from_file_field) = snap.jn_field_from_file_field.clone();
        *write_or_recover(&self.jn_use_case_from_file_use_case) =
            snap.jn_use_case_from_file_use_case.clone();
        *write_or_recover(&self.jn_dto_from_use_case_dto_in) =
            snap.jn_dto_from_use_case_dto_in.clone();
        *write_or_recover(&self.jn_dto_from_use_case_dto_out) =
            snap.jn_dto_from_use_case_dto_out.clone();
        *write_or_recover(&self.jn_entity_from_use_case_entities) =
            snap.jn_entity_from_use_case_entities.clone();
        *write_or_recover(&self.jn_dto_field_from_dto_fields) =
            snap.jn_dto_field_from_dto_fields.clone();
        *write_or_recover(&self.jn_entity_from_relationship_left_entity) =
            snap.jn_entity_from_relationship_left_entity.clone();
        *write_or_recover(&self.jn_entity_from_relationship_right_entity) =
            snap.jn_entity_from_relationship_right_entity.clone();
        // counters intentionally NOT restored — IDs must remain monotonically increasing
    }

    /// Create a type-erased store snapshot for undo.
    pub fn store_snapshot(&self) -> StoreSnapshot {
        StoreSnapshot::new(self.snapshot())
    }

    /// Restore from a type-erased store snapshot (preserves counters).
    pub fn restore_store_snapshot(&self, snap: &StoreSnapshot) {
        let s = snap
            .downcast_ref::<HashMapStoreSnapshot>()
            .expect("StoreSnapshot must contain HashMapStoreSnapshot");
        self.restore_without_counters(s);
    }
}

/// Snapshot of the entire store. O(1) to create thanks to im::HashMap structural sharing.
///
/// Entity-table and junction fields are `pub(crate)` so the generated per-entity
/// repositories (same crate) can read the captured rows/junctions during a *scoped*
/// restore. Counters stay private (restore never touches them — ids stay monotonic).
#[derive(Debug, Clone)]
pub struct HashMapStoreSnapshot {
    pub(crate) roots: HashMap<EntityId, Root>,
    pub(crate) workspaces: HashMap<EntityId, Workspace>,
    pub(crate) systems: HashMap<EntityId, System>,
    pub(crate) entities: HashMap<EntityId, Entity>,
    pub(crate) fields: HashMap<EntityId, Field>,
    pub(crate) features: HashMap<EntityId, Feature>,
    pub(crate) files: HashMap<EntityId, File>,
    pub(crate) use_cases: HashMap<EntityId, UseCase>,
    pub(crate) dtos: HashMap<EntityId, Dto>,
    pub(crate) dto_fields: HashMap<EntityId, DtoField>,
    pub(crate) globals: HashMap<EntityId, Global>,
    pub(crate) relationships: HashMap<EntityId, Relationship>,
    pub(crate) user_interfaces: HashMap<EntityId, UserInterface>,
    pub(crate) jn_system_from_root_system: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_workspace_from_root_workspace: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_entity_from_workspace_entities: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_feature_from_workspace_features: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_global_from_workspace_global: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_user_interface_from_workspace_user_interface: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_file_from_system_files: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_field_from_entity_fields: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_entity_from_entity_inherits_from: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_relationship_from_entity_relationships: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_entity_from_field_entity: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_use_case_from_feature_use_cases: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_entity_from_file_entity: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_feature_from_file_feature: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_field_from_file_field: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_use_case_from_file_use_case: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_dto_from_use_case_dto_in: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_dto_from_use_case_dto_out: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_entity_from_use_case_entities: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_dto_field_from_dto_fields: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_entity_from_relationship_left_entity: HashMap<EntityId, Vec<EntityId>>,
    pub(crate) jn_entity_from_relationship_right_entity: HashMap<EntityId, Vec<EntityId>>,
    counters: std::collections::HashMap<String, EntityId>,
}

impl StoreSnapshotTrait for HashMapStoreSnapshot {
    fn clone_box(&self) -> Box<dyn StoreSnapshotTrait> {
        Box::new(self.clone())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Helper functions
// ─────────────────────────────────────────────────────────────────────────────

/// Acquire a read guard, recovering the inner value if the lock was poisoned by
/// a panic elsewhere — and **clearing** the poison so recovery is permanent, not
/// one-shot (a recovered-but-still-poisoned lock would re-panic on the next plain
/// `.read()/.write().unwrap()`). Used throughout the store's own snapshot /
/// savepoint / restore paths so a single table poisoned by an unrelated panic
/// can't escalate a rollback (the Drop-time `restore_savepoint`) — or the very
/// next write transaction's `create_savepoint` — into a process-wide abort.
pub(crate) fn read_or_recover<T>(lock: &RwLock<T>) -> std::sync::RwLockReadGuard<'_, T> {
    match lock.read() {
        Ok(guard) => guard,
        Err(poisoned) => {
            let guard = poisoned.into_inner();
            lock.clear_poison();
            guard
        }
    }
}

/// Write-guard counterpart of [`read_or_recover`] (also clears the poison).
pub(crate) fn write_or_recover<T>(lock: &RwLock<T>) -> std::sync::RwLockWriteGuard<'_, T> {
    match lock.write() {
        Ok(guard) => guard,
        Err(poisoned) => {
            let guard = poisoned.into_inner();
            lock.clear_poison();
            guard
        }
    }
}

pub(crate) fn delete_from_backward_junction(
    junction: &RwLock<HashMap<EntityId, Vec<EntityId>>>,
    id: &EntityId,
) {
    let mut jn = write_or_recover(junction);
    let keys: Vec<EntityId> = jn.keys().copied().collect();
    for k in keys {
        // A let-chain rather than nested ifs: clippy's `collapsible_if` rejects
        // the nested form under `-D warnings`, and the generated crates are
        // edition 2024, so the chain is available.
        if let Some(right_ids) = jn.get(&k)
            && right_ids.contains(id)
        {
            let filtered: Vec<EntityId> =
                right_ids.iter().copied().filter(|eid| eid != id).collect();
            jn.insert(k, filtered);
        }
    }
}

pub(crate) fn junction_get(
    junction: &RwLock<HashMap<EntityId, Vec<EntityId>>>,
    id: &EntityId,
) -> Vec<EntityId> {
    read_or_recover(junction)
        .get(id)
        .cloned()
        .unwrap_or_default()
}

pub(crate) fn junction_set(
    junction: &RwLock<HashMap<EntityId, Vec<EntityId>>>,
    id: EntityId,
    ids: Vec<EntityId>,
) {
    write_or_recover(junction).insert(id, ids);
}

pub(crate) fn junction_remove(junction: &RwLock<HashMap<EntityId, Vec<EntityId>>>, id: &EntityId) {
    write_or_recover(junction).remove(id);
}

pub(crate) fn junction_get_relationships_from_right_ids(
    junction: &RwLock<HashMap<EntityId, Vec<EntityId>>>,
    right_ids: &[EntityId],
) -> Vec<(EntityId, Vec<EntityId>)> {
    let jn = read_or_recover(junction);
    jn.iter()
        .filter(|(_, rids)| right_ids.iter().any(|eid| rids.contains(eid)))
        .map(|(left_id, rids)| (*left_id, rids.clone()))
        .collect()
}

pub(crate) fn junction_move_ids(
    junction: &RwLock<HashMap<EntityId, Vec<EntityId>>>,
    id: &EntityId,
    ids_to_move: &[EntityId],
    new_index: i32,
) -> Vec<EntityId> {
    let current = junction_get(junction, id);
    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);
    }
    junction_set(junction, *id, remaining.clone());
    remaining
}

/// Surgically reconcile an external (out-of-scope) junction list during a scoped undo restore.
///
/// `live_list` is the current ordered value of an external referrer's junction row; `snap_list`
/// is the same row at snapshot time; `scope` is the set of subtree ids being restored. Only the
/// membership/position of `scope` ids is reconciled to match the snapshot — non-scope siblings are
/// preserved in their current relative order. Scope ids absent from the snapshot are removed
/// (undo-of-create); scope ids present in the snapshot are re-inserted at their snapshot-relative
/// position (undo-of-remove). This is what keeps undo from clobbering other trunks' edits.
pub(crate) fn reconcile_backref_list(
    live_list: &[EntityId],
    snap_list: &[EntityId],
    scope: &std::collections::HashSet<EntityId>,
) -> Vec<EntityId> {
    // Scope ids that should be present after restore, in snapshot order.
    let snap_members: Vec<EntityId> = snap_list
        .iter()
        .copied()
        .filter(|x| scope.contains(x))
        .collect();
    let snap_member_set: std::collections::HashSet<EntityId> =
        snap_members.iter().copied().collect();

    // Start from the live list, dropping only scope ids that are NOT in the snapshot.
    let mut work: Vec<EntityId> = live_list
        .iter()
        .copied()
        // De Morgan'd from `!(in_scope && !in_snapshot)`: same rule, stated the
        // way clippy's `nonminimal_bool` wants it, and arguably plainer — keep
        // anything outside the scope, plus anything the snapshot still holds.
        .filter(|x| !scope.contains(x) || snap_member_set.contains(x))
        .collect();

    // Re-insert missing scope ids at their snapshot-relative position (count of snapshot
    // predecessors that survive in `work`), so they return next to their original neighbours.
    for id in &snap_members {
        if work.contains(id) {
            continue;
        }
        let snap_idx = snap_list.iter().position(|x| x == id).unwrap_or(0);
        let pos = snap_list[..snap_idx]
            .iter()
            .filter(|x| work.contains(x))
            .count()
            .min(work.len());
        work.insert(pos, *id);
    }
    work
}

// ═════════════════════════════════════════════════════════════════════════════
// Macros for entities WITH relationships (reduces boilerplate)
// ═════════════════════════════════════════════════════════════════════════════

/// Generate standard relationship methods for a HashMap table implementation.
#[macro_export]
macro_rules! impl_relationship_methods {
    ($table_type:ty, $field_enum:ty) => {
        fn get_relationship(
            &self,
            id: &$crate::types::EntityId,
            field: &$field_enum,
        ) -> Result<Vec<$crate::types::EntityId>, $crate::error::RepositoryError> {
            Ok($crate::database::hashmap_store::junction_get(
                self.resolve_junction(field),
                id,
            ))
        }

        fn get_relationship_many(
            &self,
            ids: &[$crate::types::EntityId],
            field: &$field_enum,
        ) -> Result<
            std::collections::HashMap<$crate::types::EntityId, Vec<$crate::types::EntityId>>,
            $crate::error::RepositoryError,
        > {
            let jn = self.resolve_junction(field);
            let mut map = std::collections::HashMap::new();
            for id in ids {
                map.insert(*id, $crate::database::hashmap_store::junction_get(jn, id));
            }
            Ok(map)
        }

        fn get_relationship_count(
            &self,
            id: &$crate::types::EntityId,
            field: &$field_enum,
        ) -> Result<usize, $crate::error::RepositoryError> {
            Ok(
                $crate::database::hashmap_store::junction_get(self.resolve_junction(field), id)
                    .len(),
            )
        }

        fn get_relationship_in_range(
            &self,
            id: &$crate::types::EntityId,
            field: &$field_enum,
            offset: usize,
            limit: usize,
        ) -> Result<Vec<$crate::types::EntityId>, $crate::error::RepositoryError> {
            let all =
                $crate::database::hashmap_store::junction_get(self.resolve_junction(field), id);
            Ok(all.into_iter().skip(offset).take(limit).collect())
        }

        fn get_relationships_from_right_ids(
            &self,
            field: &$field_enum,
            right_ids: &[$crate::types::EntityId],
        ) -> Result<
            Vec<($crate::types::EntityId, Vec<$crate::types::EntityId>)>,
            $crate::error::RepositoryError,
        > {
            Ok(
                $crate::database::hashmap_store::junction_get_relationships_from_right_ids(
                    self.resolve_junction(field),
                    right_ids,
                ),
            )
        }
    };
}

#[macro_export]
macro_rules! impl_write_relationship_methods {
    ($table_type:ty, $field_enum:ty) => {
        $crate::impl_relationship_methods!($table_type, $field_enum);

        fn set_relationship_multi(
            &mut self,
            field: &$field_enum,
            relationships: Vec<($crate::types::EntityId, Vec<$crate::types::EntityId>)>,
        ) -> Result<(), $crate::error::RepositoryError> {
            let jn = self.resolve_junction(field);
            for (left_id, entities) in relationships {
                $crate::database::hashmap_store::junction_set(jn, left_id, entities);
            }
            Ok(())
        }

        fn set_relationship(
            &mut self,
            id: &$crate::types::EntityId,
            field: &$field_enum,
            right_ids: &[$crate::types::EntityId],
        ) -> Result<(), $crate::error::RepositoryError> {
            $crate::database::hashmap_store::junction_set(
                self.resolve_junction(field),
                *id,
                right_ids.to_vec(),
            );
            Ok(())
        }

        fn move_relationship_ids(
            &mut self,
            id: &$crate::types::EntityId,
            field: &$field_enum,
            ids_to_move: &[$crate::types::EntityId],
            new_index: i32,
        ) -> Result<Vec<$crate::types::EntityId>, $crate::error::RepositoryError> {
            Ok($crate::database::hashmap_store::junction_move_ids(
                self.resolve_junction(field),
                id,
                ids_to_move,
                new_index,
            ))
        }
    };
}

// ═════════════════════════════════════════════════════════════════════════════
// Leaf entity macro (entities without forward relationships)
// ═════════════════════════════════════════════════════════════════════════════

#[macro_export]
macro_rules! impl_leaf_entity_table {
    (
        entity: $Entity:ident,
        entity_name: $entity_name:expr,
        store_field: $store_field:ident,
        table_trait: $TableTrait:ident,
        table_ro_trait: $TableROTrait:ident,
        table_struct: $TableStruct:ident,
        table_ro_struct: $TableROStruct:ident,
        backward_junctions: [ $( ($bj_field:ident) ),* $(,)? ],
    ) => {
        pub struct $TableStruct<'a> {
            store: &'a $crate::database::hashmap_store::HashMapStore,
        }

        impl<'a> $TableStruct<'a> {
            pub fn new(store: &'a $crate::database::hashmap_store::HashMapStore) -> Self {
                Self { store }
            }
        }

        impl<'a> $TableTrait for $TableStruct<'a> {
            fn create(&mut self, entity: &$Entity) -> Result<$Entity, $crate::error::RepositoryError> {
                self.create_multi(std::slice::from_ref(entity))
                    .and_then(|v| {
                        v.into_iter().next().ok_or_else(|| {
                            $crate::error::RepositoryError::Other(::anyhow::anyhow!(
                                "create: the store returned no row for the entity it was given"
                            ))
                        })
                    })
            }

            fn create_multi(&mut self, entities: &[$Entity]) -> Result<Vec<$Entity>, $crate::error::RepositoryError> {
                let mut created = Vec::with_capacity(entities.len());
                let mut map = $crate::database::hashmap_store::write_or_recover(&self.store.$store_field);

                for entity in entities {
                    let new_entity = if entity.id == $crate::types::EntityId::default() {
                        let id = self.store.next_id($entity_name);
                        $Entity {
                            id,
                            ..entity.clone()
                        }
                    } else {
                        if map.contains_key(&entity.id) {
                            return Err($crate::error::RepositoryError::DuplicateId {
                                entity: stringify!($Entity),
                                id: entity.id,
                            });
                        }
                        entity.clone()
                    };

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

            fn get(&self, id: &$crate::types::EntityId) -> Result<Option<$Entity>, $crate::error::RepositoryError> {
                Ok($crate::database::hashmap_store::read_or_recover(&self.store.$store_field).get(id).cloned())
            }

            fn get_multi(&self, ids: &[$crate::types::EntityId]) -> Result<Vec<Option<$Entity>>, $crate::error::RepositoryError> {
                let map = $crate::database::hashmap_store::read_or_recover(&self.store.$store_field);
                Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
            }

            fn get_all(&self) -> Result<Vec<$Entity>, $crate::error::RepositoryError> {
                Ok($crate::database::hashmap_store::read_or_recover(&self.store.$store_field).values().cloned().collect())
            }

            fn update(&mut self, entity: &$Entity) -> Result<$Entity, $crate::error::RepositoryError> {
                self.update_multi(std::slice::from_ref(entity))
                    .and_then(|v| {
                        v.into_iter().next().ok_or_else(|| {
                            $crate::error::RepositoryError::Other(::anyhow::anyhow!(
                                "update: the store returned no row for the entity it was given"
                            ))
                        })
                    })
            }

            fn update_multi(&mut self, entities: &[$Entity]) -> Result<Vec<$Entity>, $crate::error::RepositoryError> {
                let mut map = $crate::database::hashmap_store::write_or_recover(&self.store.$store_field);
                let mut result = Vec::with_capacity(entities.len());
                for entity in entities {
                    map.insert(entity.id, entity.clone());
                    result.push(entity.clone());
                }
                Ok(result)
            }

            fn update_with_relationships(&mut self, entity: &$Entity) -> Result<$Entity, $crate::error::RepositoryError> {
                self.update(entity)
            }

            fn update_with_relationships_multi(&mut self, entities: &[$Entity]) -> Result<Vec<$Entity>, $crate::error::RepositoryError> {
                self.update_multi(entities)
            }

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

            fn remove_multi(&mut self, ids: &[$crate::types::EntityId]) -> Result<(), $crate::error::RepositoryError> {
                let mut map = $crate::database::hashmap_store::write_or_recover(&self.store.$store_field);
                for id in ids {
                    map.remove(id);
                    $(
                        $crate::database::hashmap_store::delete_from_backward_junction(&self.store.$bj_field, id);
                    )*
                }
                Ok(())
            }
        }

        pub struct $TableROStruct<'a> {
            store: &'a $crate::database::hashmap_store::HashMapStore,
        }

        impl<'a> $TableROStruct<'a> {
            pub fn new(store: &'a $crate::database::hashmap_store::HashMapStore) -> Self {
                Self { store }
            }
        }

        impl<'a> $TableROTrait for $TableROStruct<'a> {
            fn get(&self, id: &$crate::types::EntityId) -> Result<Option<$Entity>, $crate::error::RepositoryError> {
                Ok($crate::database::hashmap_store::read_or_recover(&self.store.$store_field).get(id).cloned())
            }

            fn get_multi(&self, ids: &[$crate::types::EntityId]) -> Result<Vec<Option<$Entity>>, $crate::error::RepositoryError> {
                let map = $crate::database::hashmap_store::read_or_recover(&self.store.$store_field);
                Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
            }

            fn get_all(&self) -> Result<Vec<$Entity>, $crate::error::RepositoryError> {
                Ok($crate::database::hashmap_store::read_or_recover(&self.store.$store_field).values().cloned().collect())
            }
        }
    };
}