icydb-core 0.94.3

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
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
//! Module: db::executor::tests::support
//! Owns shared executor test fixtures, stores, entity schemas, and reset
//! helpers reused across the topical executor owner suites.
//! Does not own: the topical assertions themselves.
//! Boundary: keeps reusable executor test support out of the owner `mod.rs`
//! wiring file.

pub(in crate::db::executor::tests) use crate::{
    db::{
        Db, DbSession, EntityRuntimeHooks,
        commit::{
            CommitMarker, begin_commit, commit_marker_present, ensure_recovered,
            init_commit_store_for_tests, prepare_row_commit_for_entity_with_structural_readers,
        },
        data::DataStore,
        executor::{
            DeleteExecutor, LoadExecutor, PreparedExecutionPlan, SaveExecutor,
            ScalarTerminalBoundaryRequest,
        },
        index::IndexStore,
        predicate::MissingRowPolicy,
        query::intent::Query,
        registry::StoreRegistry,
        relation::validate_delete_strong_relations_for_source,
    },
    error::InternalError,
    metrics::sink::{MetricsEvent, MetricsSink, with_metrics_sink},
    model::{
        field::{FieldKind, RelationStrength},
        index::IndexModel,
    },
    testing::test_memory,
    traits::{EntityKind, EntityValue, Path},
    types::{Ulid, Unit},
};
use icydb_derive::{FieldProjection, PersistedRow};
use serde::Deserialize;
use std::cell::RefCell;

///
/// ScanBudgetCaptureSink
///
/// Small metrics sink shared by executor owner tests that assert row-scan
/// budgets.
///

#[derive(Default)]
pub(in crate::db::executor::tests) struct ScanBudgetCaptureSink {
    events: RefCell<Vec<MetricsEvent>>,
}

impl ScanBudgetCaptureSink {
    fn into_events(self) -> Vec<MetricsEvent> {
        self.events.into_inner()
    }
}

impl MetricsSink for ScanBudgetCaptureSink {
    fn record(&self, event: MetricsEvent) {
        self.events.borrow_mut().push(event);
    }
}

// Sum `RowsScanned` metrics for one entity path under the shared executor test sink.
pub(in crate::db::executor::tests) fn rows_scanned_for_entity(
    events: &[MetricsEvent],
    entity_path: &'static str,
) -> usize {
    events.iter().fold(0usize, |acc, event| {
        let scanned = match event {
            MetricsEvent::RowsScanned {
                entity_path: path,
                rows_scanned,
            } if *path == entity_path => usize::try_from(*rows_scanned).unwrap_or(usize::MAX),
            _ => 0,
        };

        acc.saturating_add(scanned)
    })
}

// Run one closure under the shared executor test sink and return both output and
// scanned-row total for the requested entity path.
pub(in crate::db::executor::tests) fn capture_rows_scanned_for_entity<R>(
    entity_path: &'static str,
    run: impl FnOnce() -> R,
) -> (R, usize) {
    let sink = ScanBudgetCaptureSink::default();
    let output = with_metrics_sink(&sink, run);
    let rows_scanned = rows_scanned_for_entity(&sink.into_events(), entity_path);

    (output, rows_scanned)
}

// Execute one shared COUNT scalar terminal from executor owner tests.
pub(in crate::db::executor::tests) fn execute_count_terminal<E>(
    load: &LoadExecutor<E>,
    plan: PreparedExecutionPlan<E>,
) -> Result<u32, InternalError>
where
    E: EntityKind + EntityValue,
{
    load.execute_scalar_terminal_request(plan, ScalarTerminalBoundaryRequest::Count)?
        .into_count()
}

// Execute one shared EXISTS scalar terminal from executor owner tests.
pub(in crate::db::executor::tests) fn execute_exists_terminal<E>(
    load: &LoadExecutor<E>,
    plan: PreparedExecutionPlan<E>,
) -> Result<bool, InternalError>
where
    E: EntityKind + EntityValue,
{
    load.execute_scalar_terminal_request(plan, ScalarTerminalBoundaryRequest::Exists)?
        .into_exists()
}

// TestCanister

pub(in crate::db::executor::tests) struct TestCanister;

impl Path for TestCanister {
    const PATH: &'static str = concat!(module_path!(), "::TestCanister");
}

impl crate::traits::CanisterKind for TestCanister {
    const COMMIT_MEMORY_ID: u8 = crate::testing::test_commit_memory_id();
}

// TestDataStore

pub(in crate::db::executor::tests) struct TestDataStore;

impl Path for TestDataStore {
    const PATH: &'static str = concat!(module_path!(), "::TestDataStore");
}

impl crate::traits::StoreKind for TestDataStore {
    type Canister = TestCanister;
}

thread_local! {
    pub(in crate::db::executor::tests) static DATA_STORE: RefCell<DataStore> =
        RefCell::new(DataStore::init(test_memory(0)));
    pub(in crate::db::executor::tests) static INDEX_STORE: RefCell<IndexStore> =
        RefCell::new(IndexStore::init(test_memory(1)));
    pub(in crate::db::executor::tests) static STORE_REGISTRY: StoreRegistry = {
        let mut reg = StoreRegistry::new();
        reg.register_store(TestDataStore::PATH, &DATA_STORE, &INDEX_STORE)
            .expect("test store registration should succeed");
        reg
    };
}

pub(in crate::db::executor::tests) static DB: Db<TestCanister> = Db::new(&STORE_REGISTRY);

///
/// SimpleEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
pub(in crate::db::executor::tests) struct SimpleEntity {
    pub(in crate::db::executor::tests) id: Ulid,
}

crate::test_entity_schema! {
    ident = SimpleEntity,
    id = Ulid,
    id_field = id,
    entity_name = "SimpleEntity",
    entity_tag = crate::testing::SIMPLE_ENTITY_TAG,
    pk_index = 0,
    fields = [("id", FieldKind::Ulid)],
    indexes = [],
    store = TestDataStore,
    canister = TestCanister,
}

///
/// SingletonUnitEntity
///
/// Executor-lifecycle singleton fixture used to keep runtime `only()` load
/// behavior covered after the old semantics harness was pruned.
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
pub(in crate::db::executor::tests) struct SingletonUnitEntity {
    pub(in crate::db::executor::tests) id: Unit,
    pub(in crate::db::executor::tests) label: String,
}

crate::test_entity_schema! {
    ident = SingletonUnitEntity,
    id = Unit,
    id_field = id,
    singleton = true,
    entity_name = "SingletonUnitEntity",
    entity_tag = crate::testing::SINGLETON_UNIT_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Unit),
        ("label", FieldKind::Text),
    ],
    indexes = [],
    store = TestDataStore,
    canister = TestCanister,
}

///
/// IndexedMetricsEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
pub(in crate::db::executor::tests) struct IndexedMetricsEntity {
    pub(in crate::db::executor::tests) id: Ulid,
    pub(in crate::db::executor::tests) tag: u32,
    pub(in crate::db::executor::tests) label: String,
}

pub(in crate::db::executor::tests) static INDEXED_METRICS_INDEX_FIELDS: [&str; 1] = ["tag"];
pub(in crate::db::executor::tests) static INDEXED_METRICS_INDEX_MODELS: [IndexModel; 1] =
    [IndexModel::generated(
        "tag",
        TestDataStore::PATH,
        &INDEXED_METRICS_INDEX_FIELDS,
        false,
    )];

crate::test_entity_schema! {
    ident = IndexedMetricsEntity,
    id = Ulid,
    id_field = id,
    entity_name = "IndexedMetricsEntity",
    entity_tag = crate::testing::INDEXED_METRICS_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        ("tag", FieldKind::Uint),
        ("label", FieldKind::Text),
    ],
    indexes = [&INDEXED_METRICS_INDEX_MODELS[0]],
    store = TestDataStore,
    canister = TestCanister,
}

///
/// PushdownParityEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
pub(in crate::db::executor::tests) struct PushdownParityEntity {
    pub(in crate::db::executor::tests) id: Ulid,
    pub(in crate::db::executor::tests) group: u32,
    pub(in crate::db::executor::tests) rank: u32,
    pub(in crate::db::executor::tests) label: String,
}

pub(in crate::db::executor::tests) static PUSHDOWN_PARITY_INDEX_FIELDS: [&str; 2] =
    ["group", "rank"];
pub(in crate::db::executor::tests) static PUSHDOWN_PARITY_INDEX_MODELS: [IndexModel; 1] =
    [IndexModel::generated(
        "group_rank",
        TestDataStore::PATH,
        &PUSHDOWN_PARITY_INDEX_FIELDS,
        false,
    )];

crate::test_entity_schema! {
    ident = PushdownParityEntity,
    id = Ulid,
    id_field = id,
    entity_name = "PushdownParityEntity",
    entity_tag = crate::testing::PUSHDOWN_PARITY_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        ("group", FieldKind::Uint),
        ("rank", FieldKind::Uint),
        ("label", FieldKind::Text),
    ],
    indexes = [&PUSHDOWN_PARITY_INDEX_MODELS[0]],
    store = TestDataStore,
    canister = TestCanister,
}

///
/// UniqueIndexRangeEntity
///
/// Executor snapshot fixture for unique secondary range access. This keeps the
/// index-range execution snapshot coverage local to the revived executor test
/// harness instead of depending on pruned pagination backlogs.
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
pub(in crate::db::executor::tests) struct UniqueIndexRangeEntity {
    pub(in crate::db::executor::tests) id: Ulid,
    pub(in crate::db::executor::tests) code: u32,
    pub(in crate::db::executor::tests) label: String,
}

pub(in crate::db::executor::tests) static UNIQUE_INDEX_RANGE_INDEX_FIELDS: [&str; 1] = ["code"];
pub(in crate::db::executor::tests) static UNIQUE_INDEX_RANGE_INDEX_MODELS: [IndexModel; 1] =
    [IndexModel::generated(
        "code_unique",
        TestDataStore::PATH,
        &UNIQUE_INDEX_RANGE_INDEX_FIELDS,
        true,
    )];

crate::test_entity_schema! {
    ident = UniqueIndexRangeEntity,
    id = Ulid,
    id_field = id,
    entity_name = "UniqueIndexRangeEntity",
    entity_tag = crate::testing::UNIQUE_INDEX_RANGE_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        ("code", FieldKind::Uint),
        ("label", FieldKind::Text),
    ],
    indexes = [&UNIQUE_INDEX_RANGE_INDEX_MODELS[0]],
    store = TestDataStore,
    canister = TestCanister,
}

///
/// PhaseEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
pub(in crate::db::executor::tests) struct PhaseEntity {
    pub(in crate::db::executor::tests) id: Ulid,
    pub(in crate::db::executor::tests) opt_rank: Option<u32>,
    pub(in crate::db::executor::tests) rank: u32,
    pub(in crate::db::executor::tests) tags: Vec<u32>,
    pub(in crate::db::executor::tests) label: String,
}

pub(in crate::db::executor::tests) static PHASE_TAG_KIND: FieldKind = FieldKind::Uint;

crate::impl_test_entity_markers!(PhaseEntity);

crate::impl_test_entity_model_storage!(
    PhaseEntity,
    "PhaseEntity",
    0,
    fields = [
        crate::model::field::FieldModel::generated("id", FieldKind::Ulid),
        crate::model::field::FieldModel::generated_with_storage_decode_and_nullability(
            "opt_rank",
            FieldKind::Uint,
            crate::model::field::FieldStorageDecode::ByKind,
            true,
        ),
        crate::model::field::FieldModel::generated("rank", FieldKind::Uint),
        crate::model::field::FieldModel::generated("tags", FieldKind::List(&PHASE_TAG_KIND)),
        crate::model::field::FieldModel::generated("label", FieldKind::Text)
    ],
    indexes = [],
);

crate::impl_test_entity_runtime_surface!(PhaseEntity, Ulid, "PhaseEntity", MODEL_DEF);

impl crate::traits::EntityPlacement for PhaseEntity {
    type Store = TestDataStore;
    type Canister = TestCanister;
}

impl crate::traits::EntityKind for PhaseEntity {
    const ENTITY_TAG: crate::types::EntityTag = crate::testing::PHASE_ENTITY_TAG;
}

impl crate::traits::EntityValue for PhaseEntity {
    fn id(&self) -> crate::types::Id<Self> {
        crate::types::Id::from_key(self.id)
    }
}

// Clear the test data store and any pending commit marker between runs.
pub(in crate::db::executor::tests) fn reset_store() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    ensure_recovered(&DB).expect("write-side recovery should succeed");
    DATA_STORE.with(|store| store.borrow_mut().clear());
    INDEX_STORE.with(|store| store.borrow_mut().clear());
}

// RelationTestCanister

pub(in crate::db::executor::tests) struct RelationTestCanister;

impl Path for RelationTestCanister {
    const PATH: &'static str = concat!(module_path!(), "::RelationTestCanister");
}

impl crate::traits::CanisterKind for RelationTestCanister {
    const COMMIT_MEMORY_ID: u8 = crate::testing::test_commit_memory_id();
}

// RelationSourceStore

pub(in crate::db::executor::tests) struct RelationSourceStore;

impl Path for RelationSourceStore {
    const PATH: &'static str = concat!(module_path!(), "::RelationSourceStore");
}

impl crate::traits::StoreKind for RelationSourceStore {
    type Canister = RelationTestCanister;
}

// RelationTargetStore

pub(in crate::db::executor::tests) struct RelationTargetStore;

impl Path for RelationTargetStore {
    const PATH: &'static str = concat!(module_path!(), "::RelationTargetStore");
}

impl crate::traits::StoreKind for RelationTargetStore {
    type Canister = RelationTestCanister;
}

thread_local! {
    pub(in crate::db::executor::tests) static REL_SOURCE_STORE: RefCell<DataStore> =
        RefCell::new(DataStore::init(test_memory(40)));
    pub(in crate::db::executor::tests) static REL_TARGET_STORE: RefCell<DataStore> =
        RefCell::new(DataStore::init(test_memory(41)));
    pub(in crate::db::executor::tests) static REL_SOURCE_INDEX_STORE: RefCell<IndexStore> =
        RefCell::new(IndexStore::init(test_memory(42)));
    pub(in crate::db::executor::tests) static REL_TARGET_INDEX_STORE: RefCell<IndexStore> =
        RefCell::new(IndexStore::init(test_memory(43)));
    pub(in crate::db::executor::tests) static REL_STORE_REGISTRY: StoreRegistry = {
        let mut reg = StoreRegistry::new();
        reg.register_store(
            RelationSourceStore::PATH,
            &REL_SOURCE_STORE,
            &REL_SOURCE_INDEX_STORE,
        )
        .expect("relation source store registration should succeed");
        reg.register_store(
            RelationTargetStore::PATH,
            &REL_TARGET_STORE,
            &REL_TARGET_INDEX_STORE,
        )
        .expect("relation target store registration should succeed");
        reg
    };
}

pub(in crate::db::executor::tests) static REL_ENTITY_RUNTIME_HOOKS: &[EntityRuntimeHooks<
    RelationTestCanister,
>] = &[
    EntityRuntimeHooks::new(
        RelationTargetEntity::ENTITY_TAG,
        <RelationTargetEntity as crate::traits::EntitySchema>::MODEL,
        RelationTargetEntity::PATH,
        RelationTargetStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<RelationTargetEntity>,
        validate_delete_strong_relations_for_source::<RelationTargetEntity>,
    ),
    EntityRuntimeHooks::new(
        RelationSourceEntity::ENTITY_TAG,
        <RelationSourceEntity as crate::traits::EntitySchema>::MODEL,
        RelationSourceEntity::PATH,
        RelationSourceStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<RelationSourceEntity>,
        validate_delete_strong_relations_for_source::<RelationSourceEntity>,
    ),
    EntityRuntimeHooks::new(
        WeakSingleRelationSourceEntity::ENTITY_TAG,
        <WeakSingleRelationSourceEntity as crate::traits::EntitySchema>::MODEL,
        WeakSingleRelationSourceEntity::PATH,
        RelationSourceStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<WeakSingleRelationSourceEntity>,
        validate_delete_strong_relations_for_source::<WeakSingleRelationSourceEntity>,
    ),
    EntityRuntimeHooks::new(
        WeakOptionalRelationSourceEntity::ENTITY_TAG,
        <WeakOptionalRelationSourceEntity as crate::traits::EntitySchema>::MODEL,
        WeakOptionalRelationSourceEntity::PATH,
        RelationSourceStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<WeakOptionalRelationSourceEntity>,
        validate_delete_strong_relations_for_source::<WeakOptionalRelationSourceEntity>,
    ),
    EntityRuntimeHooks::new(
        WeakListRelationSourceEntity::ENTITY_TAG,
        <WeakListRelationSourceEntity as crate::traits::EntitySchema>::MODEL,
        WeakListRelationSourceEntity::PATH,
        RelationSourceStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<WeakListRelationSourceEntity>,
        validate_delete_strong_relations_for_source::<WeakListRelationSourceEntity>,
    ),
];

pub(in crate::db::executor::tests) static REL_DB: Db<RelationTestCanister> =
    Db::new_with_hooks(&REL_STORE_REGISTRY, REL_ENTITY_RUNTIME_HOOKS);

///
/// RelationTargetEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
pub(in crate::db::executor::tests) struct RelationTargetEntity {
    pub(in crate::db::executor::tests) id: Ulid,
}

crate::test_entity_schema! {
    ident = RelationTargetEntity,
    id = Ulid,
    id_field = id,
    entity_name = "RelationTargetEntity",
    entity_tag = crate::testing::RELATION_TARGET_ENTITY_TAG,
    pk_index = 0,
    fields = [("id", FieldKind::Ulid)],
    indexes = [],
    store = RelationTargetStore,
    canister = RelationTestCanister,
}

///
/// RelationSourceEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
pub(in crate::db::executor::tests) struct RelationSourceEntity {
    pub(in crate::db::executor::tests) id: Ulid,
    pub(in crate::db::executor::tests) target: Ulid,
}

crate::test_entity_schema! {
    ident = RelationSourceEntity,
    id = Ulid,
    id_field = id,
    entity_name = "RelationSourceEntity",
    entity_tag = crate::testing::RELATION_SOURCE_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        (
            "target",
            FieldKind::Relation {
                target_path: RelationTargetEntity::PATH,
                target_entity_name:
                    <RelationTargetEntity as crate::traits::EntitySchema>::MODEL.name(),
                target_entity_tag: RelationTargetEntity::ENTITY_TAG,
                target_store_path: RelationTargetStore::PATH,
                key_kind: &FieldKind::Ulid,
                strength: RelationStrength::Strong,
            }
        ),
    ],
    indexes = [],
    store = RelationSourceStore,
    canister = RelationTestCanister,
}

///
/// WeakSingleRelationSourceEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
pub(in crate::db::executor::tests) struct WeakSingleRelationSourceEntity {
    pub(in crate::db::executor::tests) id: Ulid,
    pub(in crate::db::executor::tests) target: Ulid,
}

crate::test_entity_schema! {
    ident = WeakSingleRelationSourceEntity,
    id = Ulid,
    id_field = id,
    entity_name = "WeakSingleRelationSourceEntity",
    entity_tag = crate::testing::WEAK_SINGLE_RELATION_SOURCE_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        (
            "target",
            FieldKind::Relation {
                target_path: RelationTargetEntity::PATH,
                target_entity_name:
                    <RelationTargetEntity as crate::traits::EntitySchema>::MODEL.name(),
                target_entity_tag: RelationTargetEntity::ENTITY_TAG,
                target_store_path: RelationTargetStore::PATH,
                key_kind: &FieldKind::Ulid,
                strength: RelationStrength::Weak,
            }
        ),
    ],
    indexes = [],
    store = RelationSourceStore,
    canister = RelationTestCanister,
}

///
/// WeakOptionalRelationSourceEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
pub(in crate::db::executor::tests) struct WeakOptionalRelationSourceEntity {
    pub(in crate::db::executor::tests) id: Ulid,
    pub(in crate::db::executor::tests) target: Option<Ulid>,
}

crate::test_entity_schema! {
    ident = WeakOptionalRelationSourceEntity,
    id = Ulid,
    id_field = id,
    entity_name = "WeakOptionalRelationSourceEntity",
    entity_tag = crate::testing::WEAK_OPTIONAL_RELATION_SOURCE_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        (
            "target",
            FieldKind::Relation {
                target_path: RelationTargetEntity::PATH,
                target_entity_name:
                    <RelationTargetEntity as crate::traits::EntitySchema>::MODEL.name(),
                target_entity_tag: RelationTargetEntity::ENTITY_TAG,
                target_store_path: RelationTargetStore::PATH,
                key_kind: &FieldKind::Ulid,
                strength: RelationStrength::Weak,
            }
        ),
    ],
    indexes = [],
    store = RelationSourceStore,
    canister = RelationTestCanister,
}

///
/// WeakListRelationSourceEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
pub(in crate::db::executor::tests) struct WeakListRelationSourceEntity {
    pub(in crate::db::executor::tests) id: Ulid,
    pub(in crate::db::executor::tests) targets: Vec<Ulid>,
}

pub(in crate::db::executor::tests) static REL_WEAK_LIST_TARGET_KIND: FieldKind =
    FieldKind::Relation {
        target_path: RelationTargetEntity::PATH,
        target_entity_name: <RelationTargetEntity as crate::traits::EntitySchema>::MODEL.name(),
        target_entity_tag: RelationTargetEntity::ENTITY_TAG,
        target_store_path: RelationTargetStore::PATH,
        key_kind: &FieldKind::Ulid,
        strength: RelationStrength::Weak,
    };

crate::test_entity_schema! {
    ident = WeakListRelationSourceEntity,
    id = Ulid,
    id_field = id,
    entity_name = "WeakListRelationSourceEntity",
    entity_tag = crate::testing::WEAK_LIST_RELATION_SOURCE_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        ("targets", FieldKind::List(&REL_WEAK_LIST_TARGET_KIND)),
    ],
    indexes = [],
    store = RelationSourceStore,
    canister = RelationTestCanister,
}

// Clear relation test stores and any pending commit marker between runs.
pub(in crate::db::executor::tests) fn reset_relation_stores() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    ensure_recovered(&REL_DB).expect("relation write-side recovery should succeed");
    REL_DB.with_store_registry(|reg| {
        reg.try_get_store(RelationSourceStore::PATH)
            .map(|store| {
                store.with_data_mut(DataStore::clear);
                store.with_index_mut(IndexStore::clear);
            })
            .expect("relation source store access should succeed");
        reg.try_get_store(RelationTargetStore::PATH)
            .map(|store| {
                store.with_data_mut(DataStore::clear);
                store.with_index_mut(IndexStore::clear);
            })
            .expect("relation target store access should succeed");
    });
}