ggen_core/domain/graph/
query.rs1use crate::utils::error::{Context, Result};
6use crate::Graph;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::path::PathBuf;
10
11#[derive(Debug, Clone)]
13pub struct QueryOptions {
14 pub query: String,
16 pub graph_file: Option<String>,
18 pub output_format: String,
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct QueryResult {
25 pub bindings: Vec<HashMap<String, String>>,
27 pub variables: Vec<String>,
29 pub result_count: usize,
31}
32
33#[derive(Debug, Clone, Default, Serialize, Deserialize)]
35pub struct QueryInput {
36 pub query: String,
38
39 pub graph_file: Option<PathBuf>,
41
42 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 pub fn empty() -> Self {
59 Self {
60 bindings: Vec::new(),
61 variables: Vec::new(),
62 result_count: 0,
63 }
64 }
65
66 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
77pub fn execute_sparql(options: QueryOptions) -> Result<QueryResult> {
81 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 let query_results = graph
91 .query(&options.query)
92 .context("Failed to execute SPARQL query")?;
93
94 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 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 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 Ok(QueryResult::from_bindings(
140 vec![],
141 vec!["graph".to_string()],
142 ))
143 }
144 }
145}
146
147pub 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 #[test]
168 fn test_execute_sparql_with_real_graph() -> Result<()> {
169 let graph = Graph::new()?;
171
172 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 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 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 assert_eq!(result.variables, vec!["?name", "?age"]);
213 assert_eq!(result.result_count, 2);
214 assert_eq!(result.bindings.len(), 2);
215
216 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 #[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 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 assert_eq!(result.variables, vec!["result"]);
250 assert!(result.bindings[0].get("result").unwrap().contains("true"));
251
252 Ok(())
253 }
254
255 #[test]
257 fn test_execute_sparql_empty_graph() -> Result<()> {
258 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 assert_eq!(result.result_count, 0);
269 assert_eq!(result.bindings.len(), 0);
270
271 Ok(())
272 }
273
274 #[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 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 assert_eq!(result.result_count, 2); assert_eq!(result.bindings.len(), 2);
313
314 Ok(())
315 }
316}