bevy_persistence_database 0.3.0

A persistence and database integration solution for the Bevy game engine
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
use crate::common::CountingDbConnection;
use crate::common::*;
use bevy::prelude::IntoScheduleConfigs;
use bevy::prelude::*;
use bevy_persistence_database::bevy::components::Guid;
use bevy_persistence_database::bevy::params::query::PersistentQuery;
use bevy_persistence_database::bevy::plugins::persistence_plugin::PersistenceSystemSet;
use bevy_persistence_database::core::session::commit_sync;
use bevy_persistence_database_derive::db_matrix_test;
use std::sync::{
    Arc,
    atomic::{AtomicUsize, Ordering},
};

#[db_matrix_test]
fn test_load_then_pass_through() {
    let (real_db, _container) = setup();

    // Seed DB with one entity having Health+Position.
    let mut app_seed = setup_test_app(real_db.clone(), None);
    app_seed
        .world_mut()
        .spawn((Health { value: 150 }, Position { x: 10.0, y: 20.0 }));
    app_seed.update();
    commit_sync(&mut app_seed, real_db.clone(), TEST_STORE).expect("seed commit failed");

    // Wrap the db with a counting adapter
    let counter = Arc::new(AtomicUsize::new(0));
    let db = Arc::new(CountingDbConnection::new(real_db.clone(), counter.clone()));

    // App under test
    let mut app = setup_test_app(db.clone(), None);

    // 1) Update system: explicitly load once; call twice to validate cache later.
    fn sys_load(mut pq: PersistentQuery<(&Health, &Position), (With<Health>, With<Position>)>) {
        let _ = pq.load().load();
    }
    app.add_systems(Update, sys_load);
    app.update(); // triggers DB load and schedules world ops

    // 2) Next frame: pass-throughs should see data (no DB I/O).
    fn sys_verify(pq: PersistentQuery<(&Health, &Position), (With<Health>, With<Position>)>) {
        // Deref pass-throughs: iter, single, iter_combinations
        let all: Vec<_> = pq.iter().collect();
        assert_eq!(all.len(), 1);
        let (_e, (h, p)) = pq.single().unwrap();
        assert_eq!(h.value, 150);
        assert_eq!(p.x, 10.0);
        assert_eq!(p.y, 20.0);
        let combos = pq.iter_combinations::<1>().count();
        assert_eq!(combos, 1);
    }
    app.add_systems(Update, sys_verify);
    app.update();

    // Exactly one execute_documents call
    assert_eq!(
        counter.load(Ordering::SeqCst),
        1,
        "expected exactly one execute_documents call"
    );
}

#[db_matrix_test]
fn test_cache_prevents_duplicate_loads_in_same_frame() {
    let (real_db, _container) = setup();

    // Seed DB
    let mut app_seed = setup_test_app(real_db.clone(), None);
    app_seed.world_mut().spawn(Health { value: 42 });
    app_seed.update();
    commit_sync(&mut app_seed, real_db.clone(), TEST_STORE).unwrap();

    // Wrap DB to count execute_documents calls
    let counter = Arc::new(AtomicUsize::new(0));
    let db = Arc::new(CountingDbConnection::new(real_db.clone(), counter.clone()));

    // App under test
    let mut app = setup_test_app(db.clone(), None);

    // Single system issuing two identical loads in the same frame
    fn sys_twice(mut pq: PersistentQuery<&Health, With<Health>>) {
        pq.load();
        pq.load(); // should hit cache
    }
    app.add_systems(Update, sys_twice);
    app.update();

    // No additional loads in later frame unless requested
    app.update();

    assert_eq!(
        counter.load(Ordering::SeqCst),
        1,
        "cache should coalesce identical loads"
    );
}

#[db_matrix_test]
fn test_deref_forwards_bevy_query_methods() {
    let (db_real, _container) = setup();

    // Seed one entity
    let mut app_seed = setup_test_app(db_real.clone(), None);
    let e = app_seed
        .world_mut()
        .spawn((Health { value: 5 }, Position { x: 1.0, y: 2.0 }))
        .id();
    app_seed.update();
    commit_sync(&mut app_seed, db_real.clone(), TEST_STORE).unwrap();

    // App under test
    let mut app = setup_test_app(db_real.clone(), None);

    // Frame 1: load
    fn load(mut pq: PersistentQuery<(&Health, &Position)>) {
        let _ = pq.load();
    }
    app.add_systems(Update, load);
    app.update();

    // Frame 2: use Bevy Query methods via Deref
    #[derive(Resource)]
    struct Ent(Entity);
    app.insert_resource(Ent(e));
    fn verify(pq: PersistentQuery<(&Health, &Position)>, ent: Res<Ent>) {
        // contains
        assert!(pq.contains(ent.0));
        // get
        let (_e, (h, p)) = pq.get(ent.0).unwrap();
        assert_eq!(h.value, 5);
        assert_eq!(p.x, 1.0);
        // iter and collect
        let v: Vec<_> = pq.iter().collect();
        assert_eq!(v.len(), 1);
        // combinations
        assert_eq!(pq.iter_combinations::<1>().count(), 1);
        // get_many on same entity twice just to hit the API shape
        let _ = pq.get_many([ent.0]).unwrap();
    }
    app.add_systems(Update, verify);
    app.update();
}

/// Test that verifies immediate pass-through works right after a load in the same system
#[db_matrix_test]
fn test_immediate_pass_through() {
    let (db, _container) = setup();

    // Seed DB with a few entities
    let mut app_seed = setup_test_app(db.clone(), None);
    app_seed.world_mut().spawn(Health { value: 10 });
    app_seed.world_mut().spawn(Health { value: 20 });
    app_seed.update();
    commit_sync(&mut app_seed, db.clone(), TEST_STORE).expect("seed commit failed");

    // App under test
    let mut app = setup_test_app(db.clone(), None);

    // Test resource to store results
    #[derive(Resource, Default)]
    struct TestResults {
        immediate_iter_count: usize,
        immediate_get_success: bool,
        immediate_contains: bool,
        first_entity: Option<Entity>,
    }
    app.insert_resource(TestResults::default());

    // System with load and immediate query in the same function
    fn test_immediate_system(mut pq: PersistentQuery<&Health>, mut results: ResMut<TestResults>) {
        // Load with immediate apply
        pq.load();

        // Test immediate iter
        let entities: Vec<Entity> = pq.iter().map(|(e, _)| e).collect();
        results.immediate_iter_count = entities.len();

        // Try get and contains on the first entity
        if let Some(&first) = entities.first() {
            results.first_entity = Some(first);
            results.immediate_get_success = pq.get(first).is_ok();
            results.immediate_contains = pq.contains(first);
        }
    }

    app.add_systems(
        PostUpdate,
        test_immediate_system.after(PersistenceSystemSet::PreCommit),
    );
    app.update();

    // Verify results
    let result = app.world().resource::<TestResults>();
    assert_eq!(
        result.immediate_iter_count, 2,
        "iter should return all loaded entities immediately"
    );
    assert!(
        result.immediate_get_success,
        "get should work immediately after load"
    );
    assert!(
        result.immediate_contains,
        "contains should work immediately after load"
    );

    // Verify entity is actually in the world
    if let Some(entity) = result.first_entity {
        let health = app.world().get::<Health>(entity);
        assert!(health.is_some(), "Entity should exist in the world");
    } else {
        panic!("Failed to capture entity during immediate apply");
    }
}

/// Test that verifies basic pass-through methods work after a load
#[db_matrix_test]
fn test_query_contains_method() {
    let (db, _container) = setup();

    // GIVEN a committed entity with Health
    let mut app_seed = setup_test_app(db.clone(), None);
    let entity = app_seed.world_mut().spawn(Health { value: 42 }).id();
    // Don't try to access Guid immediately - it gets added during commit
    app_seed.update();
    commit_sync(&mut app_seed, db.clone(), TEST_STORE).expect("seed commit failed");

    // Now we can safely get the Guid (after commit)
    let _guid = app_seed
        .world()
        .get::<Guid>(entity)
        .unwrap()
        .id()
        .to_string();

    // WHEN we load it into a new app
    let mut app = setup_test_app(db.clone(), None);

    // First system loads the entity
    #[derive(Resource, Default)]
    struct LoadedEntity(Option<Entity>);

    app.insert_resource(LoadedEntity::default());

    fn load_health(mut pq: PersistentQuery<&Health>, mut res: ResMut<LoadedEntity>) {
        // Load health entities
        pq.load();

        // Capture the first entity
        if let Some((e, _)) = pq.iter().next() {
            res.0 = Some(e);
        }
    }

    // Second system tests contains()
    #[derive(Resource, Default)]
    struct TestResult(bool);

    app.insert_resource(TestResult::default());

    fn check_contains(
        pq: PersistentQuery<&Health>,
        entity: Res<LoadedEntity>,
        mut result: ResMut<TestResult>,
    ) {
        if let Some(e) = entity.0 {
            result.0 = pq.contains(e);
        }
    }

    // Run the systems in sequence
    app.add_systems(Update, load_health.after(PersistenceSystemSet::PreCommit));
    app.update();

    app.add_systems(Update, check_contains);
    app.update();

    // Verify the result
    let contains_result = app.world().resource::<TestResult>().0;
    assert!(
        contains_result,
        "contains() should return true for a loaded entity"
    );
}

/// Test that verifies get() method works after a load
#[db_matrix_test]
fn test_query_get_method() {
    let (db, _container) = setup();

    // GIVEN a committed entity with Health
    let mut app_seed = setup_test_app(db.clone(), None);
    let _entity = app_seed.world_mut().spawn(Health { value: 42 }).id();
    app_seed.update();
    commit_sync(&mut app_seed, db.clone(), TEST_STORE).expect("seed commit failed");

    // WHEN we load it into a new app
    let mut app = setup_test_app(db.clone(), None);

    // First system loads the entity
    #[derive(Resource, Default)]
    struct LoadedEntity(Option<Entity>);

    app.insert_resource(LoadedEntity::default());

    fn load_health(mut pq: PersistentQuery<&Health>, mut res: ResMut<LoadedEntity>) {
        // Load health entities
        pq.load();

        // Capture the first entity
        if let Some((e, _)) = pq.iter().next() {
            res.0 = Some(e);
        }
    }

    // Second system tests get()
    #[derive(Resource, Default)]
    struct TestResult(bool);

    app.insert_resource(TestResult::default());

    fn check_get(
        pq: PersistentQuery<&Health>,
        entity: Res<LoadedEntity>,
        mut result: ResMut<TestResult>,
    ) {
        if let Some(e) = entity.0 {
            result.0 = pq.get(e).is_ok();
        }
    }

    // Run the systems in sequence
    app.add_systems(Update, load_health.after(PersistenceSystemSet::PreCommit));
    app.update();

    app.add_systems(Update, check_get);
    app.update();

    // Verify the result
    let get_result = app.world().resource::<TestResult>().0;
    assert!(get_result, "get() should succeed for a loaded entity");
}

/// Test that verifies get_mut() method works after a load
#[db_matrix_test]
fn test_query_get_mut_method() {
    let (db, _container) = setup();

    // GIVEN a committed entity with Health
    let mut app_seed = setup_test_app(db.clone(), None);
    let _entity = app_seed.world_mut().spawn(Health { value: 42 }).id();
    app_seed.update();
    commit_sync(&mut app_seed, db.clone(), TEST_STORE).expect("seed commit failed");

    // WHEN we load it into a new app
    let mut app = setup_test_app(db.clone(), None);

    // First system loads the entity
    #[derive(Resource, Default)]
    struct LoadedEntity(Option<Entity>);

    app.insert_resource(LoadedEntity::default());

    fn load_health(mut pq: PersistentQuery<&Health>, mut res: ResMut<LoadedEntity>) {
        // Load health entities
        pq.load();

        // Capture the first entity
        if let Some((e, _)) = pq.iter().next() {
            res.0 = Some(e);
        }
    }

    // Second system tests get_mut()
    #[derive(Resource, Default)]
    struct TestResult(bool);

    app.insert_resource(TestResult::default());

    fn check_get_mut(
        mut pq: PersistentQuery<&mut Health>,
        entity: Res<LoadedEntity>,
        mut result: ResMut<TestResult>,
    ) {
        if let Some(e) = entity.0 {
            result.0 = pq.get_mut(e).is_ok();
        }
    }

    // Run the systems in sequence
    app.add_systems(Update, load_health.after(PersistenceSystemSet::PreCommit));
    app.update();

    app.add_systems(Update, check_get_mut);
    app.update();

    // Verify the result
    let get_mut_result = app.world().resource::<TestResult>().0;
    assert!(
        get_mut_result,
        "get_mut() should succeed for a loaded entity"
    );
}

/// Test that verifies get_many() method works after a load
#[db_matrix_test]
fn test_query_get_many_method() {
    let (db, _container) = setup();

    // GIVEN multiple committed entities with Health
    let mut app_seed = setup_test_app(db.clone(), None);
    app_seed.world_mut().spawn(Health { value: 10 });
    app_seed.world_mut().spawn(Health { value: 20 });
    app_seed.update();
    commit_sync(&mut app_seed, db.clone(), TEST_STORE).expect("seed commit failed");

    // WHEN we load them into a new app
    let mut app = setup_test_app(db.clone(), None);

    // Resource to store entities
    #[derive(Resource, Default)]
    struct LoadedEntities(Vec<Entity>);

    app.insert_resource(LoadedEntities::default());

    fn load_health(mut pq: PersistentQuery<&Health>, mut res: ResMut<LoadedEntities>) {
        // Load health entities
        pq.load();

        // Capture entities
        for (e, _) in pq.iter() {
            res.0.push(e);
        }
    }

    // Second system tests get_many()
    #[derive(Resource, Default)]
    struct TestResult(bool);

    app.insert_resource(TestResult::default());

    fn check_get_many(
        pq: PersistentQuery<&Health>,
        entities: Res<LoadedEntities>,
        mut result: ResMut<TestResult>,
    ) {
        if entities.0.len() < 2 {
            return;
        }

        let get_result = pq.get_many([entities.0[0], entities.0[1]]);
        result.0 = get_result.is_ok();
    }

    // Run the systems in sequence
    app.add_systems(Update, load_health.after(PersistenceSystemSet::PreCommit));
    app.update();

    app.add_systems(Update, check_get_many);
    app.update();

    // Verify the result
    let get_many_result = app.world().resource::<TestResult>().0;
    assert!(
        get_many_result,
        "get_many() should succeed for loaded entities"
    );
}

/// Test that verifies single() method works after a load
#[db_matrix_test]
fn test_query_single_method() {
    let (db, _container) = setup();

    // GIVEN a committed entity with PlayerName (to ensure exactly one entity)
    let mut app_seed = setup_test_app(db.clone(), None);
    app_seed.world_mut().spawn((
        Health { value: 50 },
        PlayerName {
            name: "player".into(),
        },
    ));
    app_seed.update();
    commit_sync(&mut app_seed, db.clone(), TEST_STORE).expect("seed commit failed");

    // WHEN we load it into a new app with a filter for PlayerName
    let mut app = setup_test_app(db.clone(), None);

    // Resource to store result
    #[derive(Resource, Default)]
    struct SingleResult {
        health_value: Option<i32>,
        success: bool,
    }

    app.insert_resource(SingleResult::default());

    fn test_single(
        mut pq: PersistentQuery<&Health, With<PlayerName>>,
        mut result: ResMut<SingleResult>,
    ) {
        // Load and immediately use single
        pq.load();

        match pq.single() {
            Ok((_e, health)) => {
                result.health_value = Some(health.value);
                result.success = true;
            }
            Err(_) => {
                result.success = false;
            }
        }
    }

    app.add_systems(Update, test_single.after(PersistenceSystemSet::PreCommit));
    app.update();

    // THEN the single method should succeed
    let result = app.world().resource::<SingleResult>();
    assert!(
        result.success,
        "single() should succeed for a unique entity"
    );
    assert_eq!(
        result.health_value,
        Some(50),
        "single() should return the correct health value"
    );
}

/// Test that verifies iter_combinations() method works after a load
#[db_matrix_test]
fn test_query_iter_combinations_method() {
    let (db, _container) = setup();

    // GIVEN multiple committed entities with Health
    let mut app_seed = setup_test_app(db.clone(), None);
    app_seed.world_mut().spawn(Health { value: 10 });
    app_seed.world_mut().spawn(Health { value: 20 });
    app_seed.world_mut().spawn(Health { value: 30 });
    app_seed.update();
    commit_sync(&mut app_seed, db.clone(), TEST_STORE).expect("seed commit failed");

    // WHEN we load them into a new app
    let mut app = setup_test_app(db.clone(), None);

    // Resource to store result
    #[derive(Resource, Default)]
    struct CombinationsResult {
        count: usize,
    }

    app.insert_resource(CombinationsResult::default());

    fn test_combinations(mut pq: PersistentQuery<&Health>, mut result: ResMut<CombinationsResult>) {
        // Load and immediately use iter_combinations
        pq.load();

        // Count combinations of 2 entities
        result.count = pq.iter_combinations::<2>().count();
        bevy::log::info!("Found {} combinations of 2 entities", result.count);
    }

    app.add_systems(
        Update,
        test_combinations.after(PersistenceSystemSet::PreCommit),
    );
    app.update();

    // THEN there should be exactly 3 combinations (3 choose 2 = 3)
    let result = app.world().resource::<CombinationsResult>();
    assert_eq!(
        result.count, 3,
        "iter_combinations should return the correct number of combinations"
    );
}