ggen-core 26.7.3

Core graph-aware code generation engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! GraphUpdate - SPARQL Update operations
//!
//! Provides SPARQL 1.1 Update operations: INSERT, DELETE, UPDATE, LOAD, CLEAR, etc.

use crate::graph::core::Graph;
use crate::utils::error::{Error, Result};
use oxigraph::sparql::SparqlEvaluator;

/// GraphUpdate provides SPARQL Update operations.
///
/// SPARQL Update allows modifying RDF graphs using declarative update operations.
///
/// # Examples
///
/// ## Insert data
///
/// ```rust,no_run
/// use crate::graph::{Graph, GraphUpdate};
///
/// # fn main() -> crate::utils::error::Result<()> {
/// let graph = Graph::new()?;
/// let update = GraphUpdate::new(&graph);
///
/// // Insert new triples (without INSERT DATA wrapper)
/// update.insert("<http://example.org/alice> <http://example.org/name> \"Alice\"")?;
/// # Ok(())
/// # }
/// ```
///
/// ## Delete data
///
/// ```rust,no_run
/// use crate::graph::{Graph, GraphUpdate};
///
/// # fn main() -> crate::utils::error::Result<()> {
/// let graph = Graph::new()?;
/// let update = GraphUpdate::new(&graph);
///
/// // Delete triples matching a pattern (without DELETE DATA wrapper)
/// update.delete("<http://example.org/alice> <http://example.org/name> \"Alice\"")?;
/// # Ok(())
/// # }
/// ```
///
/// ## Update with WHERE clause
///
/// ```rust,no_run
/// use ggen_core::graph::{Graph, GraphUpdate};
///
/// # fn main() -> ggen_core::utils::error::Result<()> {
/// let graph = Graph::new()?;
/// let update = GraphUpdate::new(&graph);
///
/// // Delete and insert in one operation (DELETE / INSERT / WHERE patterns)
/// update.update(
///     "?s <http://example.org/old> ?o",
///     "?s <http://example.org/new> ?o",
///     "?s <http://example.org/old> ?o",
/// )?;
/// # Ok(())
/// # }
/// ```
pub struct GraphUpdate<'a> {
    graph: &'a Graph,
}

impl<'a> GraphUpdate<'a> {
    /// Create a new GraphUpdate instance for the given graph.
    pub fn new(graph: &'a Graph) -> Self {
        Self { graph }
    }

    /// Execute a SPARQL Update operation.
    ///
    /// Supports all SPARQL 1.1 Update operations:
    /// - INSERT DATA
    /// - DELETE DATA
    /// - DELETE/INSERT (with WHERE)
    /// - LOAD
    /// - CLEAR
    /// - COPY
    /// - MOVE
    /// - ADD
    ///
    /// # Arguments
    ///
    /// * `update` - SPARQL Update string
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The update syntax is invalid
    /// - The update cannot be executed
    pub fn execute(&self, update: &str) -> Result<()> {
        let evaluator = SparqlEvaluator::new();
        let prepared = evaluator
            .parse_update(update)
            .map_err(|e| Error::with_source("SPARQL Update parse error", Box::new(e)))?;
        prepared
            .on_store(self.graph.inner())
            .execute()
            .map_err(|e| Error::with_source("SPARQL Update execution error", Box::new(e)))?;
        self.graph.bump_epoch();
        Ok(())
    }

    /// Insert data into the graph.
    ///
    /// Shorthand for `INSERT DATA { ... }`.
    ///
    /// # Arguments
    ///
    /// * `data` - SPARQL data block (triples without INSERT DATA wrapper)
    ///
    /// # Security
    ///
    /// This method constructs SPARQL UPDATE queries. For user-provided data,
    /// prefer using type-safe builders from `crate::rdf::query_builder`.
    pub fn insert(&self, data: &str) -> Result<()> {
        // Note: This is a convenience method for trusted internal use.
        // For user-provided data, the query builder should be used instead.
        let update = format!("INSERT DATA {{ {} }}", data);
        self.execute(&update)
    }

    /// Delete data from the graph.
    ///
    /// Shorthand for `DELETE DATA { ... }`.
    ///
    /// # Arguments
    ///
    /// * `data` - SPARQL data block (triples without DELETE DATA wrapper)
    ///
    /// # Security
    ///
    /// This method constructs SPARQL UPDATE queries. For user-provided data,
    /// prefer using type-safe builders from `crate::rdf::query_builder`.
    pub fn delete(&self, data: &str) -> Result<()> {
        // Note: This is a convenience method for trusted internal use.
        // For user-provided data, the query builder should be used instead.
        let update = format!("DELETE DATA {{ {} }}", data);
        self.execute(&update)
    }

    /// Delete triples matching a WHERE pattern.
    ///
    /// Shorthand for `DELETE WHERE { ... }`.
    ///
    /// # Arguments
    ///
    /// * `pattern` - SPARQL WHERE pattern (without DELETE WHERE wrapper)
    ///
    /// # Security
    ///
    /// This method constructs SPARQL UPDATE queries. For user-provided data,
    /// prefer using type-safe builders from `crate::rdf::query_builder`.
    pub fn delete_where(&self, pattern: &str) -> Result<()> {
        // Note: This is a convenience method for trusted internal use.
        // For user-provided data, the query builder should be used instead.
        let update = format!("DELETE WHERE {{ {} }}", pattern);
        self.execute(&update)
    }

    /// Update data (DELETE + INSERT with WHERE).
    ///
    /// Shorthand for `DELETE { ... } INSERT { ... } WHERE { ... }`.
    ///
    /// # Arguments
    ///
    /// * `delete_pattern` - Pattern to delete
    /// * `insert_pattern` - Pattern to insert
    /// * `where_pattern` - WHERE clause pattern
    pub fn update(
        &self, delete_pattern: &str, insert_pattern: &str, where_pattern: &str,
    ) -> Result<()> {
        let update = format!(
            "DELETE {{ {} }} INSERT {{ {} }} WHERE {{ {} }}",
            delete_pattern, insert_pattern, where_pattern
        );
        self.execute(&update)
    }

    /// Clear the default graph.
    ///
    /// Removes all triples from the default graph.
    pub fn clear(&self) -> Result<()> {
        self.execute("CLEAR DEFAULT")
    }

    /// Clear a named graph.
    ///
    /// # Arguments
    ///
    /// * `graph_iri` - IRI of the graph to clear
    pub fn clear_graph(&self, graph_iri: &str) -> Result<()> {
        let update = format!("CLEAR GRAPH <{}>", graph_iri);
        self.execute(&update)
    }

    /// Clear all graphs (default + named).
    pub fn clear_all(&self) -> Result<()> {
        self.execute("CLEAR ALL")
    }

    /// Load data from a URL into the default graph.
    ///
    /// # Arguments
    ///
    /// * `url` - URL to load RDF data from
    pub fn load(&self, url: &str) -> Result<()> {
        let update = format!("LOAD <{}>", url);
        self.execute(&update)
    }

    /// Load data from a URL into a named graph.
    ///
    /// # Arguments
    ///
    /// * `url` - URL to load RDF data from
    /// * `graph_iri` - IRI of the target graph
    pub fn load_into(&self, url: &str, graph_iri: &str) -> Result<()> {
        let update = format!("LOAD <{}> INTO GRAPH <{}>", url, graph_iri);
        self.execute(&update)
    }

    /// Copy all data from source graph to destination graph.
    ///
    /// # Arguments
    ///
    /// * `source` - Source graph IRI
    /// * `destination` - Destination graph IRI
    pub fn copy(&self, source: &str, destination: &str) -> Result<()> {
        let update = format!("COPY <{}> TO <{}>", source, destination);
        self.execute(&update)
    }

    /// Move all data from source graph to destination graph.
    ///
    /// # Arguments
    ///
    /// * `source` - Source graph IRI
    /// * `destination` - Destination graph IRI
    pub fn move_graph(&self, source: &str, destination: &str) -> Result<()> {
        let update = format!("MOVE <{}> TO <{}>", source, destination);
        self.execute(&update)
    }

    /// Add all data from source graph to destination graph.
    ///
    /// # Arguments
    ///
    /// * `source` - Source graph IRI
    /// * `destination` - Destination graph IRI
    pub fn add(&self, source: &str, destination: &str) -> Result<()> {
        let update = format!("ADD <{}> TO <{}>", source, destination);
        self.execute(&update)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::core::Graph;

    #[test]
    fn test_update_insert() {
        // Arrange
        let graph = Graph::new().unwrap();
        let update = GraphUpdate::new(&graph);

        // Act
        update
            .insert("<http://example.org/alice> <http://example.org/name> \"Alice\"")
            .unwrap();

        // Assert
        assert!(!graph.is_empty());
        let results = graph
            .query_cached(
                "SELECT ?name WHERE { <http://example.org/alice> <http://example.org/name> ?name }",
            )
            .unwrap();
        match results {
            crate::graph::types::CachedResult::Solutions(rows) => {
                assert!(!rows.is_empty());
                assert_eq!(rows[0].get("name"), Some(&"\"Alice\"".to_string()));
            }
            _ => panic!("Expected solutions"),
        }
    }

    #[test]
    fn test_update_delete() {
        // Arrange
        let graph = Graph::new().unwrap();
        graph
            .insert_turtle(
                r#"
            @prefix ex: <http://example.org/> .
            ex:alice ex:name "Alice" .
        "#,
            )
            .unwrap();
        let update = GraphUpdate::new(&graph);
        let initial_len = graph.len();

        // Act
        update
            .delete("<http://example.org/alice> <http://example.org/name> \"Alice\"")
            .unwrap();

        // Assert
        assert!(graph.len() < initial_len);
    }

    #[test]
    fn test_update_delete_where() {
        // Arrange
        let graph = Graph::new().unwrap();
        graph
            .insert_turtle(
                r#"
            @prefix ex: <http://example.org/> .
            ex:alice ex:name "Alice" .
            ex:bob ex:name "Bob" .
        "#,
            )
            .unwrap();
        let update = GraphUpdate::new(&graph);
        let initial_len = graph.len();

        // Act
        update
            .delete_where("?s <http://example.org/name> \"Alice\"")
            .unwrap();

        // Assert
        assert!(graph.len() < initial_len);
        let results = graph
            .query_cached("ASK { <http://example.org/alice> <http://example.org/name> \"Alice\" }")
            .unwrap();
        match results {
            crate::graph::types::CachedResult::Boolean(false) => {}
            _ => panic!("Expected false (triple should be deleted)"),
        }
    }

    #[test]
    fn test_update_update_operation() {
        // Arrange
        let graph = Graph::new().unwrap();
        graph
            .insert_turtle(
                r#"
            @prefix ex: <http://example.org/> .
            ex:alice ex:age "30" .
        "#,
            )
            .unwrap();
        let update = GraphUpdate::new(&graph);

        // Act - Use full IRIs since we're not declaring prefixes
        update
            .update(
                "?s <http://example.org/age> ?o",
                "?s <http://example.org/age> \"31\"",
                "?s <http://example.org/age> ?o",
            )
            .unwrap();

        // Assert
        let results = graph
            .query_cached(
                "SELECT ?age WHERE { <http://example.org/alice> <http://example.org/age> ?age }",
            )
            .unwrap();
        match results {
            crate::graph::types::CachedResult::Solutions(rows) => {
                assert!(!rows.is_empty());
                assert_eq!(rows[0].get("age"), Some(&"\"31\"".to_string()));
            }
            _ => panic!("Expected solutions"),
        }
    }

    #[test]
    fn test_update_clear() {
        // Arrange
        let graph = Graph::new().unwrap();
        graph
            .insert_turtle(
                r#"
            @prefix ex: <http://example.org/> .
            ex:alice a ex:Person .
        "#,
            )
            .unwrap();
        let update = GraphUpdate::new(&graph);
        assert!(!graph.is_empty());

        // Act
        update.clear().unwrap();

        // Assert
        assert!(graph.is_empty());
    }

    #[test]
    fn test_update_clear_graph() {
        // Arrange
        let graph = Graph::new().unwrap();
        graph
            .insert_turtle_in(
                r#"
            @prefix ex: <http://example.org/> .
            ex:alice a ex:Person .
        "#,
                "http://example.org/graph1",
            )
            .unwrap();
        let update = GraphUpdate::new(&graph);
        let initial_len = graph.len();

        // Act
        update.clear_graph("http://example.org/graph1").unwrap();

        // Assert
        assert!(graph.len() < initial_len);
    }

    #[test]
    fn test_update_clear_all() {
        // Arrange
        let graph = Graph::new().unwrap();
        graph
            .insert_turtle(
                r#"
            @prefix ex: <http://example.org/> .
            ex:alice a ex:Person .
        "#,
            )
            .unwrap();
        let update = GraphUpdate::new(&graph);
        assert!(!graph.is_empty());

        // Act
        update.clear_all().unwrap();

        // Assert
        assert!(graph.is_empty());
    }

    #[test]
    fn test_update_execute_invalid_syntax() {
        // Arrange
        let graph = Graph::new().unwrap();
        let update = GraphUpdate::new(&graph);

        // Act & Assert
        let result = update.execute("INVALID UPDATE SYNTAX");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("SPARQL Update"));
    }

    #[test]
    fn test_update_copy() {
        // Arrange
        let graph = Graph::new().unwrap();
        graph
            .insert_turtle_in(
                r#"
            @prefix ex: <http://example.org/> .
            ex:alice a ex:Person .
        "#,
                "http://example.org/graph1",
            )
            .unwrap();
        let update = GraphUpdate::new(&graph);

        // Act
        update
            .copy("http://example.org/graph1", "http://example.org/graph2")
            .unwrap();

        // Assert - Both graphs should have data
        let results1 = graph
            .query_cached("ASK { GRAPH <http://example.org/graph1> { ?s ?p ?o } }")
            .unwrap();
        let results2 = graph
            .query_cached("ASK { GRAPH <http://example.org/graph2> { ?s ?p ?o } }")
            .unwrap();
        match (results1, results2) {
            (
                crate::graph::types::CachedResult::Boolean(true),
                crate::graph::types::CachedResult::Boolean(true),
            ) => {}
            _ => panic!("Both graphs should have data after copy"),
        }
    }
}