rudof_lib 0.3.29

RDF and Knowledge Graphs processing tool
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use crate::{
    Result, Rudof,
    api::data::implementations::{
        add_triple, add_triples, begin_staging, commit_staging, dereference, list_endpoints, load_data,
        load_service_description, node_neighborhood, remove_triple, remove_triples, reset_data,
        reset_service_description, rollback_staging, serialize_data, serialize_service_description, show_node_info,
        staging, staging_depth, triples,
    },
    formats::{
        DataFormat, DataReaderMode, InputSpec, IriNormalizationMode, NodeInspectionMode, ResultDataFormat,
        ResultServiceFormat,
    },
    types::{NodeNeighborhood, StagingGuard, Triples},
};
use rudof_rdf::rdf_impl::EndpointStrategy;
use rudof_viz::VizEngine;
use std::io;

/// Operations for managing RDF data.
pub trait DataOperations {
    /// Loads RDF data from one or more input sources.
    ///
    /// # Arguments
    ///
    /// * `data` - Optional array of input specifications defining data sources (uses None by default)
    /// * `data_format` - The RDF format of the input data (uses default if None)
    /// * `base` - Optional base IRI for resolving relative IRIs (uses default if None)
    /// * `endpoint` - Optional SPARQL endpoint URL to load data from. If stablished it overrides data (uses None by default)
    /// * `reader_mode` - The parsing mode (uses default if None)
    /// * `endpoint_strategy` - How `endpoint` (if given) answers lookups: SPARQL queries
    ///   or HTTP dereferencing. Ignored when `endpoint` is `None`.
    ///
    /// # Errors
    ///
    /// Returns an error if the data cannot be parsed or loaded.
    #[allow(clippy::too_many_arguments)]
    fn load_data(
        &mut self,
        data: Option<&[InputSpec]>,
        data_format: Option<&DataFormat>,
        base: Option<&str>,
        endpoint: Option<&str>,
        reader_mode: Option<&DataReaderMode>,
        merge: Option<bool>,
        prefixes: Option<&[InputSpec]>,
        endpoint_strategy: EndpointStrategy,
    ) -> Result<()>;

    /// Serializes the current RDF data to a writer.
    ///
    /// # Arguments
    ///
    /// * `result_data_format` - Optional output format (uses default if None)
    /// * `viz_engine` - Optional visualization engine to use for image formats (SVG/PNG); uses
    ///   `VizEngine::PlantUml` if None. Ignored for non-image formats.
    /// * `writer` - The destination to write the serialized data to
    ///
    /// # Errors
    ///
    /// Returns an error if serialization fails.
    fn serialize_data<W: io::Write>(
        &mut self,
        result_data_format: Option<&ResultDataFormat>,
        viz_engine: Option<&VizEngine>,
        writer: &mut W,
    ) -> Result<()>;

    /// Resets the current data to an empty state.
    fn reset_data(&mut self);

    /// Loads a SPARQL service description from an input specification.
    ///
    /// # Arguments
    ///
    /// * `service` - Input specification defining the service description source
    /// * `data_format` - Optional format (uses default if None)
    /// * `reader_mode` - Optional parsing mode (uses default if None)
    /// * `base` - Optional base IRI for resolving relative IRIs in the service description (uses default if None)
    ///
    /// # Errors
    ///
    /// Returns an error if the service description cannot be parsed or loaded.
    fn load_service_description(
        &mut self,
        service: &InputSpec,
        data_format: Option<&DataFormat>,
        reader_mode: Option<&DataReaderMode>,
        base: Option<&str>,
    ) -> Result<()>;

    /// Serializes the current service description to a writer.
    ///
    /// # Arguments
    ///
    /// * `result_service_format` - Optional output format for the service description (uses default if None)
    /// * `writer` - The destination to write the serialized service description to
    ///
    /// # Errors
    ///
    /// Returns an error if no service description is loaded or serialization fails.
    fn serialize_service_description<W: io::Write>(
        &self,
        result_service_format: Option<&ResultServiceFormat>,
        writer: &mut W,
    ) -> Result<()>;

    /// Resets the current service description.
    fn reset_service_description(&mut self);

    /// Shows detailed information about a node in the current RDF data.
    ///
    /// # Arguments
    ///
    /// * `node` - Node identifier (IRI or prefixed name) to inspect
    /// * `predicates` - Optional list of predicates used to filter displayed relations
    /// * `show_node_mode` - Optional inspection mode controlling the level of detail (uses default if None)
    /// * `depth` - Optional maximum traversal depth when expanding related nodes (uses 1 by default)
    /// * `show_hyperlinks` - Whether hyperlinks should be included in the output (uses false by default)
    /// * `show_colors` - Whether colored output should be used (uses false by default)
    /// * `iri_mode` - IRI normalization mode to apply when parsing the node identifier
    /// * `writer` - The destination to write the node information to
    ///
    /// # Errors
    ///
    /// Returns an error if the node information cannot be retrieved or serialized.
    fn show_node_info<W: io::Write>(
        &mut self,
        node: &str,
        predicates: Option<&[String]>,
        show_node_mode: Option<&NodeInspectionMode>,
        depth: Option<usize>,
        show_hyperlinks: Option<bool>,
        show_colors: Option<bool>,
        iri_mode: IriNormalizationMode,
        writer: &mut W,
    ) -> Result<()>;

    /// Returns a lazy iterator over the neighborhood of every node matched by `node`
    ///
    /// # Arguments
    ///
    /// * `node` - Node identifier (IRI, prefixed name, or blank node) whose neighborhood is traversed
    /// * `predicates` - Optional list of predicates; when given, only arcs with these predicates are followed
    /// * `mode - Optional inspection mode selecting the arc directions
    /// * `depth`- Optional maximum transversal depth (default is 1)
    /// * `iri_mode` - IRI normalization mode to apply when parsing the node identifier
    ///
    /// # Errors
    ///
    /// Returns an error if no RDF data is loaded or the node selector or predicates can´t be resolved.
    fn node_neighborhood<'a>(
        &'a self,
        node: &str,
        predicates: Option<&[String]>,
        mode: Option<&NodeInspectionMode>,
        depth: Option<usize>,
        iri_mode: IriNormalizationMode,
    ) -> Result<NodeNeighborhood<'a>>;

    /// Adds a triple to the current RDF data.
    ///
    /// # Arguments
    ///
    /// * `subject` - The subject, as an IRI (`<http://example.org/alice>`, `ex:alice`)
    ///   or a blank node (`_:b1`)
    /// * `predicate` - The predicate, as an angle-bracketed IRI or a prefixed name
    /// * `object` - The object, as an IRI, a blank node or a literal (`"Alice"`,
    ///   `"Alice"@en`, `23`, `"23"^^xsd:integer`)
    /// * `iri_mode` - IRI normalization mode to apply when parsing the terms
    ///
    /// Prefixed names are resolved against the prefixes of the loaded data,
    /// supplemented by the session's default prefixes. Adding a triple the data
    /// already contains changes nothing, an RDF graph being a set of triples.
    ///
    /// # Errors
    ///
    /// Returns an error if no RDF data is loaded, or if a term cannot be parsed or
    /// its prefix resolved.
    ///
    /// Also if the data cannot be modified: only the in-memory graph can be. A SPARQL
    /// endpoint and the QLever backend are read-only, and so is data federated with
    /// SPARQL endpoints — the local graph of such a session is deliberately not
    /// written to instead, since [`triples`](Self::triples) reads it and the
    /// endpoints' as one.
    fn add_triple(
        &mut self,
        subject: &str,
        predicate: &str,
        object: &str,
        iri_mode: IriNormalizationMode,
    ) -> Result<()>;

    /// Removes a triple from the current RDF data.
    ///
    /// # Arguments
    ///
    /// As [`add_triple`](Self::add_triple).
    ///
    /// # Errors
    ///
    /// As [`add_triple`](Self::add_triple).
    fn remove_triple(
        &mut self,
        subject: &str,
        predicate: &str,
        object: &str,
        iri_mode: IriNormalizationMode,
    ) -> Result<()>;

    /// Adds several triples to the current RDF data in one operation.
    ///
    /// # Arguments
    ///
    /// * `triples` - The triples to add, each one written as in
    ///   [`add_triple`](Self::add_triple)
    /// * `iri_mode` - As [`add_triple`](Self::add_triple)
    ///
    /// Every triple is parsed before any of them is added, so a batch holding a triple
    /// that cannot be parsed changes nothing at all.
    ///
    /// # Errors
    ///
    /// As [`add_triple`](Self::add_triple), for the first triple that cannot be parsed.
    fn add_triples(&mut self, triples: &[(&str, &str, &str)], iri_mode: IriNormalizationMode) -> Result<()>;

    /// Removes several triples from the current RDF data in one operation.
    ///
    /// # Arguments
    ///
    /// As [`add_triples`](Self::add_triples).
    ///
    /// # Errors
    ///
    /// As [`add_triples`](Self::add_triples).
    fn remove_triples(&mut self, triples: &[(&str, &str, &str)], iri_mode: IriNormalizationMode) -> Result<()>;

    /// Opens a staging frame over the loaded RDF data, so that the changes made from
    /// now on can be kept with [`commit_staging`](Self::commit_staging) or discarded
    /// with [`rollback_staging`](Self::rollback_staging).
    ///
    /// Returns the new staging depth: frames nest, and the innermost one is the one a
    /// commit or a rollback closes.
    ///
    /// # What is staged, and what is not
    ///
    /// The loaded **data**, and nothing else. Loaded schemas, shapemaps, prefixes and
    /// configuration are session state. What a rollback does clear is the state computed
    /// *from* the data it discards: the SHACL and ShEx validation results,
    /// the query results and the loaded SPARQL query.
    ///
    /// # Cost
    ///
    /// Rolling back costs what was staged, not the size of the graph: each triple
    /// added or removed in the frame is remembered so it can be undone. A command
    /// that cannot be undone triple by triple ([`load_data`](Self::load_data),
    /// `dereference`, [`reset_data`](Self::reset_data)) instead makes the frame
    /// remember the data as a whole.
    ///
    /// Remembering it is cheap to do and not cheap to keep: the graph is shared with
    /// the frame rather than copied, and the next write to it copies it once, so a
    /// load inside a frame leaves the graph resident twice until the frame closes.
    /// One frame pays that once however many such commands it runs, but nested frames
    /// pay it once each. A large graph is therefore better staged as triple deltas
    /// with [`add_triples`](Self::add_triples) /
    /// [`remove_triples`](Self::remove_triples), with the loads left outside the
    /// frame.
    ///
    /// # Errors
    ///
    /// Returns an error if no RDF data is loaded, or if the loaded data cannot be
    /// modified, as [`add_triple`](Self::add_triple) does.
    fn begin_staging(&mut self) -> Result<usize>;

    /// Keeps the changes staged in the innermost open frame, closing it.
    ///
    /// A frame nested in another hands its changes over to the enclosing frame, so
    /// rolling that one back still undoes them. Committing the outermost frame makes
    /// them final.
    ///
    /// # Errors
    ///
    /// Returns [`DataError::NoStagingFrame`](crate::errors::DataError::NoStagingFrame)
    /// if no frame is open.
    fn commit_staging(&mut self) -> Result<()>;

    /// Discards the changes staged in the innermost open frame, closing it and
    /// putting the loaded data back as it was when the frame was opened.
    ///
    /// See [`begin_staging`](Self::begin_staging) for what is put back and what is
    /// cleared.
    ///
    /// # Errors
    ///
    /// Returns [`DataError::NoStagingFrame`](crate::errors::DataError::NoStagingFrame)
    /// if no frame is open, or
    /// [`DataError::FailedStagingRollback`](crate::errors::DataError::FailedStagingRollback)
    /// if the data could not be put back, in which case the frame is closed all the
    /// same and the data may be left part-way.
    fn rollback_staging(&mut self) -> Result<()>;

    /// How many staging frames are open, zero when nothing is staged.
    fn staging_depth(&self) -> usize;

    /// Opens a staging frame as [`begin_staging`](Self::begin_staging) does, and
    /// returns a guard that closes it: dropping the guard rolls the frame back unless
    /// it was committed.
    ///
    /// # Errors
    ///
    /// As [`begin_staging`](Self::begin_staging).
    fn staging(&mut self) -> Result<StagingGuard<'_>>;

    /// Returns an iterator over the triples of the current RDF data matching a
    /// pattern.
    ///
    /// # Arguments
    ///
    /// * `subject` - The subject to match, as in [`add_triple`](Self::add_triple);
    ///   `None` matches any subject
    /// * `predicate` - The predicate to match; `None` matches any predicate
    /// * `object` - The object to match; `None` matches any object
    /// * `iri_mode` - IRI normalization mode to apply when parsing the terms
    ///
    /// All three `None` walks the whole graph. The iterator borrows the data, which
    /// therefore cannot be modified while its triples are being walked.
    ///
    /// # Errors
    ///
    /// Returns an error if no RDF data is loaded, or if a term of the pattern cannot
    /// be parsed or its prefix resolved.
    ///
    /// # Note
    ///
    /// The triples are retrieved before the iterator is returned, and a pattern with
    /// a SPARQL endpoint or the QLever backend as the data retrieves them from there:
    /// an unconstrained pattern then pulls the whole remote graph.
    fn triples<'a>(
        &'a self,
        subject: Option<&str>,
        predicate: Option<&str>,
        object: Option<&str>,
        iri_mode: IriNormalizationMode,
    ) -> Result<Triples<'a>>;

    /// Lists the registered SPARQL endpoints.
    ///
    /// Returns:
    ///     List of (name, url) tuples for known endpoints.
    fn list_endpoints(&mut self) -> Result<Vec<(String, String)>>;

    /// Dereferences `uri` over HTTP(S) and merges the resulting RDF data.
    ///
    /// Sends a GET request content-negotiating for an RDF serialization
    /// (`text/turtle`, `application/rdf+xml`, `application/ld+json`, ...),
    /// following redirects, and parses the response body using the format
    /// indicated by its `Content-Type` header (falling back to Turtle if the
    /// header is missing or unrecognized).
    ///
    /// # Arguments
    ///
    /// * `uri` - The absolute IRI to dereference
    /// * `reader_mode` - The parsing mode (uses default if None)
    /// * `merge` - Whether to merge with existing data or replace it (defaults to true)
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails, the response status is not
    /// successful, or the body cannot be parsed as RDF.
    fn dereference(&mut self, uri: &str, reader_mode: Option<&DataReaderMode>, merge: Option<bool>) -> Result<()>;
}

impl DataOperations for Rudof {
    fn load_data(
        &mut self,
        data: Option<&[InputSpec]>,
        data_format: Option<&DataFormat>,
        base: Option<&str>,
        endpoint: Option<&str>,
        reader_mode: Option<&DataReaderMode>,
        merge: Option<bool>,
        prefixes: Option<&[InputSpec]>,
        endpoint_strategy: EndpointStrategy,
    ) -> Result<()> {
        load_data(
            self,
            data,
            data_format,
            base,
            endpoint,
            reader_mode,
            merge,
            prefixes,
            endpoint_strategy,
        )
    }

    fn serialize_data<W: io::Write>(
        &mut self,
        result_data_format: Option<&ResultDataFormat>,
        viz_engine: Option<&VizEngine>,
        writer: &mut W,
    ) -> Result<()> {
        serialize_data(self, result_data_format, viz_engine, writer)
    }

    fn reset_data(&mut self) {
        reset_data(self)
    }

    fn load_service_description(
        &mut self,
        service: &InputSpec,
        data_format: Option<&DataFormat>,
        reader_mode: Option<&DataReaderMode>,
        base: Option<&str>,
    ) -> Result<()> {
        load_service_description(self, service, data_format, reader_mode, base)
    }

    fn serialize_service_description<W: io::Write>(
        &self,
        result_service_format: Option<&ResultServiceFormat>,
        writer: &mut W,
    ) -> Result<()> {
        serialize_service_description(self, result_service_format, writer)
    }

    fn reset_service_description(&mut self) {
        reset_service_description(self)
    }

    fn show_node_info<W: io::Write>(
        &mut self,
        node: &str,
        predicates: Option<&[String]>,
        show_node_mode: Option<&NodeInspectionMode>,
        depth: Option<usize>,
        show_hyperlinks: Option<bool>,
        show_colors: Option<bool>,
        iri_mode: IriNormalizationMode,
        writer: &mut W,
    ) -> Result<()> {
        show_node_info(
            self,
            node,
            predicates,
            show_node_mode,
            depth,
            show_hyperlinks,
            show_colors,
            iri_mode,
            writer,
        )
    }

    fn node_neighborhood<'a>(
        &'a self,
        node: &str,
        predicates: Option<&[String]>,
        mode: Option<&NodeInspectionMode>,
        depth: Option<usize>,
        iri_mode: IriNormalizationMode,
    ) -> Result<NodeNeighborhood<'a>> {
        node_neighborhood(self, node, predicates, mode, depth, iri_mode)
    }

    fn add_triple(
        &mut self,
        subject: &str,
        predicate: &str,
        object: &str,
        iri_mode: IriNormalizationMode,
    ) -> Result<()> {
        add_triple(self, subject, predicate, object, iri_mode)
    }

    fn remove_triple(
        &mut self,
        subject: &str,
        predicate: &str,
        object: &str,
        iri_mode: IriNormalizationMode,
    ) -> Result<()> {
        remove_triple(self, subject, predicate, object, iri_mode)
    }

    fn add_triples(&mut self, triples: &[(&str, &str, &str)], iri_mode: IriNormalizationMode) -> Result<()> {
        add_triples(self, triples, iri_mode)
    }

    fn remove_triples(&mut self, triples: &[(&str, &str, &str)], iri_mode: IriNormalizationMode) -> Result<()> {
        remove_triples(self, triples, iri_mode)
    }

    fn begin_staging(&mut self) -> Result<usize> {
        begin_staging(self)
    }

    fn commit_staging(&mut self) -> Result<()> {
        commit_staging(self)
    }

    fn rollback_staging(&mut self) -> Result<()> {
        rollback_staging(self)
    }

    fn staging_depth(&self) -> usize {
        staging_depth(self)
    }

    fn staging(&mut self) -> Result<StagingGuard<'_>> {
        staging(self)
    }

    fn triples<'a>(
        &'a self,
        subject: Option<&str>,
        predicate: Option<&str>,
        object: Option<&str>,
        iri_mode: IriNormalizationMode,
    ) -> Result<Triples<'a>> {
        triples(self, subject, predicate, object, iri_mode)
    }

    fn list_endpoints(&mut self) -> Result<Vec<(String, String)>> {
        list_endpoints(self)
    }

    fn dereference(&mut self, uri: &str, reader_mode: Option<&DataReaderMode>, merge: Option<bool>) -> Result<()> {
        dereference(self, uri, reader_mode, merge)
    }
}