Skip to main content

ggen_core/domain/graph/
query.rs

1//! SPARQL query execution domain logic with real Oxigraph operations
2//!
3//! Chicago TDD: Uses REAL in-memory RDF stores and ACTUAL SPARQL queries
4
5use crate::utils::error::{Context, Result};
6use crate::Graph;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::path::PathBuf;
10
11/// Options for SPARQL query execution
12#[derive(Debug, Clone)]
13pub struct QueryOptions {
14    /// SPARQL query string
15    pub query: String,
16    /// Optional graph file to load and query
17    pub graph_file: Option<String>,
18    /// Output format (json, csv, table)
19    pub output_format: String,
20}
21
22/// Result from SPARQL query execution
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct QueryResult {
25    /// Variable bindings from query results
26    pub bindings: Vec<HashMap<String, String>>,
27    /// Variable names from SELECT query
28    pub variables: Vec<String>,
29    /// Number of results returned
30    pub result_count: usize,
31}
32
33/// Query input options (pure domain type - no CLI dependencies)
34#[derive(Debug, Clone, Default, Serialize, Deserialize)]
35pub struct QueryInput {
36    /// SPARQL query string
37    pub query: String,
38
39    /// RDF graph file to query
40    pub graph_file: Option<PathBuf>,
41
42    /// Output format (json, csv, table)
43    pub format: String,
44}
45
46impl QueryInput {
47    pub fn new(query: String) -> Self {
48        Self {
49            query,
50            format: "table".to_string(),
51            ..Default::default()
52        }
53    }
54}
55
56impl QueryResult {
57    /// Create new empty query result
58    pub fn empty() -> Self {
59        Self {
60            bindings: Vec::new(),
61            variables: Vec::new(),
62            result_count: 0,
63        }
64    }
65
66    /// Create query result from bindings
67    pub fn from_bindings(bindings: Vec<HashMap<String, String>>, variables: Vec<String>) -> Self {
68        let result_count = bindings.len();
69        Self {
70            bindings,
71            variables,
72            result_count,
73        }
74    }
75}
76
77/// Execute SPARQL query against RDF graph
78///
79/// Chicago TDD: This executes REAL SPARQL queries using Oxigraph
80pub fn execute_sparql(options: QueryOptions) -> Result<QueryResult> {
81    // Load graph if file provided, otherwise create empty graph
82    let graph = if let Some(graph_file) = &options.graph_file {
83        Graph::load_from_file(graph_file)
84            .context(format!("Failed to load graph from file: {}", graph_file))?
85    } else {
86        Graph::new().context("Failed to create empty graph")?
87    };
88
89    // Execute REAL SPARQL query using Oxigraph
90    let query_results = graph
91        .query(&options.query)
92        .context("Failed to execute SPARQL query")?;
93
94    // Convert Oxigraph results to our domain model
95    match query_results {
96        oxigraph::sparql::QueryResults::Solutions(solutions) => {
97            let variables: Vec<String> = solutions
98                .variables()
99                .iter()
100                .map(|v| v.to_string())
101                .collect();
102
103            let mut bindings = Vec::new();
104            for solution in solutions {
105                let solution = solution
106                    .map_err(|e| {
107                        crate::utils::error::Error::new(&format!(
108                            "Failed to process SPARQL solution: {}",
109                            e
110                        ))
111                    })
112                    .context("Failed to process SPARQL solution")?;
113                let mut binding = HashMap::new();
114
115                for variable in &variables {
116                    // Oxigraph solution.get() expects variable name without ? prefix
117                    let var_name = variable.strip_prefix('?').unwrap_or(variable);
118                    if let Some(value) = solution.get(var_name) {
119                        binding.insert(variable.clone(), value.to_string());
120                    }
121                }
122                bindings.push(binding);
123            }
124
125            Ok(QueryResult::from_bindings(bindings, variables))
126        }
127        oxigraph::sparql::QueryResults::Boolean(result) => {
128            // For ASK queries, return boolean result as binding
129            let mut binding = HashMap::new();
130            binding.insert("result".to_string(), result.to_string());
131
132            Ok(QueryResult::from_bindings(
133                vec![binding],
134                vec!["result".to_string()],
135            ))
136        }
137        oxigraph::sparql::QueryResults::Graph(_) => {
138            // For CONSTRUCT/DESCRIBE queries, return basic info
139            Ok(QueryResult::from_bindings(
140                vec![],
141                vec!["graph".to_string()],
142            ))
143        }
144    }
145}
146
147/// Execute query with input (pure domain function)
148pub async fn execute_query(input: QueryInput) -> Result<QueryResult> {
149    let options = QueryOptions {
150        query: input.query,
151        graph_file: input
152            .graph_file
153            .as_ref()
154            .map(|p| p.to_string_lossy().to_string()),
155        output_format: input.format,
156    };
157
158    execute_sparql(options)
159        .map_err(|e| crate::utils::error::Error::new(&format!("SPARQL query failed: {}", e)))
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    /// Chicago TDD: Test with REAL in-memory RDF graph
167    #[test]
168    fn test_execute_sparql_with_real_graph() -> Result<()> {
169        // Create REAL RDF graph with Oxigraph
170        let graph = Graph::new()?;
171
172        // Insert REAL RDF triples
173        let turtle = r#"
174            @prefix ex: <http://example.org/> .
175            @prefix foaf: <http://xmlns.com/foaf/0.1/> .
176
177            ex:alice a foaf:Person ;
178                foaf:name "Alice" ;
179                foaf:age "30" .
180
181            ex:bob a foaf:Person ;
182                foaf:name "Bob" ;
183                foaf:age "25" .
184        "#;
185
186        graph.insert_turtle(turtle)?;
187
188        // Create temp file with RDF data
189        let temp_file = tempfile::Builder::new().suffix(".ttl").tempfile()?;
190        std::fs::write(temp_file.path(), turtle.as_bytes())?;
191        let temp_path = temp_file.path().to_string_lossy().to_string();
192
193        // Execute REAL SPARQL query
194        let options = QueryOptions {
195            query: r#"
196                PREFIX foaf: <http://xmlns.com/foaf/0.1/>
197                SELECT ?name ?age
198                WHERE {
199                    ?person foaf:name ?name ;
200                           foaf:age ?age .
201                }
202                ORDER BY ?name
203            "#
204            .to_string(),
205            graph_file: Some(temp_path),
206            output_format: "json".to_string(),
207        };
208
209        let result = execute_sparql(options)?;
210
211        // Verify REAL query results (SPARQL variables include ? prefix)
212        assert_eq!(result.variables, vec!["?name", "?age"]);
213        assert_eq!(result.result_count, 2);
214        assert_eq!(result.bindings.len(), 2);
215
216        // Verify actual data (bindings also use ? prefix)
217        assert!(result.bindings[0].get("?name").unwrap().contains("Alice"));
218        assert!(result.bindings[1].get("?name").unwrap().contains("Bob"));
219
220        Ok(())
221    }
222
223    /// Chicago TDD: Test ASK query with REAL boolean result
224    #[test]
225    fn test_execute_ask_query_with_real_graph() -> Result<()> {
226        let graph = Graph::new()?;
227
228        let turtle = r#"
229            @prefix ex: <http://example.org/> .
230            ex:subject ex:predicate ex:object .
231        "#;
232
233        graph.insert_turtle(turtle)?;
234
235        let temp_file = tempfile::Builder::new().suffix(".ttl").tempfile()?;
236        std::fs::write(temp_file.path(), turtle.as_bytes())?;
237        let temp_path = temp_file.path().to_string_lossy().to_string();
238
239        // Execute REAL ASK query
240        let options = QueryOptions {
241            query: "ASK { ?s ?p ?o }".to_string(),
242            graph_file: Some(temp_path),
243            output_format: "json".to_string(),
244        };
245
246        let result = execute_sparql(options)?;
247
248        // Verify boolean result
249        assert_eq!(result.variables, vec!["result"]);
250        assert!(result.bindings[0].get("result").unwrap().contains("true"));
251
252        Ok(())
253    }
254
255    /// Chicago TDD: Test empty graph returns no results
256    #[test]
257    fn test_execute_sparql_empty_graph() -> Result<()> {
258        // Execute query on empty graph
259        let options = QueryOptions {
260            query: "SELECT ?s ?p ?o WHERE { ?s ?p ?o }".to_string(),
261            graph_file: None,
262            output_format: "json".to_string(),
263        };
264
265        let result = execute_sparql(options)?;
266
267        // Verify no results from empty graph
268        assert_eq!(result.result_count, 0);
269        assert_eq!(result.bindings.len(), 0);
270
271        Ok(())
272    }
273
274    /// Chicago TDD: Test filtering with REAL SPARQL FILTER
275    #[test]
276    fn test_execute_sparql_with_filter() -> Result<()> {
277        let graph = Graph::new()?;
278
279        let turtle = r#"
280            @prefix ex: <http://example.org/> .
281            ex:alice ex:age "30"^^<http://www.w3.org/2001/XMLSchema#integer> .
282            ex:bob ex:age "25"^^<http://www.w3.org/2001/XMLSchema#integer> .
283            ex:charlie ex:age "35"^^<http://www.w3.org/2001/XMLSchema#integer> .
284        "#;
285
286        graph.insert_turtle(turtle)?;
287
288        let temp_file = tempfile::Builder::new().suffix(".ttl").tempfile()?;
289        std::fs::write(temp_file.path(), turtle.as_bytes())?;
290        let temp_path = temp_file.path().to_string_lossy().to_string();
291
292        // Execute REAL SPARQL query with FILTER
293        let options = QueryOptions {
294            query: r#"
295                PREFIX ex: <http://example.org/>
296                PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
297                SELECT ?person ?age
298                WHERE {
299                    ?person ex:age ?age .
300                    FILTER(?age > "28"^^xsd:integer)
301                }
302            "#
303            .to_string(),
304            graph_file: Some(temp_path),
305            output_format: "json".to_string(),
306        };
307
308        let result = execute_sparql(options)?;
309
310        // Verify FILTER works correctly
311        assert_eq!(result.result_count, 2); // alice and charlie
312        assert_eq!(result.bindings.len(), 2);
313
314        Ok(())
315    }
316}