Skip to main content

swls_core/
store.rs

1use bevy_ecs::prelude::*;
2use tracing::debug;
3
4use crate::prelude::*;
5
6/// Shared Oxigraph store holding the triples of every background (not [`Open`])
7/// document.
8///
9/// Each document is loaded into its own named graph, named after its [`Label`],
10/// so a document can be replaced or removed without leaving stale triples
11/// behind. Queries must therefore treat the default graph as the union of all
12/// graphs (see [`union_query`]).
13#[derive(Resource)]
14pub struct Store(pub oxigraph::store::Store);
15
16impl Store {
17    fn graph_name(label: &Label) -> Option<oxigraph::model::GraphName> {
18        oxigraph::model::NamedNode::new(label.as_str())
19            .ok()
20            .map(oxigraph::model::GraphName::NamedNode)
21    }
22
23    /// Replace the triples loaded for `label` with `triples`.
24    pub fn load_document(&self, label: &Label, triples: &Triples) {
25        self.remove_document(label);
26        let Some(graph) = Self::graph_name(label) else {
27            return;
28        };
29        let mut loader = self.0.bulk_loader();
30        let _ = loader.load_quads(
31            triples
32                .0
33                .iter()
34                .flat_map(|x| x.into_oxi(Some(graph.clone()))),
35        );
36        let _ = loader.commit();
37        debug!("Loaded {} triples from {}", triples.len(), label.as_str());
38    }
39
40    /// Drop every triple that was loaded for `label`.
41    pub fn remove_document(&self, label: &Label) {
42        if let Some(graph) = Self::graph_name(label) {
43            let _ = self.0.clear_graph(graph.as_ref());
44        }
45    }
46}
47
48/// Parse `query` so that its default graph is the union of all named graphs in
49/// the [`Store`], i.e. it sees the triples of every loaded document.
50pub fn union_query(query: &str) -> Option<oxigraph::sparql::PreparedSparqlQuery> {
51    let mut prepared = oxigraph::sparql::SparqlEvaluator::new()
52        .parse_query(query)
53        .ok()?;
54    prepared.dataset_mut().set_default_graph_as_union();
55    Some(prepared)
56}
57
58/// (Re)load the triples of every background document whose triples changed.
59///
60/// The document's previous triples are removed first, so a document that is
61/// re-fetched, replaced or edited on disk never accumulates stale data.
62pub fn load_store(
63    query: Query<(&Triples, &Label), (Changed<Triples>, Without<Open>)>,
64    store: Res<Store>,
65    mut revisions: ResMut<Revisions>,
66) {
67    if !query.is_empty() {
68        revisions.store += 1;
69    }
70    for (t, label) in &query {
71        store.load_document(label, t);
72    }
73}