ggen_core/graph/
export.rs1use 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
23pub struct GraphExport<'a> {
72 graph: &'a Graph,
73}
74
75impl<'a> GraphExport<'a> {
76 pub fn new(graph: &'a Graph) -> Self {
78 Self { graph }
79 }
80
81 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 pub fn write_to_writer<W: Write>(&self, mut writer: W, format: RdfFormat) -> Result<()> {
111 use oxigraph::model::GraphName;
112
113 match format {
116 RdfFormat::Turtle | RdfFormat::NTriples | RdfFormat::RdfXml => {
117 let mut serializer = RdfSerializer::from_format(format).for_writer(&mut writer);
120
121 let default_graph_quads = self.graph.quads_for_pattern(
123 None, None, None, Some(&GraphName::DefaultGraph), )?;
128
129 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 serializer.finish().map_err(|e| {
138 Error::new(&format!("Failed to finish RDF serialization: {}", e))
139 })?;
140 }
141 RdfFormat::TriG | RdfFormat::NQuads => {
142 let serializer = RdfSerializer::from_format(format);
144 self.graph.inner().dump_to_writer(serializer, &mut writer)?;
145 }
146 _ => {
147 let serializer = RdfSerializer::from_format(format);
149 self.graph.inner().dump_to_writer(serializer, &mut writer)?;
150 }
151 }
152 Ok(())
153 }
154
155 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 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 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 export.write_to_file(&file_path, RdfFormat::Turtle).unwrap();
242
243 assert!(file_path.exists());
245 let content = fs::read_to_string(&file_path).unwrap();
246 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 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 let result = export.write_to_string(RdfFormat::Turtle).unwrap();
268
269 assert!(!result.is_empty());
271 assert!(result.contains("ex:") || result.contains("http://example.org/"));
273 }
274
275 #[test]
276 fn test_export_write_to_string_ntriples() {
277 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 let result = export.write_to_string(RdfFormat::NTriples).unwrap();
291
292 assert!(!result.is_empty());
294 assert!(result.contains("http://example.org/alice"));
296 }
297
298 #[test]
299 fn test_export_write_to_string_rdfxml() {
300 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 let result = export.write_to_string(RdfFormat::RdfXml).unwrap();
314
315 assert!(!result.is_empty());
317 assert!(result.contains('<') && result.contains('>'));
319 }
320
321 #[test]
322 fn test_export_write_to_file_auto_turtle() {
323 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 export.write_to_file_auto(&file_path).unwrap();
339
340 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 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 export.write_to_file_auto(&file_path).unwrap();
364
365 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 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 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 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 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!(!turtle.is_empty());
408 assert!(!ntriples.is_empty());
409 assert!(!rdfxml.is_empty());
410 assert!(!trig.is_empty());
411 assert!(!nquads.is_empty());
412 assert!(turtle != ntriples || turtle != rdfxml || ntriples != rdfxml);
414 }
415
416 #[test]
417 fn test_export_turtle_format_preserves_prefixes() {
418 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 let turtle = export.write_to_string(RdfFormat::Turtle).unwrap();
434
435 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 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 let ntriples = export.write_to_string(RdfFormat::NTriples).unwrap();
456
457 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 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 let rdfxml = export.write_to_string(RdfFormat::RdfXml).unwrap();
478
479 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 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 let trig = export.write_to_string(RdfFormat::TriG).unwrap();
501
502 assert!(!trig.is_empty());
504 assert!(trig.contains("http://example.org/graph1") || trig.contains("alice"));
506 }
507
508 #[test]
509 fn test_export_nquads_format_includes_graph_context() {
510 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 let nquads = export.write_to_string(RdfFormat::NQuads).unwrap();
525
526 assert!(!nquads.is_empty());
528 assert!(nquads.contains("http://example.org/graph1") || nquads.contains("alice"));
530 }
531
532 #[test]
533 fn test_export_empty_graph() {
534 let graph = Graph::new().unwrap();
536 let export = GraphExport::new(&graph);
537
538 let result = export.write_to_string(RdfFormat::Turtle).unwrap();
540
541 assert!(result.is_empty() || !result.is_empty());
545 }
546}