Skip to main content

ggen_core/graph/
query.rs

1//! GraphQuery - Advanced query operations
2//!
3//! Provides advanced SPARQL query building and execution capabilities.
4
5use crate::graph::core::Graph;
6use crate::utils::error::Result;
7use oxigraph::sparql::{QueryResults, SparqlEvaluator};
8use std::collections::BTreeMap;
9
10/// GraphQuery provides advanced query building and execution.
11///
12/// This type provides a fluent interface for building and executing
13/// SPARQL queries with additional convenience methods.
14///
15/// # Examples
16///
17/// ## Query with prefixes
18///
19/// ```rust,no_run
20/// use ggen_core::graph::{Graph, GraphQuery};
21/// use std::collections::BTreeMap;
22///
23/// # fn main() -> ggen_core::utils::error::Result<()> {
24/// let graph = Graph::new()?;
25/// let query = GraphQuery::new(&graph);
26///
27/// let mut prefixes = BTreeMap::new();
28/// prefixes.insert("ex".to_string(), "http://example.org/".to_string());
29///
30/// let results = query.execute_with_prefixes(
31///     "SELECT ?name WHERE { ?s ex:name ?name }",
32///     &prefixes,
33///     None
34/// )?;
35/// # Ok(())
36/// # }
37/// ```
38pub struct GraphQuery<'a> {
39    graph: &'a Graph,
40}
41
42impl<'a> GraphQuery<'a> {
43    /// Create a new GraphQuery instance for the given graph.
44    pub fn new(graph: &'a Graph) -> Self {
45        Self { graph }
46    }
47
48    /// Execute a SPARQL query with PREFIX and BASE declarations.
49    ///
50    /// # Arguments
51    ///
52    /// * `sparql` - SPARQL query string (without PREFIX/BASE)
53    /// * `prefixes` - Map of prefix names to namespace URIs
54    /// * `base` - Optional base IRI
55    pub fn execute_with_prefixes(
56        &self, sparql: &str, prefixes: &BTreeMap<String, String>, base: Option<&str>,
57    ) -> Result<QueryResults<'a>> {
58        self.graph.query_with_prolog(sparql, prefixes, base)
59    }
60
61    /// Execute a SPARQL query and return cached results.
62    ///
63    /// This is a convenience method that calls `graph.query_cached()`.
64    pub fn execute_cached(&self, sparql: &str) -> Result<crate::graph::types::CachedResult> {
65        self.graph.query_cached(sparql)
66    }
67
68    /// Execute a SPARQL query and return raw QueryResults.
69    ///
70    /// This is a convenience method that calls `graph.query()`.
71    pub fn execute(&self, sparql: &str) -> Result<QueryResults<'a>> {
72        self.graph.query(sparql)
73    }
74
75    /// Execute a prepared SPARQL query.
76    ///
77    /// This is a convenience method that calls `graph.query_prepared()`.
78    pub fn execute_prepared(&self, q: &str) -> Result<QueryResults<'a>> {
79        self.graph.query_prepared(q)
80    }
81
82    /// Create a query builder for constructing queries programmatically.
83    ///
84    /// Returns a `SparqlEvaluator` that can be used to build and execute queries.
85    /// The evaluator provides a fluent API for constructing SPARQL queries.
86    ///
87    /// # Example
88    ///
89    /// ```rust,no_run
90    /// use ggen_core::graph::{Graph, GraphQuery};
91    ///
92    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
93    /// let graph = Graph::new()?;
94    /// let query = GraphQuery::new(&graph);
95    ///
96    /// // Use the builder to construct and execute a query
97    /// let results = query.builder()
98    ///     .parse_query("SELECT ?s WHERE { ?s ?p ?o }")?
99    ///     .on_store(graph.inner())
100    ///     .execute()?;
101    /// # Ok(())
102    /// # }
103    /// ```
104    pub fn builder(&self) -> SparqlEvaluator {
105        SparqlEvaluator::new()
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use crate::graph::core::Graph;
113    use std::collections::BTreeMap;
114
115    #[test]
116    fn test_query_execute_cached() {
117        // Arrange
118        let graph = Graph::new().unwrap();
119        graph
120            .insert_turtle(
121                r#"
122            @prefix ex: <http://example.org/> .
123            ex:alice ex:name "Alice" .
124        "#,
125            )
126            .unwrap();
127        let query = GraphQuery::new(&graph);
128
129        // Act - Use full IRI since we're not declaring prefixes in the query
130        let result = query
131            .execute_cached("SELECT ?name WHERE { ?s <http://example.org/name> ?name }")
132            .unwrap();
133
134        // Assert
135        match result {
136            crate::graph::types::CachedResult::Solutions(rows) => {
137                assert!(!rows.is_empty());
138                assert!(rows[0].contains_key("name"));
139            }
140            _ => panic!("Expected solutions"),
141        }
142    }
143
144    #[test]
145    fn test_query_execute() {
146        // Arrange
147        let graph = Graph::new().unwrap();
148        graph
149            .insert_turtle(
150                r#"
151            @prefix ex: <http://example.org/> .
152            ex:alice ex:name "Alice" .
153        "#,
154            )
155            .unwrap();
156        let query = GraphQuery::new(&graph);
157
158        // Act - Use full IRI since we're not declaring prefixes in the query
159        let results = query
160            .execute("SELECT ?name WHERE { ?s <http://example.org/name> ?name }")
161            .unwrap();
162
163        // Assert
164        match results {
165            QueryResults::Solutions(_) => {}
166            _ => panic!("Expected solutions"),
167        }
168    }
169
170    #[test]
171    fn test_query_execute_with_prefixes() {
172        // Arrange
173        let graph = Graph::new().unwrap();
174        graph
175            .insert_turtle(
176                r#"
177            @prefix ex: <http://example.org/> .
178            ex:alice ex:name "Alice" .
179        "#,
180            )
181            .unwrap();
182        let query = GraphQuery::new(&graph);
183        let mut prefixes = BTreeMap::new();
184        prefixes.insert("ex".to_string(), "http://example.org/".to_string());
185
186        // Act
187        let results = query
188            .execute_with_prefixes("SELECT ?name WHERE { ?s ex:name ?name }", &prefixes, None)
189            .unwrap();
190
191        // Assert
192        match results {
193            QueryResults::Solutions(_) => {}
194            _ => panic!("Expected solutions"),
195        }
196    }
197
198    #[test]
199    fn test_query_execute_with_base() {
200        // Arrange
201        let graph = Graph::new().unwrap();
202        graph
203            .insert_turtle(
204                r#"
205            @prefix ex: <http://example.org/> .
206            ex:alice ex:name "Alice" .
207        "#,
208            )
209            .unwrap();
210        let query = GraphQuery::new(&graph);
211        let prefixes = BTreeMap::new();
212
213        // Act - Use full IRI since prefix map is empty
214        let results = query
215            .execute_with_prefixes(
216                "SELECT ?name WHERE { ?s <http://example.org/name> ?name }",
217                &prefixes,
218                Some("http://example.org/"),
219            )
220            .unwrap();
221
222        // Assert
223        match results {
224            QueryResults::Solutions(_) => {}
225            _ => panic!("Expected solutions"),
226        }
227    }
228
229    #[test]
230    fn test_query_execute_prepared() {
231        // Arrange
232        let graph = Graph::new().unwrap();
233        graph
234            .insert_turtle(
235                r#"
236            @prefix ex: <http://example.org/> .
237            ex:alice ex:name "Alice" .
238        "#,
239            )
240            .unwrap();
241        let query = GraphQuery::new(&graph);
242
243        // Act - Use full IRI since we're not declaring prefixes in the query
244        let results = query
245            .execute_prepared("SELECT ?name WHERE { ?s <http://example.org/name> ?name }")
246            .unwrap();
247
248        // Assert
249        match results {
250            QueryResults::Solutions(_) => {}
251            _ => panic!("Expected solutions"),
252        }
253    }
254
255    #[test]
256    fn test_query_builder() {
257        // Arrange
258        let graph = Graph::new().unwrap();
259        graph
260            .insert_turtle(
261                r#"
262            @prefix ex: <http://example.org/> .
263            ex:alice ex:name "Alice" .
264        "#,
265            )
266            .unwrap();
267        let query = GraphQuery::new(&graph);
268
269        // Act - Use full IRI since we're not declaring prefixes in the query
270        let builder = query.builder();
271        let results = builder
272            .parse_query("SELECT ?name WHERE { ?s <http://example.org/name> ?name }")
273            .unwrap()
274            .on_store(graph.inner())
275            .execute()
276            .unwrap();
277
278        // Assert
279        match results {
280            QueryResults::Solutions(_) => {}
281            _ => panic!("Expected solutions"),
282        }
283    }
284
285    #[test]
286    fn test_query_ask_query() {
287        // Arrange
288        let graph = Graph::new().unwrap();
289        graph
290            .insert_turtle(
291                r#"
292            @prefix ex: <http://example.org/> .
293            ex:alice a ex:Person .
294        "#,
295            )
296            .unwrap();
297        let query = GraphQuery::new(&graph);
298
299        // Act - Use full IRI since we're not declaring prefixes in the query
300        let result = query
301            .execute_cached("ASK { ?s a <http://example.org/Person> }")
302            .unwrap();
303
304        // Assert
305        match result {
306            crate::graph::types::CachedResult::Boolean(true) => {}
307            _ => panic!("Expected true"),
308        }
309    }
310
311    #[test]
312    fn test_query_invalid_syntax() {
313        // Arrange
314        let graph = Graph::new().unwrap();
315        let query = GraphQuery::new(&graph);
316
317        // Act & Assert
318        let result = query.execute_cached("INVALID SPARQL SYNTAX");
319        assert!(result.is_err());
320    }
321}