Skip to main content

ggen_core/graph/
construct.rs

1//! CONSTRUCT query executor
2//!
3//! Provides specialized operations for SPARQL CONSTRUCT queries,
4//! including execution and materialization (inserting results back into the graph).
5
6use crate::graph::Graph;
7use crate::utils::error::{Error, Result};
8use oxigraph::sparql::QueryResults;
9use sha2::{Digest, Sha256};
10
11/// Executor for SPARQL CONSTRUCT queries
12pub struct ConstructExecutor<'a> {
13    /// Reference to the graph
14    graph: &'a Graph,
15}
16
17impl<'a> ConstructExecutor<'a> {
18    /// Create a new CONSTRUCT executor for the given graph
19    ///
20    /// # Arguments
21    /// * `graph` - Reference to the RDF graph
22    pub fn new(graph: &'a Graph) -> Self {
23        Self { graph }
24    }
25
26    /// Execute a CONSTRUCT query and return the resulting triples as strings
27    ///
28    /// # Arguments
29    /// * `query` - SPARQL CONSTRUCT query string
30    ///
31    /// # Returns
32    /// * `Ok(Vec<String>)` - Resulting triples in N-Triples format
33    /// * `Err(Error)` - Query execution error
34    ///
35    /// # Example
36    /// ```rust,no_run
37    /// use crate::graph::{Graph, ConstructExecutor};
38    ///
39    /// let graph = Graph::new()?;
40    /// graph.insert_turtle(r#"
41    ///     @prefix ex: <http://example.org/> .
42    ///     ex:alice ex:knows ex:bob .
43    /// "#)?;
44    ///
45    /// let executor = ConstructExecutor::new(&graph);
46    /// let triples = executor.execute(r#"
47    ///     CONSTRUCT { ?s ?p ?o }
48    ///     WHERE { ?s ?p ?o }
49    /// "#)?;
50    /// # Ok::<(), crate::utils::error::Error>(())
51    /// ```
52    pub fn execute(&self, query: &str) -> Result<Vec<String>> {
53        // Execute query using the graph's query method
54        let results = self
55            .graph
56            .query(query)
57            .map_err(|e| Error::new(&format!("CONSTRUCT query failed: {}", e)))?;
58
59        // Handle CONSTRUCT results (Graph variant)
60        match results {
61            QueryResults::Graph(quads) => {
62                let mut triples = Vec::new();
63                for quad_result in quads {
64                    let quad = quad_result
65                        .map_err(|e| Error::new(&format!("Error reading quad: {}", e)))?;
66                    triples.push(quad.to_string());
67                }
68                Ok(triples)
69            }
70            QueryResults::Solutions(_) => Err(Error::new(
71                "Expected CONSTRUCT query but got SELECT results",
72            )),
73            QueryResults::Boolean(_) => {
74                Err(Error::new("Expected CONSTRUCT query but got ASK results"))
75            }
76        }
77    }
78
79    /// Execute a CONSTRUCT query and insert the results back into the graph
80    ///
81    /// This implements the "sequential materialization" pattern where each
82    /// CONSTRUCT rule's output is materialized before the next rule executes.
83    ///
84    /// # Arguments
85    /// * `query` - SPARQL CONSTRUCT query string
86    ///
87    /// # Returns
88    /// * `Ok(usize)` - Number of triples added
89    /// * `Err(Error)` - Query or insert error
90    pub fn execute_and_materialize(&self, query: &str) -> Result<usize> {
91        // First execute the CONSTRUCT
92        let triples = self.execute(query)?;
93        let count = triples.len();
94
95        // Convert triples to N-Triples format and insert via Turtle
96        // Note: Quad::to_string() produces N-Quads format WITHOUT trailing dot
97        // (e.g. "<s> <p> <o>"). We must append " ." to each line so the Turtle
98        // parser (which is a superset of N-Triples) can accept them.
99        if !triples.is_empty() {
100            let ntriples: String = triples
101                .iter()
102                .map(|t| format!("{} .", t))
103                .collect::<Vec<_>>()
104                .join("\n");
105            self.graph.insert_turtle(&ntriples)?;
106        }
107
108        Ok(count)
109    }
110
111    /// Execute a chain of CONSTRUCT queries in order, materializing after each
112    ///
113    /// # Arguments
114    /// * `queries` - Ordered list of (name, query) pairs
115    ///
116    /// # Returns
117    /// * `Ok(Vec<(String, usize)>)` - List of (rule_name, triples_added)
118    /// * `Err(Error)` - First error encountered
119    pub fn execute_chain(&self, queries: &[(&str, &str)]) -> Result<Vec<(String, usize)>> {
120        let mut results = Vec::new();
121
122        for (name, query) in queries {
123            let count = self.execute_and_materialize(query)?;
124            results.push((name.to_string(), count));
125        }
126
127        Ok(results)
128    }
129
130    /// Generate a deterministic IRI from a base and optional salt
131    ///
132    /// This ensures reproducible IRI generation across runs.
133    ///
134    /// # Arguments
135    /// * `base` - Base IRI prefix
136    /// * `components` - Components to include in hash
137    /// * `salt` - Optional salt for additional uniqueness
138    ///
139    /// # Returns
140    /// A deterministic IRI string
141    pub fn generate_iri(base: &str, components: &[&str], salt: Option<&str>) -> String {
142        let mut hasher = Sha256::new();
143
144        // Include base in hash
145        hasher.update(base.as_bytes());
146
147        // Include all components
148        for component in components {
149            hasher.update(component.as_bytes());
150        }
151
152        // Include salt if provided
153        if let Some(s) = salt {
154            hasher.update(s.as_bytes());
155        }
156
157        let hash = hasher.finalize();
158        // Use first 16 bytes (32 hex chars) for reasonably unique IRI
159        let hash_str: String = hash
160            .iter()
161            .take(16)
162            .fold(String::with_capacity(32), |mut s, b| {
163                use std::fmt::Write as _;
164                let _ = write!(s, "{:02x}", b);
165                s
166            });
167
168        format!("{}{}", base, hash_str)
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    #[test]
177    fn test_generate_iri_deterministic() {
178        let iri1 = ConstructExecutor::generate_iri(
179            "http://ggen.dev/code#",
180            &["User", "struct"],
181            Some("salt-v1"),
182        );
183        let iri2 = ConstructExecutor::generate_iri(
184            "http://ggen.dev/code#",
185            &["User", "struct"],
186            Some("salt-v1"),
187        );
188        let iri3 = ConstructExecutor::generate_iri(
189            "http://ggen.dev/code#",
190            &["Order", "struct"],
191            Some("salt-v1"),
192        );
193
194        // Same inputs produce same output
195        assert_eq!(iri1, iri2);
196        // Different inputs produce different output
197        assert_ne!(iri1, iri3);
198    }
199
200    #[test]
201    fn test_generate_iri_format() {
202        let iri = ConstructExecutor::generate_iri("http://example.org/", &["test"], None);
203        assert!(iri.starts_with("http://example.org/"));
204        // Hash portion should be 32 hex chars
205        let hash_part = iri.strip_prefix("http://example.org/").unwrap();
206        assert_eq!(hash_part.len(), 32);
207    }
208
209    #[test]
210    fn test_construct_executor_creation() {
211        let graph = Graph::new().expect("Failed to create graph");
212        let _executor = ConstructExecutor::new(&graph);
213        // Just verify construction works
214    }
215
216    #[test]
217    fn test_execute_simple_construct() {
218        let graph = Graph::new().expect("Failed to create graph");
219        graph
220            .insert_turtle(
221                r#"
222            @prefix ex: <http://example.org/> .
223            ex:alice ex:knows ex:bob .
224        "#,
225            )
226            .expect("Failed to insert turtle");
227
228        let executor = ConstructExecutor::new(&graph);
229        let result = executor.execute(
230            r#"
231            PREFIX ex: <http://example.org/>
232            CONSTRUCT { ?s ex:related ?o }
233            WHERE { ?s ex:knows ?o }
234        "#,
235        );
236
237        assert!(result.is_ok());
238        let triples = result.unwrap();
239        assert_eq!(triples.len(), 1);
240    }
241}