bevy_persistence_database 0.2.10

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
//! Implements a Bevy SystemParam for querying entities from both world and database
//! in a seamless, integrated way.

use bevy::ecs::query::{QueryData, QueryFilter, QueryState};
use bevy::ecs::system::SystemParam;
use bevy::prelude::{Entity, Query, Res, World};

use crate::bevy::plugins::persistence_plugin::{PersistencePluginConfig, TokioRuntime};
use crate::bevy::world_access::{DeferredWorldOperations, ImmediateWorldPtr};
use crate::core::db::connection::DatabaseConnectionResource;
use crate::core::query::FilterExpression;

use super::cache::{CachePolicy, PersistenceQueryCache};
use super::presence_spec::{ToPresenceSpec, collect_presence_components};
use super::query_data_to_components::QueryDataToComponents;
use super::query_thread_local::{
    drain_additional_components, drain_without_components, set_cache_policy, set_filter,
    set_pagination_size, set_store, take_cache_policy, take_filter, take_store,
};

/// System parameter for querying entities from both the world and database
#[derive(SystemParam)]
pub struct PersistentQueryParam<'w, 's, Q: QueryData + 'static, F: QueryFilter + 'static = ()> {
    /// The underlying world query
    pub(crate) query: Query<'w, 's, (Entity, Q), F>,
    /// The database connection
    pub(crate) db: Res<'w, DatabaseConnectionResource>,
    /// The query cache - using immutable access with interior mutability
    pub(crate) cache: Res<'w, PersistenceQueryCache>,
    /// Runtime to drive async DB calls
    pub(crate) runtime: Res<'w, TokioRuntime>,
    /// Add access to the deferred ops queue (immutable; interior mutability)
    pub(crate) ops: Res<'w, DeferredWorldOperations>,
    /// Optional: immediate world access for in-system materialization
    pub(crate) world_ptr: Option<Res<'w, ImmediateWorldPtr>>,
    /// Plugin configuration for defaults such as store
    pub(crate) config: Res<'w, PersistencePluginConfig>,
}

/// Convenient alias mirroring Bevy's `Query<'w, 's, ...>` shape so lifetime
/// elision works at call sites (e.g. `PersistentQuery<&Health>`).
pub type PersistentQuery<'w, 's, Q, F = ()> = PersistentQueryParam<'w, 's, Q, F>;

impl<'w, 's, Q, F> PersistentQuery<'w, 's, Q, F>
where
    Q: QueryData + QueryDataToComponents,
    F: QueryFilter + ToPresenceSpec,
{
    #[inline]
    fn immediate_world_ptr(&self) -> Option<*mut World> {
        self.world_ptr.as_ref().map(|p| p.ptr)
    }

    /// Explicit load trigger that performs DB I/O (if needed) and returns self for pass-through use.
    /// This does not directly mutate the world; world mutations are applied by the plugin in PostUpdate.
    pub fn ensure_loaded(&mut self) -> &mut Self {
        bevy::log::debug!("PersistentQuery::ensure_loaded called");

        // Drain transient config from TLS for this call
        let mut fetch_names: Vec<&'static str> = Vec::new();
        let mut presence_names: Vec<&'static str> = drain_additional_components();
        let mut without_names: Vec<&'static str> = drain_without_components();
        let tls_filter_expression: Option<FilterExpression> = take_filter();
        let cache_policy: CachePolicy = take_cache_policy();
        let store = take_store().unwrap_or_else(|| self.config.default_store.clone());

        // 1) Type-driven component extraction from Q (fetch targets, not presence gates)
        Q::push_names(&mut fetch_names);

        // 2) Merge type-driven presence from F (presence gates + ORs)
        let type_presence = <F as ToPresenceSpec>::to_presence_spec();
        presence_names.extend(type_presence.withs().iter().copied());
        without_names.extend(type_presence.withouts().iter().copied());

        // Collect components referenced by presence expr branches so we fetch them too
        if let Some(expr) = type_presence.expr() {
            collect_presence_components(expr, &mut fetch_names);
        }

        // Ensure fetch includes presence-gated components
        for &n in &presence_names {
            if !fetch_names.contains(&n) {
                fetch_names.push(n);
            }
        }

        // Dedup
        Self::sort_dedup(&mut fetch_names);
        Self::sort_dedup(&mut presence_names);
        Self::sort_dedup(&mut without_names);

        // 3) Combine presence-derived expression (from Or cases) with TLS filter via AND
        let combined_expr: Option<FilterExpression> =
            match (type_presence.expr().cloned(), tls_filter_expression) {
                (Some(a), Some(b)) => Some(a.and(b)),
                (Some(a), None) => Some(a),
                (None, Some(b)) => Some(b),
                (None, None) => None,
            };

        // Reuse the shared executor
        self.execute_combined_load(
            cache_policy,
            presence_names,
            without_names,
            fetch_names,
            combined_expr,
            &[],   // no extra salt
            false, // don't force full docs for plain ensure_loaded
            store,
        );

        self
    }

    /// Add a value filter pushed down to the backend.
    /// Alias for `where(...)` to avoid raw-identifier call sites.
    pub fn filter(self, expr: FilterExpression) -> Self {
        self.r#where(expr)
    }

    /// Add a value filter pushed down to the backend.
    pub fn r#where(self, expr: FilterExpression) -> Self {
        set_filter(expr);
        self
    }

    /// Force a refresh from the database, bypassing the cache.
    pub fn force_refresh(self) -> Self {
        set_cache_policy(CachePolicy::ForceRefresh);
        self
    }

    /// Select the store to query against for the next load.
    pub fn store(self, store: impl Into<String>) -> Self {
        set_store(store);
        self
    }

    /// Small helper: sort + dedup in-place.
    #[inline]
    fn sort_dedup<T: Ord>(v: &mut Vec<T>) {
        v.sort_unstable();
        v.dedup();
    }

    /// Returns an iterator over all matching entities with up-to-date world state,
    /// including entities loaded in the current frame.
    /// This overrides the `iter()` method from `Deref<Target=Query>`.
    pub fn iter(
        &self,
    ) -> Box<
        dyn Iterator<Item = <<(Entity, Q) as QueryData>::ReadOnly as QueryData>::Item<'_, '_>> + '_,
    > {
        bevy::log::trace!("PersistentQuery::iter called");
        if let Some(ptr) = self.immediate_world_ptr() {
            // Safety: pointer is published from an exclusive system each frame.
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            let items: Vec<_> = state.iter(world).collect();
            let items: Vec<_> = unsafe { std::mem::transmute(items) };
            return Box::new(items.into_iter());
        }
        Box::new(self.query.iter())
    }

    /// Returns a mutable iterator over all matching entities with up-to-date world state.
    /// This overrides the `iter_mut()` method from `Deref<Target=Query>`.
    pub fn iter_mut(
        &mut self,
    ) -> Box<dyn Iterator<Item = <(Entity, Q) as QueryData>::Item<'_, 's>> + '_> {
        bevy::log::trace!("PersistentQuery::iter_mut called");
        if let Some(ptr) = self.immediate_world_ptr() {
            // Safety: pointer is published from an exclusive system each frame.
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            let items: Vec<_> = state.iter_mut(world).collect();
            let items: Vec<_> = unsafe { std::mem::transmute(items) };
            return Box::new(items.into_iter());
        }
        Box::new(self.query.iter_mut())
    }

    /// Gets data for a specific entity with up-to-date world state.
    /// This overrides the `get()` method from `Deref<Target=Query>`.
    #[inline]
    pub fn get(
        &self,
        entity: Entity,
    ) -> Result<
        <<(Entity, Q) as QueryData>::ReadOnly as QueryData>::Item<'_, '_>,
        bevy::ecs::query::QueryEntityError,
    > {
        bevy::log::trace!("PersistentQuery::get called for entity {:?}", entity);
        if let Some(ptr) = self.immediate_world_ptr() {
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            let res = state.get(world, entity);
            return unsafe { std::mem::transmute(res) };
        }
        self.query.get(entity)
    }

    /// Gets mutable data for a specific entity with up-to-date world state.
    /// This overrides the `get_mut()` method from `Deref<Target=Query>`.
    #[inline]
    pub fn get_mut(
        &mut self,
        entity: Entity,
    ) -> Result<<(Entity, Q) as QueryData>::Item<'_, 's>, bevy::ecs::query::QueryEntityError> {
        bevy::log::trace!("PersistentQuery::get_mut called for entity {:?}", entity);
        if let Some(ptr) = self.immediate_world_ptr() {
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            let res = state.get_mut(world, entity);
            return unsafe { std::mem::transmute(res) };
        }
        self.query.get_mut(entity)
    }

    /// Returns a single entity result with up-to-date world state.
    /// This overrides the `single()` method from `Deref<Target=Query>`.
    #[inline]
    pub fn single(
        &self,
    ) -> Result<
        <<(Entity, Q) as QueryData>::ReadOnly as QueryData>::Item<'_, '_>,
        bevy::ecs::query::QuerySingleError,
    > {
        bevy::log::trace!("PersistentQuery::single called");
        if let Some(ptr) = self.immediate_world_ptr() {
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            let res = state.single(world);
            return unsafe { std::mem::transmute(res) };
        }
        self.query.single()
    }

    /// Returns a single mutable entity result with up-to-date world state.
    /// This overrides the `single_mut()` method from `Deref<Target=Query>`.
    #[inline]
    pub fn single_mut(
        &mut self,
    ) -> Result<<(Entity, Q) as QueryData>::Item<'_, 's>, bevy::ecs::query::QuerySingleError> {
        bevy::log::trace!("PersistentQuery::single_mut called");
        if let Some(ptr) = self.immediate_world_ptr() {
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            let res = state.single_mut(world);
            return unsafe { std::mem::transmute(res) };
        }
        self.query.single_mut()
    }

    /// Gets data for multiple entities with up-to-date world state.
    /// This overrides the `get_many()` method from `Deref<Target=Query>`.
    pub fn get_many<const N: usize>(
        &self,
        entities: [Entity; N],
    ) -> Result<
        [<<(Entity, Q) as QueryData>::ReadOnly as QueryData>::Item<'_, '_>; N],
        bevy::ecs::query::QueryEntityError,
    > {
        bevy::log::trace!("PersistentQuery::get_many called with {} entities", N);
        if let Some(ptr) = self.immediate_world_ptr() {
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            let res = state.get_many(world, entities);
            return unsafe { std::mem::transmute(res) };
        }
        self.query.get_many(entities)
    }

    /// Gets mutable data for multiple entities with up-to-date world state.
    /// This overrides the `get_many_mut()` method from `Deref<Target=Query>`.
    pub fn get_many_mut<const N: usize>(
        &mut self,
        entities: [Entity; N],
    ) -> Result<[<(Entity, Q) as QueryData>::Item<'_, 's>; N], bevy::ecs::query::QueryEntityError>
    {
        bevy::log::trace!("PersistentQuery::get_many_mut called with {} entities", N);
        if let Some(ptr) = self.immediate_world_ptr() {
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            let res = state.get_many_mut(world, entities);
            return unsafe { std::mem::transmute(res) };
        }
        self.query.get_many_mut(entities)
    }

    /// Iterates over a specific set of entities that match the query.
    /// This overrides the `iter_many()` method from `Deref<Target=Query>`.
    pub fn iter_many<EntityList: IntoIterator<Item = Entity>>(
        &self,
        entities: EntityList,
    ) -> Box<
        dyn Iterator<Item = <<(Entity, Q) as QueryData>::ReadOnly as QueryData>::Item<'_, '_>> + '_,
    > {
        bevy::log::trace!("PersistentQuery::iter_many called");
        let entity_vec: Vec<Entity> = entities.into_iter().collect();
        if let Some(ptr) = self.immediate_world_ptr() {
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            let items: Vec<_> = state.iter_many(world, entity_vec).collect();
            let items: Vec<_> = unsafe { std::mem::transmute(items) };
            return Box::new(items.into_iter());
        }
        Box::new(self.query.iter_many(entity_vec))
    }

    /// Iterates with mutable access over a specific set of entities that match the query.
    /// This overrides the `iter_many_mut()` method from `Deref<Target=Query>`.
    pub fn iter_many_mut<EntityList: IntoIterator<Item = Entity>>(
        &mut self,
        entities: EntityList,
    ) -> Box<dyn Iterator<Item = <(Entity, Q) as QueryData>::Item<'_, 's>> + '_>
    where
        Q: bevy::ecs::query::ReadOnlyQueryData,
    {
        bevy::log::trace!("PersistentQuery::iter_many_mut called");
        let entity_vec: Vec<Entity> = entities.into_iter().collect();
        if let Some(ptr) = self.immediate_world_ptr() {
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            let items: Vec<_> = state.iter_many_mut(world, entity_vec).collect();
            let items: Vec<_> = unsafe { std::mem::transmute(items) };
            return Box::new(items.into_iter());
        }
        Box::new(self.query.iter_many_mut(entity_vec))
    }

    /// Returns an iterator over all combinations of N entities with up-to-date world state.
    /// This overrides the `iter_combinations()` method from `Deref<Target=Query>`.
    pub fn iter_combinations<const N: usize>(
        &self,
    ) -> Box<
        dyn Iterator<Item = [<<(Entity, Q) as QueryData>::ReadOnly as QueryData>::Item<'_, '_>; N]>
            + '_,
    > {
        bevy::log::trace!("PersistentQuery::iter_combinations called");
        if let Some(ptr) = self.immediate_world_ptr() {
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            let items: Vec<_> = state.iter_combinations::<N>(world).collect();
            let items: Vec<_> = unsafe { std::mem::transmute(items) };
            return Box::new(items.into_iter());
        }
        Box::new(self.query.iter_combinations::<N>())
    }

    /// Returns an iterator over all combinations of N entities with mutable access and up-to-date world state.
    /// This overrides the `iter_combinations_mut()` method from `Deref<Target=Query>`.
    pub fn iter_combinations_mut<const N: usize>(
        &mut self,
    ) -> Box<dyn Iterator<Item = [<(Entity, Q) as QueryData>::Item<'_, 's>; N]> + '_>
    where
        Q: bevy::ecs::query::ReadOnlyQueryData,
    {
        bevy::log::trace!("PersistentQuery::iter_combinations_mut called");
        if let Some(ptr) = self.immediate_world_ptr() {
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            let items: Vec<_> = state.iter_combinations_mut::<N>(world).collect();
            let items: Vec<_> = unsafe { std::mem::transmute(items) };
            return Box::new(items.into_iter());
        }
        Box::new(self.query.iter_combinations_mut::<N>())
    }

    /// Checks if the given entity matches the query.
    /// This overrides the `contains()` method from `Deref<Target=Query>`.
    #[inline]
    pub fn contains(&self, entity: Entity) -> bool {
        bevy::log::trace!("PersistentQuery::contains called for entity {:?}", entity);
        if let Some(ptr) = self.immediate_world_ptr() {
            let world: &mut World = unsafe { &mut *ptr };
            let mut state: QueryState<(Entity, Q), F> = QueryState::new(world);
            return state.iter(world).any(|(e, _)| e == entity);
        }
        self.query.contains(entity)
    }

    /// Execute a load with pagination to reduce memory pressure for large datasets
    pub fn paginated_load(&mut self, page_size: usize) -> &mut Self {
        // Configure TLS for chunked loading
        set_pagination_size(page_size);
        self.ensure_loaded()
    }
}

// World-only pass-through: Deref to the inner Query for compatibility.
// Note: Methods directly on PersistentQuery (iter, get, etc.) override these
// and provide up-to-date views of the world.
impl<'w, 's, Q: QueryData + 'static, F: QueryFilter + 'static> std::ops::Deref
    for PersistentQueryParam<'w, 's, Q, F>
{
    type Target = Query<'w, 's, (Entity, Q), F>;
    fn deref(&self) -> &Self::Target {
        &self.query
    }
}

impl<'w, 's, Q: QueryData + 'static, F: QueryFilter + 'static> std::ops::DerefMut
    for PersistentQueryParam<'w, 's, Q, F>
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.query
    }
}