Skip to main content

ggen_core/graph/
export.rs

1//! GraphExport - RDF serialization and export
2//!
3//! Provides operations for exporting RDF graphs to files and streams
4//! in various RDF formats using Oxigraph's core team best practices.
5//!
6//! ## Implementation
7//!
8//! This module uses Oxigraph's `RdfSerializer` API following the recommended pattern:
9//! 1. Create serializer with `RdfSerializer::from_format().for_writer()`
10//! 2. Iterate over quads and serialize each with `serialize_quad()`
11//! 3. Complete serialization with `finish()`
12//!
13//! This ensures proper format-specific serialization for all supported RDF formats:
14//! Turtle, N-Triples, RDF/XML, TriG, and N-Quads.
15
16use crate::graph::core::Graph;
17use crate::utils::error::{Error, Result};
18use oxigraph::io::{RdfFormat, RdfSerializer};
19use std::fs::File;
20use std::io::{BufWriter, Write};
21use std::path::Path;
22
23/// GraphExport provides RDF serialization and export operations.
24///
25/// Uses Oxigraph's `RdfSerializer` API following core team best practices for
26/// efficient and format-compliant RDF serialization.
27///
28/// Supports exporting graphs to files and streams in all RDF formats:
29/// - Turtle (.ttl) - Human-readable format with prefix support
30/// - N-Triples (.nt) - Line-based format with full IRIs
31/// - RDF/XML (.rdf, .xml) - XML-based RDF serialization
32/// - TriG (.trig) - Turtle format with named graph support
33/// - N-Quads (.nq) - N-Triples format with named graph support
34///
35/// # Examples
36///
37/// ## Export to file
38///
39/// ```rust,no_run
40/// use crate::graph::{Graph, GraphExport};
41/// use oxigraph::io::RdfFormat;
42///
43/// # fn main() -> crate::utils::error::Result<()> {
44/// let graph = Graph::new()?;
45/// graph.insert_turtle(r#"
46///     @prefix ex: <http://example.org/> .
47///     ex:alice a ex:Person .
48/// "#)?;
49///
50/// let export = GraphExport::new(&graph);
51/// export.write_to_file("output.ttl", RdfFormat::Turtle)?;
52/// # Ok(())
53/// # }
54/// ```
55///
56/// ## Export to string
57///
58/// ```rust,no_run
59/// use crate::graph::{Graph, GraphExport};
60/// use oxigraph::io::RdfFormat;
61///
62/// # fn main() -> crate::utils::error::Result<()> {
63/// let graph = Graph::new()?;
64/// let export = GraphExport::new(&graph);
65///
66/// let turtle = export.write_to_string(RdfFormat::Turtle)?;
67/// println!("{}", turtle);
68/// # Ok(())
69/// # }
70/// ```
71pub struct GraphExport<'a> {
72    graph: &'a Graph,
73}
74
75impl<'a> GraphExport<'a> {
76    /// Create a new GraphExport instance for the given graph.
77    pub fn new(graph: &'a Graph) -> Self {
78        Self { graph }
79    }
80
81    /// Write the graph to a file in the specified format.
82    ///
83    /// # Arguments
84    ///
85    /// * `path` - Path to the output file
86    /// * `format` - RDF format to use
87    ///
88    /// # Errors
89    ///
90    /// Returns an error if:
91    /// - The file cannot be created or written
92    /// - The format is unsupported
93    pub fn write_to_file<P: AsRef<Path>>(&self, path: P, format: RdfFormat) -> Result<()> {
94        let file =
95            File::create(path).map_err(|e| Error::new(&format!("Failed to create file: {}", e)))?;
96        let writer = BufWriter::new(file);
97        self.write_to_writer(writer, format)
98    }
99
100    /// Write the graph to a writer in the specified format.
101    ///
102    /// Uses Oxigraph's Store API appropriately:
103    /// - For graph formats (Turtle, N-Triples, RDF/XML): manually serializes default graph only
104    /// - For dataset formats (TriG, N-Quads): uses `dump_to_writer` for all graphs
105    ///
106    /// # Arguments
107    ///
108    /// * `writer` - Writer to write to
109    /// * `format` - RDF format to use (Turtle, N-Triples, RDF/XML, TriG, N-Quads)
110    pub fn write_to_writer<W: Write>(&self, mut writer: W, format: RdfFormat) -> Result<()> {
111        use oxigraph::model::GraphName;
112
113        // Graph formats (Turtle, N-Triples, RDF/XML) only support single graphs
114        // Dataset formats (TriG, N-Quads) support multiple named graphs
115        match format {
116            RdfFormat::Turtle | RdfFormat::NTriples | RdfFormat::RdfXml => {
117                // For single-graph formats, manually serialize only the default graph
118                // This prevents "dataset format expected" errors
119                let mut serializer = RdfSerializer::from_format(format).for_writer(&mut writer);
120
121                // Query only the default graph quads
122                let default_graph_quads = self.graph.quads_for_pattern(
123                    None,                           // subject: any
124                    None,                           // predicate: any
125                    None,                           // object: any
126                    Some(&GraphName::DefaultGraph), // graph_name: default graph only
127                )?;
128
129                // Serialize each quad from the default graph
130                for quad in default_graph_quads {
131                    serializer
132                        .serialize_quad(&quad)
133                        .map_err(|e| Error::new(&format!("Failed to serialize quad: {}", e)))?;
134                }
135
136                // Finish serialization
137                serializer.finish().map_err(|e| {
138                    Error::new(&format!("Failed to finish RDF serialization: {}", e))
139                })?;
140            }
141            RdfFormat::TriG | RdfFormat::NQuads => {
142                // For dataset formats, dump all graphs
143                let serializer = RdfSerializer::from_format(format);
144                self.graph.inner().dump_to_writer(serializer, &mut writer)?;
145            }
146            _ => {
147                // For any other formats, try the dataset approach
148                let serializer = RdfSerializer::from_format(format);
149                self.graph.inner().dump_to_writer(serializer, &mut writer)?;
150            }
151        }
152        Ok(())
153    }
154
155    /// Write the graph to a string in the specified format.
156    ///
157    /// # Arguments
158    ///
159    /// * `format` - RDF format to use
160    ///
161    /// # Returns
162    ///
163    /// The serialized RDF as a string in the requested format.
164    pub fn write_to_string(&self, format: RdfFormat) -> Result<String> {
165        let mut buffer = Vec::new();
166        self.write_to_writer(&mut buffer, format)?;
167        String::from_utf8(buffer)
168            .map_err(|e| Error::new(&format!("Invalid UTF-8 in RDF output: {}", e)))
169    }
170
171    /// Write the graph to a file, auto-detecting format from extension.
172    ///
173    /// Supported extensions:
174    /// - `.ttl`, `.turtle` - Turtle
175    /// - `.nt`, `.ntriples` - N-Triples
176    /// - `.rdf`, `.xml` - RDF/XML
177    /// - `.trig` - TriG
178    /// - `.nq`, `.nquads` - N-Quads
179    ///
180    /// # Arguments
181    ///
182    /// * `path` - Path to the output file
183    ///
184    /// # Errors
185    ///
186    /// Returns an error if:
187    /// - The file extension is unsupported
188    /// - The file cannot be created or written
189    pub fn write_to_file_auto<P: AsRef<Path>>(&self, path: P) -> Result<()> {
190        let path = path.as_ref();
191        let ext = path
192            .extension()
193            .and_then(|e| e.to_str())
194            .map(|s| s.to_ascii_lowercase())
195            .unwrap_or_default();
196
197        let format = match ext.as_str() {
198            "ttl" | "turtle" => RdfFormat::Turtle,
199            "nt" | "ntriples" => RdfFormat::NTriples,
200            "rdf" | "xml" => RdfFormat::RdfXml,
201            "trig" => RdfFormat::TriG,
202            "nq" | "nquads" => RdfFormat::NQuads,
203            other => {
204                return Err(Error::new(&format!(
205                    "unsupported RDF format extension: {}",
206                    other
207                )))
208            }
209        };
210
211        self.write_to_file(path, format)
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use crate::graph::core::Graph;
219    use oxigraph::io::RdfFormat;
220    use std::fs;
221    use tempfile::TempDir;
222
223    #[test]
224    fn test_export_write_to_file() {
225        // Arrange
226        let graph = Graph::new().unwrap();
227        graph
228            .insert_turtle(
229                r#"
230            @prefix ex: <http://example.org/> .
231            ex:alice a ex:Person ;
232                     ex:name "Alice" .
233        "#,
234            )
235            .unwrap();
236        let export = GraphExport::new(&graph);
237        let temp_dir = TempDir::new().unwrap();
238        let file_path = temp_dir.path().join("output.ttl");
239
240        // Act
241        export.write_to_file(&file_path, RdfFormat::Turtle).unwrap();
242
243        // Assert
244        assert!(file_path.exists());
245        let content = fs::read_to_string(&file_path).unwrap();
246        // Turtle serialization may use full IRIs or prefixes depending on serializer config
247        // Check for either the prefix form or the full IRI
248        assert!(content.contains("ex:alice") || content.contains("http://example.org/alice"));
249        assert!(content.contains("ex:Person") || content.contains("http://example.org/Person"));
250    }
251
252    #[test]
253    fn test_export_write_to_string_turtle() {
254        // Arrange
255        let graph = Graph::new().unwrap();
256        graph
257            .insert_turtle(
258                r#"
259            @prefix ex: <http://example.org/> .
260            ex:alice a ex:Person .
261        "#,
262            )
263            .unwrap();
264        let export = GraphExport::new(&graph);
265
266        // Act
267        let result = export.write_to_string(RdfFormat::Turtle).unwrap();
268
269        // Assert
270        assert!(!result.is_empty());
271        // Turtle format should contain prefix or triples
272        assert!(result.contains("ex:") || result.contains("http://example.org/"));
273    }
274
275    #[test]
276    fn test_export_write_to_string_ntriples() {
277        // Arrange
278        let graph = Graph::new().unwrap();
279        graph
280            .insert_turtle(
281                r#"
282            @prefix ex: <http://example.org/> .
283            ex:alice a ex:Person .
284        "#,
285            )
286            .unwrap();
287        let export = GraphExport::new(&graph);
288
289        // Act
290        let result = export.write_to_string(RdfFormat::NTriples).unwrap();
291
292        // Assert
293        assert!(!result.is_empty());
294        // N-Triples format should contain full IRIs
295        assert!(result.contains("http://example.org/alice"));
296    }
297
298    #[test]
299    fn test_export_write_to_string_rdfxml() {
300        // Arrange
301        let graph = Graph::new().unwrap();
302        graph
303            .insert_turtle(
304                r#"
305            @prefix ex: <http://example.org/> .
306            ex:alice a ex:Person .
307        "#,
308            )
309            .unwrap();
310        let export = GraphExport::new(&graph);
311
312        // Act
313        let result = export.write_to_string(RdfFormat::RdfXml).unwrap();
314
315        // Assert
316        assert!(!result.is_empty());
317        // RDF/XML format should contain XML tags
318        assert!(result.contains('<') && result.contains('>'));
319    }
320
321    #[test]
322    fn test_export_write_to_file_auto_turtle() {
323        // Arrange
324        let graph = Graph::new().unwrap();
325        graph
326            .insert_turtle(
327                r#"
328            @prefix ex: <http://example.org/> .
329            ex:alice a ex:Person .
330        "#,
331            )
332            .unwrap();
333        let export = GraphExport::new(&graph);
334        let temp_dir = TempDir::new().unwrap();
335        let file_path = temp_dir.path().join("output.ttl");
336
337        // Act
338        export.write_to_file_auto(&file_path).unwrap();
339
340        // Assert
341        assert!(file_path.exists());
342        let content = fs::read_to_string(&file_path).unwrap();
343        assert!(!content.is_empty());
344    }
345
346    #[test]
347    fn test_export_write_to_file_auto_ntriples() {
348        // Arrange
349        let graph = Graph::new().unwrap();
350        graph
351            .insert_turtle(
352                r#"
353            @prefix ex: <http://example.org/> .
354            ex:alice a ex:Person .
355        "#,
356            )
357            .unwrap();
358        let export = GraphExport::new(&graph);
359        let temp_dir = TempDir::new().unwrap();
360        let file_path = temp_dir.path().join("output.nt");
361
362        // Act
363        export.write_to_file_auto(&file_path).unwrap();
364
365        // Assert
366        assert!(file_path.exists());
367        let content = fs::read_to_string(&file_path).unwrap();
368        assert!(!content.is_empty());
369    }
370
371    #[test]
372    fn test_export_write_to_file_auto_unsupported_format() {
373        // Arrange
374        let graph = Graph::new().unwrap();
375        let export = GraphExport::new(&graph);
376        let temp_dir = TempDir::new().unwrap();
377        let file_path = temp_dir.path().join("output.unknown");
378
379        // Act & Assert
380        let result = export.write_to_file_auto(&file_path);
381        assert!(result.is_err());
382        assert!(result.unwrap_err().to_string().contains("unsupported"));
383    }
384
385    #[test]
386    fn test_export_format_specific_serialization() {
387        // Arrange
388        let graph = Graph::new().unwrap();
389        graph
390            .insert_turtle(
391                r#"
392            @prefix ex: <http://example.org/> .
393            ex:alice a ex:Person .
394        "#,
395            )
396            .unwrap();
397        let export = GraphExport::new(&graph);
398
399        // Act - Test multiple formats
400        let turtle = export.write_to_string(RdfFormat::Turtle).unwrap();
401        let ntriples = export.write_to_string(RdfFormat::NTriples).unwrap();
402        let rdfxml = export.write_to_string(RdfFormat::RdfXml).unwrap();
403        let trig = export.write_to_string(RdfFormat::TriG).unwrap();
404        let nquads = export.write_to_string(RdfFormat::NQuads).unwrap();
405
406        // Assert - Each format should produce different output
407        assert!(!turtle.is_empty());
408        assert!(!ntriples.is_empty());
409        assert!(!rdfxml.is_empty());
410        assert!(!trig.is_empty());
411        assert!(!nquads.is_empty());
412        // Formats should be different (at least one should differ)
413        assert!(turtle != ntriples || turtle != rdfxml || ntriples != rdfxml);
414    }
415
416    #[test]
417    fn test_export_turtle_format_preserves_prefixes() {
418        // Arrange
419        let graph = Graph::new().unwrap();
420        graph
421            .insert_turtle(
422                r#"
423            @prefix ex: <http://example.org/> .
424            @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
425            ex:alice a ex:Person ;
426                     ex:name "Alice" .
427        "#,
428            )
429            .unwrap();
430        let export = GraphExport::new(&graph);
431
432        // Act
433        let turtle = export.write_to_string(RdfFormat::Turtle).unwrap();
434
435        // Assert - Turtle format should preserve prefixes or use full IRIs
436        assert!(turtle.contains("ex:") || turtle.contains("http://example.org/"));
437        assert!(turtle.contains("alice") || turtle.contains("Alice"));
438    }
439
440    #[test]
441    fn test_export_ntriples_format_uses_full_iris() {
442        // Arrange
443        let graph = Graph::new().unwrap();
444        graph
445            .insert_turtle(
446                r#"
447            @prefix ex: <http://example.org/> .
448            ex:alice a ex:Person .
449        "#,
450            )
451            .unwrap();
452        let export = GraphExport::new(&graph);
453
454        // Act
455        let ntriples = export.write_to_string(RdfFormat::NTriples).unwrap();
456
457        // Assert - N-Triples format should use full IRIs, not prefixes
458        assert!(ntriples.contains("http://example.org/alice"));
459        assert!(ntriples.contains("http://example.org/Person"));
460    }
461
462    #[test]
463    fn test_export_rdfxml_format_has_xml_structure() {
464        // Arrange
465        let graph = Graph::new().unwrap();
466        graph
467            .insert_turtle(
468                r#"
469            @prefix ex: <http://example.org/> .
470            ex:alice a ex:Person .
471        "#,
472            )
473            .unwrap();
474        let export = GraphExport::new(&graph);
475
476        // Act
477        let rdfxml = export.write_to_string(RdfFormat::RdfXml).unwrap();
478
479        // Assert - RDF/XML format should have XML structure
480        assert!(rdfxml.contains('<') && rdfxml.contains('>'));
481        assert!(rdfxml.contains("rdf:") || rdfxml.contains("RDF"));
482    }
483
484    #[test]
485    fn test_export_trig_format_supports_named_graphs() {
486        // Arrange
487        let graph = Graph::new().unwrap();
488        graph
489            .insert_turtle_in(
490                r#"
491            @prefix ex: <http://example.org/> .
492            ex:alice a ex:Person .
493        "#,
494                "http://example.org/graph1",
495            )
496            .unwrap();
497        let export = GraphExport::new(&graph);
498
499        // Act
500        let trig = export.write_to_string(RdfFormat::TriG).unwrap();
501
502        // Assert - TriG format should support named graphs
503        assert!(!trig.is_empty());
504        // TriG should contain graph information
505        assert!(trig.contains("http://example.org/graph1") || trig.contains("alice"));
506    }
507
508    #[test]
509    fn test_export_nquads_format_includes_graph_context() {
510        // Arrange
511        let graph = Graph::new().unwrap();
512        graph
513            .insert_turtle_in(
514                r#"
515            @prefix ex: <http://example.org/> .
516            ex:alice a ex:Person .
517        "#,
518                "http://example.org/graph1",
519            )
520            .unwrap();
521        let export = GraphExport::new(&graph);
522
523        // Act
524        let nquads = export.write_to_string(RdfFormat::NQuads).unwrap();
525
526        // Assert - N-Quads format should include graph context
527        assert!(!nquads.is_empty());
528        // N-Quads should contain graph information
529        assert!(nquads.contains("http://example.org/graph1") || nquads.contains("alice"));
530    }
531
532    #[test]
533    fn test_export_empty_graph() {
534        // Arrange
535        let graph = Graph::new().unwrap();
536        let export = GraphExport::new(&graph);
537
538        // Act
539        let result = export.write_to_string(RdfFormat::Turtle).unwrap();
540
541        // Assert
542        // Empty graph may produce empty string or minimal output
543        // Just verify it doesn't panic
544        assert!(result.is_empty() || !result.is_empty());
545    }
546}