Skip to main content

ggen_core/graph/
update.rs

1//! GraphUpdate - SPARQL Update operations
2//!
3//! Provides SPARQL 1.1 Update operations: INSERT, DELETE, UPDATE, LOAD, CLEAR, etc.
4
5use crate::graph::core::Graph;
6use crate::utils::error::{Error, Result};
7use oxigraph::sparql::SparqlEvaluator;
8
9/// GraphUpdate provides SPARQL Update operations.
10///
11/// SPARQL Update allows modifying RDF graphs using declarative update operations.
12///
13/// # Examples
14///
15/// ## Insert data
16///
17/// ```rust,no_run
18/// use crate::graph::{Graph, GraphUpdate};
19///
20/// # fn main() -> crate::utils::error::Result<()> {
21/// let graph = Graph::new()?;
22/// let update = GraphUpdate::new(&graph);
23///
24/// // Insert new triples (without INSERT DATA wrapper)
25/// update.insert("<http://example.org/alice> <http://example.org/name> \"Alice\"")?;
26/// # Ok(())
27/// # }
28/// ```
29///
30/// ## Delete data
31///
32/// ```rust,no_run
33/// use crate::graph::{Graph, GraphUpdate};
34///
35/// # fn main() -> crate::utils::error::Result<()> {
36/// let graph = Graph::new()?;
37/// let update = GraphUpdate::new(&graph);
38///
39/// // Delete triples matching a pattern (without DELETE DATA wrapper)
40/// update.delete("<http://example.org/alice> <http://example.org/name> \"Alice\"")?;
41/// # Ok(())
42/// # }
43/// ```
44///
45/// ## Update with WHERE clause
46///
47/// ```rust,no_run
48/// use ggen_core::graph::{Graph, GraphUpdate};
49///
50/// # fn main() -> ggen_core::utils::error::Result<()> {
51/// let graph = Graph::new()?;
52/// let update = GraphUpdate::new(&graph);
53///
54/// // Delete and insert in one operation (DELETE / INSERT / WHERE patterns)
55/// update.update(
56///     "?s <http://example.org/old> ?o",
57///     "?s <http://example.org/new> ?o",
58///     "?s <http://example.org/old> ?o",
59/// )?;
60/// # Ok(())
61/// # }
62/// ```
63pub struct GraphUpdate<'a> {
64    graph: &'a Graph,
65}
66
67impl<'a> GraphUpdate<'a> {
68    /// Create a new GraphUpdate instance for the given graph.
69    pub fn new(graph: &'a Graph) -> Self {
70        Self { graph }
71    }
72
73    /// Execute a SPARQL Update operation.
74    ///
75    /// Supports all SPARQL 1.1 Update operations:
76    /// - INSERT DATA
77    /// - DELETE DATA
78    /// - DELETE/INSERT (with WHERE)
79    /// - LOAD
80    /// - CLEAR
81    /// - COPY
82    /// - MOVE
83    /// - ADD
84    ///
85    /// # Arguments
86    ///
87    /// * `update` - SPARQL Update string
88    ///
89    /// # Errors
90    ///
91    /// Returns an error if:
92    /// - The update syntax is invalid
93    /// - The update cannot be executed
94    pub fn execute(&self, update: &str) -> Result<()> {
95        let evaluator = SparqlEvaluator::new();
96        let prepared = evaluator
97            .parse_update(update)
98            .map_err(|e| Error::with_source("SPARQL Update parse error", Box::new(e)))?;
99        prepared
100            .on_store(self.graph.inner())
101            .execute()
102            .map_err(|e| Error::with_source("SPARQL Update execution error", Box::new(e)))?;
103        self.graph.bump_epoch();
104        Ok(())
105    }
106
107    /// Insert data into the graph.
108    ///
109    /// Shorthand for `INSERT DATA { ... }`.
110    ///
111    /// # Arguments
112    ///
113    /// * `data` - SPARQL data block (triples without INSERT DATA wrapper)
114    ///
115    /// # Security
116    ///
117    /// This method constructs SPARQL UPDATE queries. For user-provided data,
118    /// prefer using type-safe builders from `crate::rdf::query_builder`.
119    pub fn insert(&self, data: &str) -> Result<()> {
120        // Note: This is a convenience method for trusted internal use.
121        // For user-provided data, the query builder should be used instead.
122        let update = format!("INSERT DATA {{ {} }}", data);
123        self.execute(&update)
124    }
125
126    /// Delete data from the graph.
127    ///
128    /// Shorthand for `DELETE DATA { ... }`.
129    ///
130    /// # Arguments
131    ///
132    /// * `data` - SPARQL data block (triples without DELETE DATA wrapper)
133    ///
134    /// # Security
135    ///
136    /// This method constructs SPARQL UPDATE queries. For user-provided data,
137    /// prefer using type-safe builders from `crate::rdf::query_builder`.
138    pub fn delete(&self, data: &str) -> Result<()> {
139        // Note: This is a convenience method for trusted internal use.
140        // For user-provided data, the query builder should be used instead.
141        let update = format!("DELETE DATA {{ {} }}", data);
142        self.execute(&update)
143    }
144
145    /// Delete triples matching a WHERE pattern.
146    ///
147    /// Shorthand for `DELETE WHERE { ... }`.
148    ///
149    /// # Arguments
150    ///
151    /// * `pattern` - SPARQL WHERE pattern (without DELETE WHERE wrapper)
152    ///
153    /// # Security
154    ///
155    /// This method constructs SPARQL UPDATE queries. For user-provided data,
156    /// prefer using type-safe builders from `crate::rdf::query_builder`.
157    pub fn delete_where(&self, pattern: &str) -> Result<()> {
158        // Note: This is a convenience method for trusted internal use.
159        // For user-provided data, the query builder should be used instead.
160        let update = format!("DELETE WHERE {{ {} }}", pattern);
161        self.execute(&update)
162    }
163
164    /// Update data (DELETE + INSERT with WHERE).
165    ///
166    /// Shorthand for `DELETE { ... } INSERT { ... } WHERE { ... }`.
167    ///
168    /// # Arguments
169    ///
170    /// * `delete_pattern` - Pattern to delete
171    /// * `insert_pattern` - Pattern to insert
172    /// * `where_pattern` - WHERE clause pattern
173    pub fn update(
174        &self, delete_pattern: &str, insert_pattern: &str, where_pattern: &str,
175    ) -> Result<()> {
176        let update = format!(
177            "DELETE {{ {} }} INSERT {{ {} }} WHERE {{ {} }}",
178            delete_pattern, insert_pattern, where_pattern
179        );
180        self.execute(&update)
181    }
182
183    /// Clear the default graph.
184    ///
185    /// Removes all triples from the default graph.
186    pub fn clear(&self) -> Result<()> {
187        self.execute("CLEAR DEFAULT")
188    }
189
190    /// Clear a named graph.
191    ///
192    /// # Arguments
193    ///
194    /// * `graph_iri` - IRI of the graph to clear
195    pub fn clear_graph(&self, graph_iri: &str) -> Result<()> {
196        let update = format!("CLEAR GRAPH <{}>", graph_iri);
197        self.execute(&update)
198    }
199
200    /// Clear all graphs (default + named).
201    pub fn clear_all(&self) -> Result<()> {
202        self.execute("CLEAR ALL")
203    }
204
205    /// Load data from a URL into the default graph.
206    ///
207    /// # Arguments
208    ///
209    /// * `url` - URL to load RDF data from
210    pub fn load(&self, url: &str) -> Result<()> {
211        let update = format!("LOAD <{}>", url);
212        self.execute(&update)
213    }
214
215    /// Load data from a URL into a named graph.
216    ///
217    /// # Arguments
218    ///
219    /// * `url` - URL to load RDF data from
220    /// * `graph_iri` - IRI of the target graph
221    pub fn load_into(&self, url: &str, graph_iri: &str) -> Result<()> {
222        let update = format!("LOAD <{}> INTO GRAPH <{}>", url, graph_iri);
223        self.execute(&update)
224    }
225
226    /// Copy all data from source graph to destination graph.
227    ///
228    /// # Arguments
229    ///
230    /// * `source` - Source graph IRI
231    /// * `destination` - Destination graph IRI
232    pub fn copy(&self, source: &str, destination: &str) -> Result<()> {
233        let update = format!("COPY <{}> TO <{}>", source, destination);
234        self.execute(&update)
235    }
236
237    /// Move all data from source graph to destination graph.
238    ///
239    /// # Arguments
240    ///
241    /// * `source` - Source graph IRI
242    /// * `destination` - Destination graph IRI
243    pub fn move_graph(&self, source: &str, destination: &str) -> Result<()> {
244        let update = format!("MOVE <{}> TO <{}>", source, destination);
245        self.execute(&update)
246    }
247
248    /// Add all data from source graph to destination graph.
249    ///
250    /// # Arguments
251    ///
252    /// * `source` - Source graph IRI
253    /// * `destination` - Destination graph IRI
254    pub fn add(&self, source: &str, destination: &str) -> Result<()> {
255        let update = format!("ADD <{}> TO <{}>", source, destination);
256        self.execute(&update)
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use crate::graph::core::Graph;
264
265    #[test]
266    fn test_update_insert() {
267        // Arrange
268        let graph = Graph::new().unwrap();
269        let update = GraphUpdate::new(&graph);
270
271        // Act
272        update
273            .insert("<http://example.org/alice> <http://example.org/name> \"Alice\"")
274            .unwrap();
275
276        // Assert
277        assert!(!graph.is_empty());
278        let results = graph
279            .query_cached(
280                "SELECT ?name WHERE { <http://example.org/alice> <http://example.org/name> ?name }",
281            )
282            .unwrap();
283        match results {
284            crate::graph::types::CachedResult::Solutions(rows) => {
285                assert!(!rows.is_empty());
286                assert_eq!(rows[0].get("name"), Some(&"\"Alice\"".to_string()));
287            }
288            _ => panic!("Expected solutions"),
289        }
290    }
291
292    #[test]
293    fn test_update_delete() {
294        // Arrange
295        let graph = Graph::new().unwrap();
296        graph
297            .insert_turtle(
298                r#"
299            @prefix ex: <http://example.org/> .
300            ex:alice ex:name "Alice" .
301        "#,
302            )
303            .unwrap();
304        let update = GraphUpdate::new(&graph);
305        let initial_len = graph.len();
306
307        // Act
308        update
309            .delete("<http://example.org/alice> <http://example.org/name> \"Alice\"")
310            .unwrap();
311
312        // Assert
313        assert!(graph.len() < initial_len);
314    }
315
316    #[test]
317    fn test_update_delete_where() {
318        // Arrange
319        let graph = Graph::new().unwrap();
320        graph
321            .insert_turtle(
322                r#"
323            @prefix ex: <http://example.org/> .
324            ex:alice ex:name "Alice" .
325            ex:bob ex:name "Bob" .
326        "#,
327            )
328            .unwrap();
329        let update = GraphUpdate::new(&graph);
330        let initial_len = graph.len();
331
332        // Act
333        update
334            .delete_where("?s <http://example.org/name> \"Alice\"")
335            .unwrap();
336
337        // Assert
338        assert!(graph.len() < initial_len);
339        let results = graph
340            .query_cached("ASK { <http://example.org/alice> <http://example.org/name> \"Alice\" }")
341            .unwrap();
342        match results {
343            crate::graph::types::CachedResult::Boolean(false) => {}
344            _ => panic!("Expected false (triple should be deleted)"),
345        }
346    }
347
348    #[test]
349    fn test_update_update_operation() {
350        // Arrange
351        let graph = Graph::new().unwrap();
352        graph
353            .insert_turtle(
354                r#"
355            @prefix ex: <http://example.org/> .
356            ex:alice ex:age "30" .
357        "#,
358            )
359            .unwrap();
360        let update = GraphUpdate::new(&graph);
361
362        // Act - Use full IRIs since we're not declaring prefixes
363        update
364            .update(
365                "?s <http://example.org/age> ?o",
366                "?s <http://example.org/age> \"31\"",
367                "?s <http://example.org/age> ?o",
368            )
369            .unwrap();
370
371        // Assert
372        let results = graph
373            .query_cached(
374                "SELECT ?age WHERE { <http://example.org/alice> <http://example.org/age> ?age }",
375            )
376            .unwrap();
377        match results {
378            crate::graph::types::CachedResult::Solutions(rows) => {
379                assert!(!rows.is_empty());
380                assert_eq!(rows[0].get("age"), Some(&"\"31\"".to_string()));
381            }
382            _ => panic!("Expected solutions"),
383        }
384    }
385
386    #[test]
387    fn test_update_clear() {
388        // Arrange
389        let graph = Graph::new().unwrap();
390        graph
391            .insert_turtle(
392                r#"
393            @prefix ex: <http://example.org/> .
394            ex:alice a ex:Person .
395        "#,
396            )
397            .unwrap();
398        let update = GraphUpdate::new(&graph);
399        assert!(!graph.is_empty());
400
401        // Act
402        update.clear().unwrap();
403
404        // Assert
405        assert!(graph.is_empty());
406    }
407
408    #[test]
409    fn test_update_clear_graph() {
410        // Arrange
411        let graph = Graph::new().unwrap();
412        graph
413            .insert_turtle_in(
414                r#"
415            @prefix ex: <http://example.org/> .
416            ex:alice a ex:Person .
417        "#,
418                "http://example.org/graph1",
419            )
420            .unwrap();
421        let update = GraphUpdate::new(&graph);
422        let initial_len = graph.len();
423
424        // Act
425        update.clear_graph("http://example.org/graph1").unwrap();
426
427        // Assert
428        assert!(graph.len() < initial_len);
429    }
430
431    #[test]
432    fn test_update_clear_all() {
433        // Arrange
434        let graph = Graph::new().unwrap();
435        graph
436            .insert_turtle(
437                r#"
438            @prefix ex: <http://example.org/> .
439            ex:alice a ex:Person .
440        "#,
441            )
442            .unwrap();
443        let update = GraphUpdate::new(&graph);
444        assert!(!graph.is_empty());
445
446        // Act
447        update.clear_all().unwrap();
448
449        // Assert
450        assert!(graph.is_empty());
451    }
452
453    #[test]
454    fn test_update_execute_invalid_syntax() {
455        // Arrange
456        let graph = Graph::new().unwrap();
457        let update = GraphUpdate::new(&graph);
458
459        // Act & Assert
460        let result = update.execute("INVALID UPDATE SYNTAX");
461        assert!(result.is_err());
462        assert!(result.unwrap_err().to_string().contains("SPARQL Update"));
463    }
464
465    #[test]
466    fn test_update_copy() {
467        // Arrange
468        let graph = Graph::new().unwrap();
469        graph
470            .insert_turtle_in(
471                r#"
472            @prefix ex: <http://example.org/> .
473            ex:alice a ex:Person .
474        "#,
475                "http://example.org/graph1",
476            )
477            .unwrap();
478        let update = GraphUpdate::new(&graph);
479
480        // Act
481        update
482            .copy("http://example.org/graph1", "http://example.org/graph2")
483            .unwrap();
484
485        // Assert - Both graphs should have data
486        let results1 = graph
487            .query_cached("ASK { GRAPH <http://example.org/graph1> { ?s ?p ?o } }")
488            .unwrap();
489        let results2 = graph
490            .query_cached("ASK { GRAPH <http://example.org/graph2> { ?s ?p ?o } }")
491            .unwrap();
492        match (results1, results2) {
493            (
494                crate::graph::types::CachedResult::Boolean(true),
495                crate::graph::types::CachedResult::Boolean(true),
496            ) => {}
497            _ => panic!("Both graphs should have data after copy"),
498        }
499    }
500}