oxiland 0.7.0

Embedded RDF datasets, SPARQL, persistence, and streaming I/O for Rust
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
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! SPARQL query, update, streaming results, and result serialization.
//!
//! See ADR-009–ADR-012 and `docs/design/0.3-query-api.md`.

use std::fmt;
use std::io::Write;

use oxigraph::model::{GraphName, NamedOrBlankNode};
use oxigraph::sparql::results::{QueryResultsFormat, QueryResultsSerializer};
use oxigraph::sparql::{
    CancellationToken, PreparedSparqlQuery, QuerySolutionIter, QueryTripleIter, SparqlEvaluator,
};
use spargebra::algebra::GraphPattern;
use spargebra::{Query as SparqlAlgebraQuery, SparqlParser};

use crate::io::Serializer;
use crate::{Error, Model, Result};

/// Results returned by a SPARQL query (ADR-010).
///
/// Wraps Oxigraph iterators. [`Debug`] prints the variant without draining
/// streaming results.
pub enum QueryResults<'a> {
    /// ASK result.
    Boolean(bool),
    /// SELECT solution stream.
    Solutions(QuerySolutionIter<'a>),
    /// CONSTRUCT / DESCRIBE triple stream.
    Graph(QueryTripleIter<'a>),
}

impl fmt::Debug for QueryResults<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Boolean(value) => f.debug_tuple("Boolean").field(value).finish(),
            Self::Solutions(_) => f.write_str("Solutions(..)"),
            Self::Graph(_) => f.write_str("Graph(..)"),
        }
    }
}

fn map_query_results(results: oxigraph::sparql::QueryResults<'_>) -> QueryResults<'_> {
    match results {
        oxigraph::sparql::QueryResults::Boolean(value) => QueryResults::Boolean(value),
        oxigraph::sparql::QueryResults::Solutions(solutions) => QueryResults::Solutions(solutions),
        oxigraph::sparql::QueryResults::Graph(graph) => QueryResults::Graph(graph),
    }
}

/// Dataset configuration applied at execute time (ADR-009).
#[derive(Clone, Debug, Default)]
struct DatasetConfig {
    default_graphs: Option<Vec<GraphName>>,
    default_as_union: bool,
    named_graphs: Option<Vec<NamedOrBlankNode>>,
}

impl DatasetConfig {
    fn is_configured(&self) -> bool {
        self.default_as_union || self.default_graphs.is_some() || self.named_graphs.is_some()
    }
}

/// A SPARQL query configured before execution (ADR-009).
///
/// # Examples
///
/// ASK:
///
/// ```
/// use oxiland::terms::{self, Literal, Triple};
/// use oxiland::{Model, Query, QueryResults};
///
/// # fn main() -> oxiland::Result<()> {
/// let model = Model::new()?;
/// model.add(Triple::new(
///     terms::named_node("https://example.com/alice")?,
///     terms::named_node("https://example.com/name")?,
///     Literal::new_simple_literal("Alice"),
/// ))?;
///
/// let results = Query::new("ASK { ?s ?p ?o }").execute(&model)?;
/// assert!(matches!(results, QueryResults::Boolean(true)));
/// # Ok(())
/// # }
/// ```
///
/// SELECT with limit:
///
/// ```
/// use oxiland::terms::{self, Literal, Triple};
/// use oxiland::{Model, Query, QueryResults};
///
/// # fn main() -> oxiland::Result<()> {
/// let model = Model::new()?;
/// model.add(Triple::new(
///     terms::named_node("https://example.com/alice")?,
///     terms::named_node("https://example.com/name")?,
///     Literal::new_simple_literal("Alice"),
/// ))?;
///
/// let results = Query::new(
///     "SELECT ?name WHERE { <https://example.com/alice> <https://example.com/name> ?name }",
/// )
/// .limit(1)?
/// .execute(&model)?;
///
/// if let QueryResults::Solutions(mut solutions) = results {
///     let solution = solutions
///         .next()
///         .expect("one row")
///         .map_err(|error| oxiland::Error::SparqlEvaluation(error.to_string()))?;
///     assert!(solution.get("name").is_some());
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Query {
    text: String,
    base_iri: Option<String>,
    prefixes: Vec<(String, String)>,
    limit: Option<usize>,
    offset: usize,
    dataset: DatasetConfig,
    cancellation: Option<CancellationToken>,
}

impl Query {
    /// Creates a SPARQL query from its text.
    #[must_use]
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            base_iri: None,
            prefixes: Vec::new(),
            limit: None,
            offset: 0,
            dataset: DatasetConfig::default(),
            cancellation: None,
        }
    }

    /// Returns the query text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Sets the base IRI used while parsing the query.
    ///
    /// Invalid IRIs return [`Error::InvalidRdf`].
    pub fn base_iri(mut self, base_iri: impl Into<String>) -> Result<Self> {
        let base_iri = base_iri.into();
        let _ = SparqlParser::new()
            .with_base_iri(&base_iri)
            .map_err(|error| Error::InvalidRdf(error.to_string()))?;
        self.base_iri = Some(base_iri);
        Ok(self)
    }

    /// Adds a default IRI prefix used while parsing the query.
    ///
    /// Invalid IRIs return [`Error::InvalidRdf`].
    pub fn prefix(
        mut self,
        prefix_name: impl Into<String>,
        prefix_iri: impl Into<String>,
    ) -> Result<Self> {
        let prefix_name = prefix_name.into();
        let prefix_iri = prefix_iri.into();
        let _ = SparqlParser::new()
            .with_prefix(&prefix_name, &prefix_iri)
            .map_err(|error| Error::InvalidRdf(error.to_string()))?;
        self.prefixes.push((prefix_name, prefix_iri));
        Ok(self)
    }

    /// Sets an API-level result limit (algebra `Slice`; ADR-009).
    ///
    /// Replaces any in-query `LIMIT`/`OFFSET` slice on SELECT/CONSTRUCT/DESCRIBE.
    /// ASK queries return [`Error::Unsupported`] here (not only at execute).
    pub fn limit(mut self, limit: usize) -> Result<Self> {
        self.ensure_not_ask_for_slice()?;
        self.limit = Some(limit);
        Ok(self)
    }

    /// Sets an API-level result offset (algebra `Slice`; ADR-009).
    ///
    /// Replaces any in-query `LIMIT`/`OFFSET` slice on SELECT/CONSTRUCT/DESCRIBE.
    /// ASK queries return [`Error::Unsupported`] here (not only at execute).
    pub fn offset(mut self, offset: usize) -> Result<Self> {
        self.ensure_not_ask_for_slice()?;
        self.offset = offset;
        Ok(self)
    }

    /// Restricts the query default graph to the given graph names.
    ///
    /// An empty list selects an empty default dataset (no triples match from
    /// the default graph).
    #[must_use]
    pub fn default_graph(mut self, graphs: impl IntoIterator<Item = GraphName>) -> Self {
        self.dataset.default_graphs = Some(graphs.into_iter().collect());
        self.dataset.default_as_union = false;
        self
    }

    /// Treats the union of all named graphs as the default graph.
    #[must_use]
    pub fn default_graph_as_union(mut self) -> Self {
        self.dataset.default_as_union = true;
        self.dataset.default_graphs = None;
        self
    }

    /// Restricts available named graphs for the query dataset.
    #[must_use]
    pub fn available_named_graphs(
        mut self,
        graphs: impl IntoIterator<Item = NamedOrBlankNode>,
    ) -> Self {
        self.dataset.named_graphs = Some(graphs.into_iter().collect());
        self
    }

    /// Attaches a cooperative cancellation token (ADR-012).
    ///
    /// Wall-clock timeouts are caller-driven: cancel the token from another
    /// thread when a deadline expires.
    #[must_use]
    pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
        self.cancellation = Some(token);
        self
    }

    /// Parses and executes the query against a model.
    ///
    /// Parse failures return [`Error::SparqlParse`]. Evaluation failures return
    /// [`Error::SparqlEvaluation`]. Invalid configured base/prefix IRIs return
    /// [`Error::InvalidRdf`].
    pub fn execute<'a>(&self, model: &'a Model) -> Result<QueryResults<'a>> {
        let prepared = self.prepare()?;
        model.with_read_lock(|| {
            let results = prepared
                .on_store(model.store())
                .execute()
                .map_err(|error| Error::SparqlEvaluation(error.to_string()))?;
            Ok(map_query_results(results))
        })
    }

    fn ensure_not_ask_for_slice(&self) -> Result<()> {
        if looks_like_ask_query(&self.text) {
            return Err(Error::Unsupported(
                "API-level limit/offset cannot be applied to ASK queries; put LIMIT in the query text if needed"
                    .into(),
            ));
        }
        Ok(())
    }

    fn prepare(&self) -> Result<PreparedSparqlQuery> {
        let mut parser = SparqlParser::new();
        if let Some(base_iri) = &self.base_iri {
            parser = parser
                .with_base_iri(base_iri)
                .map_err(|error| Error::InvalidRdf(error.to_string()))?;
        }
        for (name, iri) in &self.prefixes {
            parser = parser
                .with_prefix(name, iri)
                .map_err(|error| Error::InvalidRdf(error.to_string()))?;
        }
        let mut algebra = parser
            .parse_query(&self.text)
            .map_err(|error| Error::SparqlParse(error.to_string()))?;
        algebra = apply_slice(algebra, self.offset, self.limit)?;

        let mut evaluator = SparqlEvaluator::new();
        if let Some(token) = &self.cancellation {
            evaluator = evaluator.with_cancellation_token(token.clone());
        }
        let mut prepared = evaluator.for_query(algebra);
        apply_dataset(prepared.dataset_mut(), &self.dataset);
        Ok(prepared)
    }
}

/// A SPARQL Update operation configured before execution (ADR-009).
#[derive(Clone)]
pub struct Update {
    text: String,
    base_iri: Option<String>,
    prefixes: Vec<(String, String)>,
    dataset: DatasetConfig,
    cancellation: Option<CancellationToken>,
}

impl Update {
    /// Creates a SPARQL Update from its text.
    #[must_use]
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            base_iri: None,
            prefixes: Vec::new(),
            dataset: DatasetConfig::default(),
            cancellation: None,
        }
    }

    /// Returns the update text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Sets the base IRI used while parsing the update.
    ///
    /// Invalid IRIs return [`Error::InvalidRdf`].
    pub fn base_iri(mut self, base_iri: impl Into<String>) -> Result<Self> {
        let base_iri = base_iri.into();
        let _ = SparqlParser::new()
            .with_base_iri(&base_iri)
            .map_err(|error| Error::InvalidRdf(error.to_string()))?;
        self.base_iri = Some(base_iri);
        Ok(self)
    }

    /// Adds a default IRI prefix used while parsing the update.
    ///
    /// Invalid IRIs return [`Error::InvalidRdf`].
    pub fn prefix(
        mut self,
        prefix_name: impl Into<String>,
        prefix_iri: impl Into<String>,
    ) -> Result<Self> {
        let prefix_name = prefix_name.into();
        let prefix_iri = prefix_iri.into();
        let _ = SparqlParser::new()
            .with_prefix(&prefix_name, &prefix_iri)
            .map_err(|error| Error::InvalidRdf(error.to_string()))?;
        self.prefixes.push((prefix_name, prefix_iri));
        Ok(self)
    }

    /// Restricts USING-style dataset default graphs when applicable.
    ///
    /// Only SPARQL Update operations that expose USING datasets (for example
    /// `DELETE/INSERT`) honor this. `INSERT DATA` / `DELETE DATA` return
    /// [`Error::Unsupported`] at execute time if dataset configuration is set.
    #[must_use]
    pub fn default_graph(mut self, graphs: impl IntoIterator<Item = GraphName>) -> Self {
        self.dataset.default_graphs = Some(graphs.into_iter().collect());
        self.dataset.default_as_union = false;
        self
    }

    /// Treats the union of named graphs as the default graph for USING datasets.
    #[must_use]
    pub fn default_graph_as_union(mut self) -> Self {
        self.dataset.default_as_union = true;
        self.dataset.default_graphs = None;
        self
    }

    /// Attaches a cooperative cancellation token (ADR-012).
    #[must_use]
    pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
        self.cancellation = Some(token);
        self
    }

    /// Parses and executes the update against a model.
    ///
    /// Execution holds the model write lock. On Fjall-backed models, the durable
    /// copy is resynced after a successful update with compensated
    /// inserts/deletes so a mid-sync failure restores the pre-update on-disk
    /// key set; memory is then reloaded from that snapshot.
    pub fn execute(self, model: &Model) -> Result<()> {
        let mut evaluator = SparqlEvaluator::new();
        if let Some(base_iri) = &self.base_iri {
            evaluator = evaluator
                .with_base_iri(base_iri)
                .map_err(|error| Error::InvalidRdf(error.to_string()))?;
        }
        for (name, iri) in &self.prefixes {
            evaluator = evaluator
                .with_prefix(name, iri)
                .map_err(|error| Error::InvalidRdf(error.to_string()))?;
        }
        if let Some(token) = &self.cancellation {
            evaluator = evaluator.with_cancellation_token(token.clone());
        }
        let mut prepared = evaluator
            .parse_update(&self.text)
            .map_err(|error| Error::SparqlParse(error.to_string()))?;

        let mut applied_dataset = false;
        for dataset in prepared.using_datasets_mut() {
            apply_dataset(dataset, &self.dataset);
            applied_dataset = true;
        }
        if self.dataset.is_configured() && !applied_dataset {
            return Err(Error::Unsupported(
                "Update dataset configuration requires DELETE/INSERT operations that expose USING datasets; INSERT DATA and DELETE DATA do not accept dataset overrides"
                    .into(),
            ));
        }

        model.run_sparql_update(|store| {
            prepared
                .on_store(store)
                .execute()
                .map_err(|error| Error::SparqlEvaluation(error.to_string()))
        })
    }
}

/// Closed set of SPARQL Query Results formats (ADR-011).
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ResultsFormat {
    /// SPARQL Results XML.
    Xml,
    /// SPARQL Results JSON.
    Json,
    /// SPARQL Results CSV.
    Csv,
    /// SPARQL Results TSV.
    Tsv,
}

impl ResultsFormat {
    /// Canonical short name.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Xml => "xml",
            Self::Json => "json",
            Self::Csv => "csv",
            Self::Tsv => "tsv",
        }
    }

    /// Canonical media type.
    #[must_use]
    pub const fn media_type(self) -> &'static str {
        match self {
            Self::Xml => "application/sparql-results+xml",
            Self::Json => "application/sparql-results+json",
            Self::Csv => "text/csv",
            Self::Tsv => "text/tab-separated-values",
        }
    }

    /// Resolves a format name or common alias.
    pub fn from_name(name: &str) -> Result<Self> {
        match name.trim().to_ascii_lowercase().as_str() {
            "xml" | "sparql-results+xml" => Ok(Self::Xml),
            "json" | "sparql-results+json" => Ok(Self::Json),
            "csv" => Ok(Self::Csv),
            "tsv" | "tab-separated-values" => Ok(Self::Tsv),
            other => Err(Error::Unsupported(format!(
                "SPARQL results format '{other}' is not supported"
            ))),
        }
    }

    /// Resolves a media type (parameters ignored).
    pub fn from_media_type(media_type: &str) -> Result<Self> {
        let base = media_type
            .split(';')
            .next()
            .unwrap_or(media_type)
            .trim()
            .to_ascii_lowercase();
        match base.as_str() {
            "application/sparql-results+xml" => Ok(Self::Xml),
            "application/sparql-results+json" => Ok(Self::Json),
            "text/csv" => Ok(Self::Csv),
            "text/tab-separated-values" | "text/tsv" => Ok(Self::Tsv),
            other => Err(Error::Unsupported(format!(
                "SPARQL results media type '{other}' is not supported"
            ))),
        }
    }

    fn to_oxigraph(self) -> QueryResultsFormat {
        match self {
            Self::Xml => QueryResultsFormat::Xml,
            Self::Json => QueryResultsFormat::Json,
            Self::Csv => QueryResultsFormat::Csv,
            Self::Tsv => QueryResultsFormat::Tsv,
        }
    }
}

/// Serializes ASK or SELECT [`QueryResults`] to a writer.
///
/// Graph results are not SPARQL Results documents—use
/// [`serialize_graph_results_to_writer`].
pub fn serialize_query_results_to_writer<W: Write>(
    results: QueryResults<'_>,
    format: ResultsFormat,
    writer: W,
) -> Result<W> {
    let serializer = QueryResultsSerializer::from_format(format.to_oxigraph());
    match results {
        QueryResults::Boolean(value) => serializer
            .serialize_boolean_to_writer(writer, value)
            .map_err(|error| Error::Serialize(error.to_string())),
        QueryResults::Solutions(mut solutions) => {
            let variables = solutions.variables().to_vec();
            let mut solutions_writer = serializer
                .serialize_solutions_to_writer(writer, variables)
                .map_err(|error| Error::Serialize(error.to_string()))?;
            for solution in solutions.by_ref() {
                let solution =
                    solution.map_err(|error| Error::SparqlEvaluation(error.to_string()))?;
                solutions_writer
                    .serialize(&solution)
                    .map_err(|error| Error::Serialize(error.to_string()))?;
            }
            solutions_writer
                .finish()
                .map_err(|error| Error::Serialize(error.to_string()))
        }
        QueryResults::Graph(_) => Err(Error::Unsupported(
            "graph query results must be serialized with serialize_graph_results_to_writer / oxiland::io::Serializer, not ResultsFormat"
                .into(),
        )),
    }
}

/// Serializes ASK or SELECT [`QueryResults`] to a UTF-8 string.
pub fn serialize_query_results_to_string(
    results: QueryResults<'_>,
    format: ResultsFormat,
) -> Result<String> {
    let buffer = serialize_query_results_to_writer(results, format, Vec::new())?;
    String::from_utf8(buffer).map_err(|error| Error::Serialize(error.to_string()))
}

/// Serializes CONSTRUCT/DESCRIBE [`QueryResults::Graph`] with an RDF
/// [`Serializer`].
///
/// Triples are written as they are produced; the helper does not buffer the
/// full graph. Evaluation errors from the graph iterator map to
/// [`Error::SparqlEvaluation`].
pub fn serialize_graph_results_to_writer<W: Write>(
    results: QueryResults<'_>,
    serializer: &Serializer,
    writer: W,
) -> Result<W> {
    let QueryResults::Graph(graph) = results else {
        return Err(Error::Unsupported(
            "serialize_graph_results_to_writer requires QueryResults::Graph".into(),
        ));
    };
    serializer.serialize_triples_fallible_to_writer(
        writer,
        graph.map(|triple| triple.map_err(|error| Error::SparqlEvaluation(error.to_string()))),
    )
}

fn looks_like_ask_query(text: &str) -> bool {
    let trimmed = strip_sparql_prologue(text).trim_start();
    let Some(rest) = trimmed.get(..3) else {
        return false;
    };
    if !rest.eq_ignore_ascii_case("ask") {
        return false;
    }
    match trimmed.as_bytes().get(3) {
        None => true,
        Some(b) => b.is_ascii_whitespace() || *b == b'{',
    }
}

/// Skips leading BOM, comments, and BASE/PREFIX declarations for early ASK checks.
fn strip_sparql_prologue(text: &str) -> &str {
    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
    let bytes = text.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        if i >= bytes.len() {
            break;
        }
        if bytes[i] == b'#' {
            while i < bytes.len() && bytes[i] != b'\n' {
                i += 1;
            }
            continue;
        }
        let rest = &text[i..];
        if rest.len() >= 4
            && rest.is_char_boundary(4)
            && rest[..4].eq_ignore_ascii_case("base")
            && rest
                .as_bytes()
                .get(4)
                .is_some_and(|b| b.is_ascii_whitespace() || *b == b'<')
        {
            if let Some(rel) = rest.find('>') {
                i += rel + 1;
                continue;
            }
            break;
        }
        if rest.len() >= 6
            && rest.is_char_boundary(6)
            && rest[..6].eq_ignore_ascii_case("prefix")
            && rest
                .as_bytes()
                .get(6)
                .is_some_and(|b| b.is_ascii_whitespace())
        {
            if let Some(rel) = rest.find('>') {
                i += rel + 1;
                continue;
            }
            break;
        }
        break;
    }
    &text[i..]
}

fn apply_slice(
    mut query: SparqlAlgebraQuery,
    offset: usize,
    limit: Option<usize>,
) -> Result<SparqlAlgebraQuery> {
    if offset == 0 && limit.is_none() {
        return Ok(query);
    }
    match &mut query {
        SparqlAlgebraQuery::Select { pattern, .. }
        | SparqlAlgebraQuery::Construct { pattern, .. }
        | SparqlAlgebraQuery::Describe { pattern, .. } => {
            let inner = strip_slices(std::mem::replace(
                pattern,
                GraphPattern::Bgp {
                    patterns: Vec::new(),
                },
            ));
            *pattern = GraphPattern::Slice {
                inner: Box::new(inner),
                start: offset,
                length: limit,
            };
            Ok(query)
        }
        SparqlAlgebraQuery::Ask { .. } => Err(Error::Unsupported(
            "API-level limit/offset cannot be applied to ASK queries; put LIMIT in the query text if needed"
                .into(),
        )),
    }
}

/// Removes existing `Slice` layers so API limit/offset replace in-query limits.
fn strip_slices(mut pattern: GraphPattern) -> GraphPattern {
    while let GraphPattern::Slice { inner, .. } = pattern {
        pattern = *inner;
    }
    pattern
}

fn apply_dataset(dataset: &mut oxigraph::sparql::QueryDataset, config: &DatasetConfig) {
    if config.default_as_union {
        dataset.set_default_graph_as_union();
    } else if let Some(graphs) = &config.default_graphs {
        dataset.set_default_graph(graphs.clone());
    }
    if let Some(named) = &config.named_graphs {
        dataset.set_available_named_graphs(named.clone());
    }
}