oxilite 0.9.1

Oxigraph-compatible RDF database and SPARQL engine on SQLite (native, dlopen'ed libsqlite3, Cloudflare D1)
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! The schema registry: ontology and shapes graphs, scoped reasoning, schema-graph hiding and
//! the compiled shape index.

use oxilite::io::RdfFormat;
use oxilite::model::{GraphName, NamedNode, Term};
use oxilite::schema::{Registration, SchemaRole};
use oxilite::sparql::{QueryOptions, Reasoning};
use oxilite::store::Store;
use oxilite_core::{QueryOutput, SyncBackend};

const PREFIXES: &str = "@prefix ex: <http://example.com/> . \
     @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \
     @prefix owl: <http://www.w3.org/2002/07/owl#> . \
     @prefix sh: <http://www.w3.org/ns/shacl#> . \
     @prefix xsd: <http://www.w3.org/2001/XMLSchema#> . ";

fn store() -> Store {
    Store::new().unwrap()
}

fn load<B: SyncBackend + Send + Sync + 'static>(store: &Store<B>, trig: &str) {
    store
        .load_from_slice(RdfFormat::TriG, format!("{PREFIXES}{trig}").as_bytes())
        .unwrap();
}

fn graph(iri: &str) -> GraphName {
    NamedNode::new(iri).unwrap().into()
}

/// Values of the first variable, as N-Triples strings, sorted.
fn values<B: SyncBackend + Send + Sync + 'static>(
    store: &Store<B>,
    query: &str,
    options: &QueryOptions,
) -> Vec<String> {
    let q = format!(
        "PREFIX ex: <http://example.com/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
         PREFIX owl: <http://www.w3.org/2002/07/owl#> {query}"
    );
    match store.query_output(q.as_str(), options).unwrap() {
        QueryOutput::Solutions { rows, .. } => {
            let mut v: Vec<String> = rows
                .iter()
                .filter_map(|r| r.first().cloned().flatten())
                .map(|t: Term| t.to_string())
                .collect();
            v.sort();
            v
        }
        _ => panic!("expected solutions"),
    }
}

fn rdfs() -> QueryOptions {
    QueryOptions {
        reasoning: Reasoning::Rdfs,
        union_default_graph: true,
        ..QueryOptions::default()
    }
}

// @lat: [[tests#Schema registry#Registration round-trip]]
#[test]
fn registers_lists_and_unregisters() {
    let store = store();
    load(&store, "GRAPH ex:onto { ex:Dog rdfs:subClassOf ex:Animal }");
    let g = graph("http://example.com/onto");
    store
        .register_schema_graph(
            g.as_ref(),
            SchemaRole::Ontology,
            &Registration::new()
                .with_iri(NamedNode::new("http://example.com/onto").unwrap())
                .with_version("v1")
                .with_imports([NamedNode::new("http://example.com/base").unwrap()]),
        )
        .unwrap();

    let listed = store.schema_graphs().unwrap();
    assert_eq!(listed.len(), 1);
    assert_eq!(listed[0].graph, g);
    assert_eq!(listed[0].role, SchemaRole::Ontology);
    assert_eq!(listed[0].registration.version.as_deref(), Some("v1"));
    assert_eq!(listed[0].registration.imports.len(), 1);
    assert!(listed[0].registration.active);

    // Registering does not move triples: the graph is still ordinary RDF.
    assert_eq!(
        values(
            &store,
            "SELECT ?o WHERE { GRAPH <http://example.com/onto> { ex:Dog rdfs:subClassOf ?o } }",
            &QueryOptions::default()
        ),
        ["<http://example.com/Animal>"]
    );

    assert!(store.unregister_schema_graph(g.as_ref()).unwrap());
    assert!(store.schema_graphs().unwrap().is_empty());
    // …and unregistering does not remove them either.
    assert_eq!(store.len().unwrap(), 1);
}

// @lat: [[tests#Schema registry#Reasoning scoped to registered ontologies]]
#[test]
fn reasoning_is_scoped_to_active_ontologies() {
    let store = store();
    load(
        &store,
        "GRAPH ex:good { ex:Dog rdfs:subClassOf ex:Animal } \
         GRAPH ex:bad { ex:Rock rdfs:subClassOf ex:Animal } \
         ex:rex a ex:Dog . ex:granite a ex:Rock .",
    );
    let q = "SELECT ?x WHERE { ?x a ex:Animal }";

    // Nothing registered: every graph contributes, as before the registry existed.
    assert_eq!(
        values(&store, q, &rdfs()),
        ["<http://example.com/granite>", "<http://example.com/rex>"]
    );

    let good = graph("http://example.com/good");
    let bad = graph("http://example.com/bad");
    store
        .register_schema_graph(good.as_ref(), SchemaRole::Ontology, &Registration::new())
        .unwrap();
    store
        .register_schema_graph(bad.as_ref(), SchemaRole::Ontology, &Registration::new())
        .unwrap();
    assert_eq!(
        values(&store, q, &rdfs()),
        ["<http://example.com/granite>", "<http://example.com/rex>"]
    );

    // Deactivating one ontology withdraws its entailments.
    assert!(store.set_schema_graph_active(bad.as_ref(), false).unwrap());
    assert_eq!(values(&store, q, &rdfs()), ["<http://example.com/rex>"]);

    // Reactivating restores them, with no reload of data.
    assert!(store.set_schema_graph_active(bad.as_ref(), true).unwrap());
    assert_eq!(
        values(&store, q, &rdfs()),
        ["<http://example.com/granite>", "<http://example.com/rex>"]
    );
}

// @lat: [[tests#Schema registry#Axioms outside registered ontologies]]
#[test]
fn axioms_outside_registered_ontologies_are_ignored() {
    let store = store();
    load(
        &store,
        "GRAPH ex:onto { ex:Dog rdfs:subClassOf ex:Animal } \
         GRAPH ex:notes { ex:Rock rdfs:subClassOf ex:Animal } \
         ex:rex a ex:Dog . ex:granite a ex:Rock .",
    );
    store
        .register_schema_graph(
            graph("http://example.com/onto").as_ref(),
            SchemaRole::Ontology,
            &Registration::new(),
        )
        .unwrap();
    assert_eq!(
        values(&store, "SELECT ?x WHERE { ?x a ex:Animal }", &rdfs()),
        ["<http://example.com/rex>"]
    );
}

// @lat: [[tests#Schema registry#Hiding schema graphs]]
#[test]
fn schema_graphs_can_be_hidden() {
    let store = store();
    load(
        &store,
        "GRAPH ex:onto { ex:Dog rdfs:subClassOf ex:Animal } ex:rex a ex:Dog .",
    );
    let visible = QueryOptions {
        union_default_graph: true,
        ..QueryOptions::default()
    };
    let hidden = QueryOptions {
        include_schema_graphs: false,
        ..visible.clone()
    };
    let q = "SELECT (COUNT(*) AS ?n) WHERE { ?s ?p ?o }";

    // Not registered yet: hiding changes nothing.
    assert_eq!(values(&store, q, &visible), values(&store, q, &hidden));

    store
        .register_schema_graph(
            graph("http://example.com/onto").as_ref(),
            SchemaRole::Ontology,
            &Registration::new(),
        )
        .unwrap();
    // Visible: the data, the ontology, and the registry graph's description of it (type,
    // active flag, oxl:appliesTo oxl:AllGraphs, registration time).
    assert_eq!(
        values(&store, q, &visible),
        ["\"6\"^^<http://www.w3.org/2001/XMLSchema#integer>"]
    );
    assert_eq!(
        values(&store, q, &hidden),
        ["\"1\"^^<http://www.w3.org/2001/XMLSchema#integer>"]
    );

    // Hiding ignores the active flag: an inactive ontology graph is still schema.
    store
        .set_schema_graph_active(graph("http://example.com/onto").as_ref(), false)
        .unwrap();
    assert_eq!(
        values(&store, q, &hidden),
        ["\"1\"^^<http://www.w3.org/2001/XMLSchema#integer>"]
    );
}

// @lat: [[tests#Schema registry#Dropping a schema graph]]
#[test]
fn drop_removes_registration_and_quads() {
    let store = store();
    load(
        &store,
        "GRAPH ex:onto { ex:Dog rdfs:subClassOf ex:Animal } ex:rex a ex:Dog .",
    );
    let g = graph("http://example.com/onto");
    store
        .register_schema_graph(g.as_ref(), SchemaRole::Ontology, &Registration::new())
        .unwrap();
    assert_eq!(store.drop_schema_graph(g.as_ref()).unwrap(), 1);
    assert!(store.schema_graphs().unwrap().is_empty());
    assert_eq!(store.len().unwrap(), 1);
    assert!(values(&store, "SELECT ?x WHERE { ?x a ex:Animal }", &rdfs()).is_empty());
}

const SHAPES: &str = "GRAPH ex:shapes { \
     ex:PersonShape a sh:NodeShape ; sh:targetClass ex:Person ; \
       sh:property [ sh:path ex:age ; sh:datatype xsd:integer ; sh:minCount 1 ; sh:maxCount 1 ] ; \
       sh:property [ sh:path ex:status ; sh:in ( \"on\" \"off\" ) ] ; \
       sh:property [ sh:path ex:name ; sh:pattern \"^[A-Z]\" ] ; \
       sh:property [ sh:path ex:employer ; sh:class ex:Company ] . }";

// @lat: [[tests#Schema registry#Compiled shape index]]
#[test]
fn shape_index_is_compiled_on_write() {
    let store = store();
    load(&store, SHAPES);
    // No `optimize()`: the index is refreshed inside the write that stored the shapes.
    let index = store.shape_index().unwrap();
    let person = NamedNode::new("http://example.com/Person").unwrap();

    let age = index
        .get(&person, &NamedNode::new("http://example.com/age").unwrap())
        .expect("age shape");
    assert_eq!(
        age.datatype.as_ref().map(|d| d.as_str()),
        Some("http://www.w3.org/2001/XMLSchema#integer")
    );
    assert_eq!(age.min, Some(1));
    assert_eq!(age.max, Some(1));
    assert!(!age.relationship);

    let status = index
        .get(
            &person,
            &NamedNode::new("http://example.com/status").unwrap(),
        )
        .expect("status shape");
    let mut got: Vec<String> = status.values_in.iter().map(Term::to_string).collect();
    got.sort();
    assert_eq!(got, ["\"off\"", "\"on\""]);

    let name = index
        .get(&person, &NamedNode::new("http://example.com/name").unwrap())
        .expect("name shape");
    assert_eq!(name.pattern.as_deref(), Some("^[A-Z]"));

    let employer = index
        .get(
            &person,
            &NamedNode::new("http://example.com/employer").unwrap(),
        )
        .expect("employer shape");
    assert!(employer.relationship);
}

// @lat: [[tests#Schema registry#Shape index follows deletions]]
#[test]
fn shape_index_follows_deletions_and_scope() {
    let store = store();
    load(&store, SHAPES);
    load(
        &store,
        "GRAPH ex:other { ex:OtherShape sh:targetClass ex:Thing ; \
           sh:property [ sh:path ex:label ; sh:minCount 1 ] . }",
    );
    let thing = NamedNode::new("http://example.com/Thing").unwrap();
    let label = NamedNode::new("http://example.com/label").unwrap();
    assert!(store.shape_index().unwrap().get(&thing, &label).is_some());

    // Registering one shapes graph narrows the index to it.
    store
        .register_schema_graph(
            graph("http://example.com/shapes").as_ref(),
            SchemaRole::Shacl,
            &Registration::new(),
        )
        .unwrap();
    assert!(store.shape_index().unwrap().get(&thing, &label).is_none());

    // Deleting the shape triples empties the index.
    store
        .update(
            "PREFIX sh: <http://www.w3.org/ns/shacl#> \
             DELETE WHERE { GRAPH <http://example.com/shapes> { ?s sh:targetClass ?o } }",
        )
        .unwrap();
    assert!(store.shape_index().unwrap().is_empty());
}

// @lat: [[tests#Schema registry#Shapes merged across shapes]]
#[test]
fn shapes_targeting_the_same_path_merge() {
    let store = store();
    load(
        &store,
        "ex:A sh:targetClass ex:Person ; sh:property [ sh:path ex:age ; sh:minCount 1 ] . \
         ex:B sh:targetClass ex:Person ; sh:property [ sh:path ex:age ; sh:datatype xsd:integer ] .",
    );
    let shape = store
        .shape_index()
        .unwrap()
        .get(
            &NamedNode::new("http://example.com/Person").unwrap(),
            &NamedNode::new("http://example.com/age").unwrap(),
        )
        .cloned()
        .expect("merged shape");
    assert_eq!(shape.min, Some(1));
    assert_eq!(
        shape.datatype.as_ref().map(|d| d.as_str()),
        Some("http://www.w3.org/2001/XMLSchema#integer")
    );
}

// @lat: [[tests#Schema registry#Registry survives reopening]]
#[test]
fn registry_survives_reopening() {
    let path = std::env::temp_dir().join(format!("oxilite-registry-{}", std::process::id()));
    let _ = std::fs::remove_file(&path);
    let g = graph("http://example.com/onto");
    {
        let store = Store::open(&path).unwrap();
        load(
            &store,
            "GRAPH ex:onto { ex:Dog rdfs:subClassOf ex:Animal } ex:rex a ex:Dog .",
        );
        store
            .register_schema_graph(
                g.as_ref(),
                SchemaRole::Ontology,
                &Registration::new().with_version("v2"),
            )
            .unwrap();
    }
    let store = Store::open(&path).unwrap();
    let listed = store.schema_graphs().unwrap();
    assert_eq!(listed.len(), 1);
    assert_eq!(listed[0].graph, g);
    assert_eq!(listed[0].registration.version.as_deref(), Some("v2"));
    assert_eq!(
        values(&store, "SELECT ?x WHERE { ?x a ex:Animal }", &rdfs()),
        ["<http://example.com/rex>"]
    );
    drop(store);
    let _ = std::fs::remove_file(&path);
}

fn with_graphs(store: &Store) {
    load(
        store,
        "GRAPH ex:o1 { ex:Dog rdfs:subClassOf ex:Animal } \
         GRAPH ex:o2 { ex:Dog rdfs:subClassOf ex:Plant } \
         GRAPH ex:base { ex:Animal rdfs:subClassOf ex:Being . ex:Plant rdfs:subClassOf ex:Being } \
         GRAPH ex:a { ex:rex a ex:Dog } \
         GRAPH ex:b { ex:fido a ex:Dog }",
    );
}

// @lat: [[tests#Schema registry#Ontologies apply to the graphs they are mapped to]]
#[test]
fn ontologies_apply_to_mapped_graphs() {
    let store = store();
    with_graphs(&store);
    let register = |o: &str, to: &[&str]| {
        store
            .register_schema_graph(
                graph(o).as_ref(),
                SchemaRole::Ontology,
                &Registration::new().applies_to(to.iter().map(|g| graph(g))),
            )
            .unwrap();
    };
    register("http://example.com/o1", &["http://example.com/a"]);
    register("http://example.com/o2", &["http://example.com/b"]);
    let animals = "SELECT ?x WHERE { ?x a ex:Animal }";
    let plants = "SELECT ?x WHERE { ?x a ex:Plant }";
    assert_eq!(
        values(&store, animals, &rdfs()),
        ["<http://example.com/rex>"]
    );
    assert_eq!(
        values(&store, plants, &rdfs()),
        ["<http://example.com/fido>"]
    );
    // The same through GRAPH ?g, and through the fallback evaluator's quad source.
    assert_eq!(
        values(
            &store,
            "SELECT ?x WHERE { GRAPH ?g { ?x a ex:Plant } }",
            &rdfs()
        ),
        ["<http://example.com/fido>"]
    );

    // A global ontology applies everywhere, on top of the mapped ones.
    register("http://example.com/base", &[]);
    assert_eq!(
        values(&store, "SELECT ?x WHERE { ?x a ex:Being }", &rdfs()),
        ["<http://example.com/fido>", "<http://example.com/rex>"]
    );
    // Remapping o1 to every graph makes rex and fido animals.
    register("http://example.com/o1", &[]);
    assert_eq!(
        values(&store, animals, &rdfs()),
        ["<http://example.com/fido>", "<http://example.com/rex>"]
    );
    assert_eq!(
        store
            .schema_graphs_for(graph("http://example.com/b").as_ref(), SchemaRole::Ontology)
            .unwrap(),
        [
            graph("http://example.com/base"),
            graph("http://example.com/o1"),
            graph("http://example.com/o2")
        ]
    );
    assert_eq!(
        store
            .schema_graphs_for(graph("http://example.com/a").as_ref(), SchemaRole::Ontology)
            .unwrap(),
        [
            graph("http://example.com/base"),
            graph("http://example.com/o1")
        ]
    );
}

// @lat: [[tests#Schema registry#The registry is RDF in the schema graph]]
#[test]
fn registry_is_rdf_in_the_schema_graph() {
    let store = store();
    with_graphs(&store);
    // Registered by a plain SPARQL update, as on any SPARQL store.
    store
        .update(
            "PREFIX oxl: <https://oxilite.dev/ns#> INSERT DATA { GRAPH <oxilite:schema> { \
             <http://example.com/o2> a oxl:OntologyGraph ; oxl:appliesTo <http://example.com/b> ; oxl:version \"7\" } }",
        )
        .unwrap();
    let listed = store.schema_graphs().unwrap();
    assert_eq!(listed.len(), 1);
    assert_eq!(listed[0].registration.version.as_deref(), Some("7"));
    assert_eq!(
        listed[0].registration.applies_to,
        [graph("http://example.com/b")]
    );
    assert!(listed[0].registration.active);
    assert_eq!(
        values(&store, "SELECT ?x WHERE { ?x a ex:Plant }", &rdfs()),
        ["<http://example.com/fido>"],
        "a SPARQL registration scopes reasoning like the API"
    );
    // What the API writes reads back with SPARQL.
    store
        .register_schema_graph(
            graph("http://example.com/o1").as_ref(),
            SchemaRole::Ontology,
            &Registration::new()
                .with_version("v1")
                .applies_to([GraphName::DefaultGraph]),
        )
        .unwrap();
    let ask = |q: &str| {
        matches!(
            store
                .query_output(
                    format!("PREFIX oxl: <https://oxilite.dev/ns#> ASK {{ GRAPH <oxilite:schema> {{ {q} }} }}").as_str(),
                    &QueryOptions::default()
                )
                .unwrap(),
            QueryOutput::Boolean(true)
        )
    };
    assert!(ask("<http://example.com/o1> a oxl:OntologyGraph ; oxl:version \"v1\" ; oxl:active true ; oxl:appliesTo oxl:DefaultGraph ; oxl:loadedAt ?t"));
    // Deactivating is a registry change too.
    assert!(store
        .set_schema_graph_active(graph("http://example.com/o2").as_ref(), false)
        .unwrap());
    assert!(ask("<http://example.com/o2> oxl:active false"));
    assert!(values(&store, "SELECT ?x WHERE { ?x a ex:Plant }", &rdfs()).is_empty());
    // The registry graph is hidden with the schema graphs.
    let hidden = QueryOptions {
        include_schema_graphs: false,
        ..QueryOptions::default()
    };
    assert!(
        values(&store, "SELECT ?g WHERE { GRAPH ?g { ?s ?p ?o } }", &hidden)
            .iter()
            .all(|g| g != "<oxilite:schema>" && g != "<http://example.com/o1>")
    );
    assert!(oxilite::schema::VOCABULARY.contains("oxl:appliesTo"));
}

// @lat: [[tests#Schema registry#A version 1 registry is migrated]]
#[test]
fn version_one_registry_is_migrated() {
    use oxilite_core::sql::Request;
    let path = std::env::temp_dir().join(format!("oxilite-registry-v1-{}", std::process::id()));
    let _ = std::fs::remove_file(&path);
    {
        let store = Store::open(&path).unwrap();
        load(
            &store,
            "GRAPH ex:onto { ex:Dog rdfs:subClassOf ex:Animal } \
             GRAPH ex:other { ex:Rock rdfs:subClassOf ex:Animal } ex:rex a ex:Dog . ex:granite a ex:Rock .",
        );
    }
    // Turn the file into a schema version 1 store holding one registration.
    let onto = oxilite_core::encoding::named_node_id("http://example.com/onto");
    let backend = oxilite::rusqlite::RusqliteBackend::open(&path).unwrap();
    backend
        .execute(&Request::atomic(vec![
            "DROP TABLE tbox_closure".into(),
            "CREATE TABLE tbox_closure (kind INTEGER NOT NULL, sub INTEGER NOT NULL, sup INTEGER NOT NULL, PRIMARY KEY (kind, sup, sub)) WITHOUT ROWID, STRICT".into(),
            "CREATE INDEX tbox_closure_sub ON tbox_closure(kind, sub, sup)".into(),
            "CREATE TABLE schema_graphs (g INTEGER PRIMARY KEY, role INTEGER NOT NULL, iri TEXT, version TEXT, sha256 TEXT, imports TEXT, active INTEGER NOT NULL DEFAULT 1, loaded_at REAL NOT NULL) STRICT".into(),
            format!("INSERT INTO schema_graphs VALUES ({onto}, 1, NULL, 'v1', NULL, 'http://example.com/base', 1, 0)").into(),
            "UPDATE oxilite_meta SET value = '1' WHERE key = 'schema_version'".into(),
        ]))
        .unwrap();
    drop(backend);

    let store = Store::open(&path).unwrap();
    let listed = store.schema_graphs().unwrap();
    assert_eq!(listed.len(), 1);
    assert_eq!(listed[0].graph, graph("http://example.com/onto"));
    assert_eq!(listed[0].role, SchemaRole::Ontology);
    assert_eq!(listed[0].registration.version.as_deref(), Some("v1"));
    assert_eq!(
        listed[0].registration.imports,
        [NamedNode::new("http://example.com/base").unwrap()]
    );
    assert_eq!(
        values(&store, "SELECT ?x WHERE { ?x a ex:Animal }", &rdfs()),
        ["<http://example.com/rex>"],
        "the migrated registration scopes reasoning"
    );
    drop(store);
    let backend = oxilite::rusqlite::RusqliteBackend::open(&path).unwrap();
    let r = backend
        .execute(&Request::read(vec![
            "SELECT count(*) FROM sqlite_master WHERE name = 'schema_graphs'".into(),
            "SELECT value FROM oxilite_meta WHERE key = 'schema_version'".into(),
        ]))
        .unwrap();
    assert_eq!(r[0].rows[0][0].as_i64(), Some(0));
    assert_eq!(r[1].rows[0][0].as_str(), Some("2"));
    drop(backend);
    let _ = std::fs::remove_file(&path);
}

// @lat: [[tests#Schema registry#A blank store starts with the system graphs]]
#[test]
fn blank_store_starts_with_system_graphs() {
    let options = oxilite::StoreOptions {
        system_graphs: true,
        ..Default::default()
    };
    let store = Store::with_backend_and_options(
        oxilite::rusqlite::RusqliteBackend::memory().unwrap(),
        &options,
    )
    .unwrap();
    let all = QueryOptions {
        union_default_graph: true,
        ..QueryOptions::default()
    };
    let graphs = values(
        &store,
        "SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }",
        &all,
    );
    assert_eq!(graphs, ["<oxilite:schema>", "<oxilite:vocabulary>"]);
    assert!(store.system_graphs_installed().unwrap());
    assert!(!store.install_system_graphs().unwrap(), "already current");
    // The vocabulary is there, typed and documented.
    assert_eq!(
        values(
            &store,
            "SELECT ?c WHERE { GRAPH <oxilite:vocabulary> { ?c rdfs:subClassOf <https://oxilite.dev/ns#SchemaGraph> } }",
            &all
        )
        .len(),
        3,
        "the role classes; oxl:SystemGraph is not a schema graph"
    );
    // System graphs are not registrations, do not narrow reasoning, and hide with the schema.
    assert!(store.schema_graphs().unwrap().is_empty());
    load(
        &store,
        "GRAPH ex:onto { ex:Dog rdfs:subClassOf ex:Animal } ex:rex a ex:Dog .",
    );
    assert_eq!(
        values(&store, "SELECT ?x WHERE { ?x a ex:Animal }", &rdfs()),
        ["<http://example.com/rex>"]
    );
    let hidden = QueryOptions {
        include_schema_graphs: false,
        ..all.clone()
    };
    assert_eq!(
        values(
            &store,
            "SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }",
            &hidden
        ),
        ["<http://example.com/onto>"]
    );
    // An existing store gets them on request; a store that has data is never bootstrapped.
    let plain = Store::new().unwrap();
    load(&plain, "ex:a ex:b ex:c .");
    assert!(!plain.system_graphs_installed().unwrap());
    assert!(plain.install_system_graphs().unwrap());
    assert!(plain.system_graphs_installed().unwrap());
    assert!(plain.schema_graphs().unwrap().is_empty());
}

// @lat: [[tests#Schema registry#Imports bring registered ontologies into scope]]
#[test]
fn imports_bring_registered_ontologies_into_scope() {
    let store = store();
    load(
        &store,
        "GRAPH ex:zoo { ex:Dog rdfs:subClassOf ex:Mammal } \
         GRAPH ex:core { ex:Mammal rdfs:subClassOf ex:Animal } \
         GRAPH ex:a { ex:rex a ex:Dog } \
         GRAPH ex:b { ex:tom a ex:Mammal }",
    );
    let register = |o: &str, r: Registration| {
        store
            .register_schema_graph(graph(o).as_ref(), SchemaRole::Ontology, &r)
            .unwrap();
    };
    let core = || Registration::new().applies_to([graph("http://example.com/b")]);
    let zoo = || Registration::new().applies_to([graph("http://example.com/a")]);
    let animals = "SELECT ?x WHERE { ?x a ex:Animal }";
    register("http://example.com/core", core());
    register("http://example.com/zoo", zoo());
    assert_eq!(
        values(&store, animals, &rdfs()),
        ["<http://example.com/tom>"]
    );

    // An import recorded in the registry, naming the imported graph.
    register(
        "http://example.com/zoo",
        zoo().with_imports([NamedNode::new("http://example.com/core").unwrap()]),
    );
    assert_eq!(
        values(&store, animals, &rdfs()),
        ["<http://example.com/rex>", "<http://example.com/tom>"]
    );
    // The registry records it as oxl:imports, never owl:imports (whose domain is owl:Ontology).
    assert_eq!(
        values(
            &store,
            "SELECT ?p WHERE { GRAPH <oxilite:schema> { ex:zoo ?p ex:core } }",
            &QueryOptions::default()
        ),
        ["<https://oxilite.dev/ns#imports>"]
    );

    // An owl:imports in the registry, as vocabulary 2 wrote it, still resolves.
    register("http://example.com/zoo", zoo());
    load(
        &store,
        "GRAPH <oxilite:schema> { ex:zoo owl:imports ex:core }",
    );
    assert_eq!(
        values(&store, animals, &rdfs()),
        ["<http://example.com/rex>", "<http://example.com/tom>"]
    );
    assert_eq!(
        store
            .schema_graphs()
            .unwrap()
            .iter()
            .find(|g| g.graph == graph("http://example.com/zoo"))
            .unwrap()
            .registration
            .imports,
        [NamedNode::new("http://example.com/core").unwrap()]
    );

    // An import asserted in the ontology itself, naming the other's oxl:ontologyIri.
    register("http://example.com/zoo", zoo());
    assert_eq!(
        values(&store, animals, &rdfs()),
        ["<http://example.com/tom>"]
    );
    register(
        "http://example.com/core",
        core().with_iri(NamedNode::new("http://example.com/coreOnto").unwrap()),
    );
    load(
        &store,
        "GRAPH ex:zoo { ex:zooOnto owl:imports ex:coreOnto }",
    );
    assert_eq!(
        values(&store, animals, &rdfs()),
        ["<http://example.com/rex>", "<http://example.com/tom>"]
    );

    // Import cycles end; the imported ontology does not import its importer's targets.
    load(&store, "GRAPH ex:core { ex:coreOnto owl:imports ex:zoo }");
    assert_eq!(
        values(&store, "SELECT ?x WHERE { ?x a ex:Mammal }", &rdfs()),
        ["<http://example.com/rex>", "<http://example.com/tom>"]
    );

    // An inactive ontology is not imported; deactivating every ontology silences reasoning
    // rather than falling back to every graph.
    store
        .set_schema_graph_active(graph("http://example.com/core").as_ref(), false)
        .unwrap();
    assert!(values(&store, animals, &rdfs()).is_empty());
    store
        .set_schema_graph_active(graph("http://example.com/zoo").as_ref(), false)
        .unwrap();
    assert_eq!(
        values(&store, "SELECT ?x WHERE { ?x a ex:Mammal }", &rdfs()),
        ["<http://example.com/tom>"],
        "only the asserted mammal"
    );
}

// @lat: [[tests#Schema registry#The active flag reads alike everywhere]]
#[test]
fn active_flag_reads_alike_everywhere() {
    let store = store();
    with_graphs(&store);
    store
        .register_schema_graph(
            graph("http://example.com/o1").as_ref(),
            SchemaRole::Ontology,
            &Registration::new().applies_to([graph("http://example.com/a")]),
        )
        .unwrap();
    let set = |o: &str| {
        store
            .update(
                format!(
                    "PREFIX oxl: <https://oxilite.dev/ns#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> \
                     DELETE WHERE {{ GRAPH <oxilite:schema> {{ <http://example.com/o2> ?p ?v }} }} ; \
                     INSERT DATA {{ GRAPH <oxilite:schema> {{ \
                     <http://example.com/o2> a oxl:OntologyGraph ; oxl:appliesTo <http://example.com/b> ; oxl:active {o} }} }}"
                )
                .as_str(),
            )
            .unwrap();
    };
    let plants = "SELECT ?x WHERE { ?x a ex:Plant }";
    let o2 = |store: &Store| {
        store
            .schema_graphs()
            .unwrap()
            .into_iter()
            .find(|e| e.graph == graph("http://example.com/o2"))
            .unwrap()
    };

    // A plain "false" is not an xsd:boolean: invalid, and ignored by every reader.
    set("\"false\"");
    assert!(o2(&store).registration.active);
    assert_eq!(
        values(&store, plants, &rdfs()),
        ["<http://example.com/fido>"]
    );
    let problems = store.registry_problems().unwrap();
    assert_eq!(problems.len(), 1, "{problems:?}");
    assert!(problems[0].contains("is not an <http://www.w3.org/2001/XMLSchema#boolean>"));

    // "0"^^xsd:boolean is false, for the API and for reasoning alike.
    set("\"0\"^^xsd:boolean");
    assert!(!o2(&store).registration.active);
    assert!(values(&store, plants, &rdfs()).is_empty());
    assert!(store.registry_problems().unwrap().is_empty());
}

// @lat: [[tests#Schema registry#Remapping keeps the description]]
#[test]
fn remapping_keeps_roles_and_description() {
    let store = store();
    with_graphs(&store);
    // An ontology that also carries shapes: two roles, one description.
    store
        .update(
            "PREFIX oxl: <https://oxilite.dev/ns#> INSERT DATA { GRAPH <oxilite:schema> { \
             <http://example.com/o1> a oxl:OntologyGraph , oxl:ShapesGraph ; oxl:version \"3\" ; \
             oxl:appliesTo <http://example.com/a> } }",
        )
        .unwrap();
    let listed = store.schema_graphs().unwrap();
    assert_eq!(
        listed.iter().map(|e| e.role).collect::<Vec<_>>(),
        [SchemaRole::Ontology, SchemaRole::Shacl]
    );
    assert!(store
        .set_schema_graph_targets(
            graph("http://example.com/o1").as_ref(),
            &[graph("http://example.com/b")]
        )
        .unwrap());
    let listed = store.schema_graphs().unwrap();
    assert_eq!(listed.len(), 2);
    for e in &listed {
        assert_eq!(e.registration.applies_to, [graph("http://example.com/b")]);
        assert_eq!(e.registration.version.as_deref(), Some("3"));
    }
    assert_eq!(
        values(&store, "SELECT ?x WHERE { ?x a ex:Animal }", &rdfs()),
        ["<http://example.com/fido>"]
    );
    // No targets: every graph, written as oxl:AllGraphs.
    assert!(store
        .set_schema_graph_targets(graph("http://example.com/o1").as_ref(), &[])
        .unwrap());
    assert!(store.schema_graphs().unwrap()[0]
        .registration
        .applies_to
        .is_empty());
    assert_eq!(
        values(
            &store,
            "SELECT ?t WHERE { GRAPH <oxilite:schema> { <http://example.com/o1> <https://oxilite.dev/ns#appliesTo> ?t } }",
            &QueryOptions::default()
        ),
        ["<https://oxilite.dev/ns#AllGraphs>"]
    );
    assert!(!store
        .set_schema_graph_targets(graph("http://example.com/nope").as_ref(), &[])
        .unwrap());
    assert!(store.registry_problems().unwrap().is_empty());
}