query_flow/db.rs
1//! Database trait for query execution.
2
3use std::sync::Arc;
4
5use crate::asset::AssetKey;
6use crate::loading::AssetLoadingState;
7use crate::query::Query;
8use crate::QueryError;
9
10/// Database trait that provides query execution and asset access.
11///
12/// This trait is implemented by both [`QueryRuntime`](crate::QueryRuntime) and
13/// [`QueryContext`](crate::QueryContext), allowing queries to work with either.
14///
15/// - `QueryRuntime::query()` / `QueryRuntime::asset()`: No dependency tracking
16/// - `QueryContext::query()` / `QueryContext::asset()`: With dependency tracking
17pub trait Db {
18 /// Execute a query, returning the cached result if available.
19 fn query<Q: Query>(&self, query: Q) -> Result<Arc<Q::Output>, QueryError>;
20
21 /// Access an asset by key.
22 ///
23 /// Returns the asset value if ready, or `Err(QueryError::Suspend)` if still loading.
24 /// Use this with the `?` operator for automatic suspension on loading.
25 ///
26 /// # Example
27 ///
28 /// ```ignore
29 /// fn query(&self, db: &impl Db) -> Result<MyOutput, QueryError> {
30 /// let data = db.asset(key)?; // Suspends if loading
31 /// Ok(process(&data))
32 /// }
33 /// ```
34 fn asset<K: AssetKey>(&self, key: K) -> Result<Arc<K::Asset>, QueryError>;
35
36 /// Access an asset's loading state by key.
37 ///
38 /// Unlike [`asset()`](Self::asset), this method returns the full loading state,
39 /// allowing you to check if an asset is loading without triggering suspension.
40 ///
41 /// # Example
42 ///
43 /// ```ignore
44 /// let state = db.asset_state(key)?;
45 /// if state.is_loading() {
46 /// // Handle loading case explicitly
47 /// } else {
48 /// let value = state.get().unwrap();
49 /// }
50 /// ```
51 fn asset_state<K: AssetKey>(&self, key: K) -> Result<AssetLoadingState<K>, QueryError>;
52
53 /// List all executed queries of a specific type.
54 fn list_queries<Q: Query>(&self) -> Vec<Q>;
55
56 /// List all resolved asset keys of a specific type.
57 fn list_asset_keys<K: AssetKey>(&self) -> Vec<K>;
58}