ontoenv 0.5.5

Rust library for managing ontologies and their imports in a local environment.
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
//! Defines the core data structures for representing ontologies and their metadata within the OntoEnv.
//! Includes `Ontology`, `GraphIdentifier`, and `OntologyLocation`.

use crate::consts::*;
use crate::util::{read_file, read_url};
use anyhow::Result;
use chrono::prelude::*;
use log::{debug, info, warn};
use oxigraph::model::{
    Graph as OxigraphGraph, GraphName, GraphNameRef, NamedNode, NamedNodeRef, NamedOrBlankNode,
    NamedOrBlankNodeRef, Term,
};
use oxigraph::store::Store;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_with::{serde_as, DeserializeAs, SerializeAs};
use std::collections::HashMap;
use std::hash::Hash;
use std::path::{Path, PathBuf};
use url::Url;
//
// custom derive for NamedNode
fn namednode_ser<S>(namednode: &NamedNode, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(namednode.as_str())
}

fn namednode_de<'de, D>(deserializer: D) -> Result<NamedNode, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    NamedNode::new(s).map_err(serde::de::Error::custom)
}

#[derive(Serialize, Deserialize, Eq, Debug, Clone)]
pub struct GraphIdentifier {
    location: OntologyLocation,
    #[serde(serialize_with = "namednode_ser", deserialize_with = "namednode_de")]
    name: NamedNode,
}

// equality for GraphIdentifier is based on the name and location
impl PartialEq for GraphIdentifier {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.location == other.location
    }
}

impl Hash for GraphIdentifier {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.location.hash(state);
    }
}

impl std::fmt::Display for GraphIdentifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} @ {}", self.name, self.location)
    }
}

impl From<GraphIdentifier> for NamedNode {
    fn from(val: GraphIdentifier) -> Self {
        val.name
    }
}

impl<'a> From<&'a GraphIdentifier> for NamedNodeRef<'a> {
    fn from(val: &'a GraphIdentifier) -> Self {
        (&val.name).into()
    }
}

impl GraphIdentifier {
    pub fn new(name: NamedNodeRef) -> Self {
        // Default location mirrors the graph IRI for simple in-memory identifiers.
        // location is same as name
        GraphIdentifier {
            location: OntologyLocation::from_str(name.as_str()).unwrap(),
            name: name.into(),
        }
    }
    pub fn new_with_location(name: NamedNodeRef, location: OntologyLocation) -> Self {
        // Use explicit location when the graph IRI differs from its source.
        GraphIdentifier {
            location,
            name: name.into(),
        }
    }
    pub fn location(&self) -> &OntologyLocation {
        // Borrow the location to avoid cloning for simple lookups.
        &self.location
    }

    pub fn name(&self) -> NamedNodeRef<'_> {
        // Return a lightweight reference to the graph name.
        self.name.as_ref()
    }

    pub fn to_filename(&self) -> String {
        // Create a filesystem-safe name for cache/storage paths.
        let name = self.name.as_str().replace(':', "+");
        let location = self.location.as_str().replace("file://", "");
        format!("{name}-{location}").replace('/', "_")
    }

    pub fn graphname(&self) -> Result<GraphName> {
        // Convert identifier to an Oxigraph GraphName for store APIs.
        Ok(GraphName::NamedNode(self.name.clone()))
    }
}

#[derive(Serialize, Deserialize, Hash, Clone, Eq, PartialEq, Debug)]
pub enum OntologyLocation {
    #[serde(rename = "file")]
    File(PathBuf),
    #[serde(rename = "url")]
    Url(String),
    /// Virtual source identifier for ontologies supplied as in-memory bytes.
    ///
    /// This identifier is used for environment bookkeeping only. `owl:imports` resolution still
    /// uses the import IRIs declared in the ontology content and resolves those against permanent
    /// locations (e.g., `http(s)`/`file`) when loaded through OntoEnv APIs.
    #[serde(rename = "in-memory")]
    InMemory { identifier: String },
}

// impl display for OntologyLocation
impl std::fmt::Display for OntologyLocation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OntologyLocation::Url(url) => write!(f, "{}", url),
            OntologyLocation::File(path) => {
                let effective_path = Self::normalized_file_path(path);
                if let Some(url) = Self::file_url_for(&effective_path) {
                    write!(f, "{}", url)
                } else {
                    write!(f, "{}", effective_path.display())
                }
            }
            OntologyLocation::InMemory { identifier } => {
                write!(f, "in-memory:{}", identifier)
            }
        }
    }
}

// impl default for OntologyLocation
impl Default for OntologyLocation {
    fn default() -> Self {
        OntologyLocation::File(Self::normalized_file_path(Path::new("")))
    }
}

impl OntologyLocation {
    pub fn as_str(&self) -> &str {
        // Provide a shared string view for logging and comparisons.
        match self {
            OntologyLocation::File(p) => p.to_str().unwrap_or_default(),
            OntologyLocation::Url(u) => u.as_str(),
            OntologyLocation::InMemory { identifier } => identifier.as_str(),
        }
    }

    pub fn graph(&self) -> Result<OxigraphGraph> {
        // Load content from the underlying location when possible.
        match self {
            OntologyLocation::File(p) => read_file(p),
            OntologyLocation::Url(u) => read_url(u),
            OntologyLocation::InMemory { .. } => Err(anyhow::anyhow!(
                "In-memory ontology locations cannot be refreshed from an external source"
            )),
        }
    }

    pub fn is_file(&self) -> bool {
        // Simple predicate used in filters and branching logic.
        match self {
            OntologyLocation::File(_) => true,
            OntologyLocation::Url(_) => false,
            OntologyLocation::InMemory { .. } => false,
        }
    }

    pub fn is_url(&self) -> bool {
        // Simple predicate used in filters and branching logic.
        match self {
            OntologyLocation::File(_) => false,
            OntologyLocation::Url(_) => true,
            OntologyLocation::InMemory { .. } => false,
        }
    }

    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Result<Self> {
        // Accept both IRIs and file paths, normalizing to absolute paths.
        let trimmed = s.trim();
        let value = if trimmed.starts_with('<') && trimmed.ends_with('>') && trimmed.len() >= 2 {
            &trimmed[1..trimmed.len() - 1]
        } else {
            trimmed
        };

        if value.starts_with("http://") || value.starts_with("https://") {
            return Ok(OntologyLocation::Url(value.to_string()));
        }

        if value.starts_with("file://") {
            let url = Url::parse(value)?;
            let path = match url.to_file_path() {
                Ok(path) => path,
                Err(()) => {
                    // Compatibility fallback for platform-dependent file URL handling
                    // (e.g., `file:///dummy.ttl` on Windows).
                    let mut p = PathBuf::from(value.trim_start_matches("file://"));
                    if !p.is_absolute() {
                        p = std::env::current_dir()?.join(p);
                    }
                    p
                }
            };
            return Ok(OntologyLocation::File(Self::normalized_file_path(&path)));
        }

        let mut p = PathBuf::from(value);
        if !p.is_absolute() {
            p = std::env::current_dir()?.join(p);
        }
        Ok(OntologyLocation::File(Self::normalized_file_path(&p)))
    }

    pub fn to_iri(&self) -> NamedNode {
        // Convert location to a canonical IRI for graph identifiers.
        match self {
            OntologyLocation::File(p) => {
                let effective_path = Self::normalized_file_path(p);
                if let Some(url) = Self::file_url_for(&effective_path) {
                    let iri: String = url.into();
                    return NamedNode::new(iri.clone())
                        .unwrap_or_else(|_| NamedNode::new_unchecked(iri));
                }

                let fallback_iri = format!("file://{}", effective_path.display());
                NamedNode::new(fallback_iri.clone())
                    .unwrap_or_else(|_| NamedNode::new_unchecked(fallback_iri))
            }
            OntologyLocation::Url(u) => {
                // Strip angle brackets if present (e.g., "<http://...>")
                let iri = if u.starts_with('<') && u.ends_with('>') && u.len() >= 2 {
                    u[1..u.len() - 1].to_string()
                } else {
                    u.clone()
                };
                NamedNode::new(iri).unwrap()
            }
            OntologyLocation::InMemory { identifier } => NamedNode::new(identifier.clone())
                .unwrap_or_else(|_| NamedNode::new_unchecked(identifier.clone())),
        }
    }

    pub fn as_path(&self) -> Option<&PathBuf> {
        // Expose file paths only when the location is filesystem-based.
        match self {
            OntologyLocation::File(p) => Some(p),
            OntologyLocation::Url(_) => None,
            OntologyLocation::InMemory { .. } => None,
        }
    }

    fn normalized_file_path(path: &Path) -> PathBuf {
        if path.as_os_str().is_empty() {
            return std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        }

        if path.is_relative() {
            let base = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
            return base.join(path);
        }

        path.to_path_buf()
    }

    fn file_url_for(path: &Path) -> Option<Url> {
        Url::from_file_path(path)
            .ok()
            .or_else(|| Url::from_directory_path(path).ok())
    }
}

struct LocalType;

impl SerializeAs<NamedNode> for LocalType {
    fn serialize_as<S>(value: &NamedNode, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        namednode_ser(value, serializer)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn assert_location_matches_path(display: &str, iri: &NamedNode, expected: &Path) {
        if let Some(url) = OntologyLocation::file_url_for(expected) {
            let expected_url: String = url.into();
            assert_eq!(display, expected_url, "display should equal file URL");
            assert_eq!(iri.as_str(), expected_url, "iri should equal file URL");
        } else {
            let expected_str = expected.to_string_lossy().into_owned();
            assert!(
                display.contains(&expected_str),
                "display should contain normalized path"
            );
            assert!(
                iri.as_str().contains(&expected_str),
                "iri should contain normalized path"
            );
        }
    }

    #[test]
    fn file_location_with_empty_path_uses_current_dir() {
        let cwd = std::env::current_dir().unwrap();
        let expected = OntologyLocation::normalized_file_path(Path::new(""));
        assert_eq!(expected, cwd);
        let location = OntologyLocation::File(PathBuf::new());

        let display = location.to_string();
        let iri = location.to_iri();

        assert!(!display.is_empty());
        assert_location_matches_path(&display, &iri, &expected);
    }

    #[test]
    fn file_location_normalizes_relative_paths() {
        let relative = PathBuf::from("some/relative/path");
        let location = OntologyLocation::File(relative.clone());

        let expected = OntologyLocation::normalized_file_path(&relative);
        let cwd = std::env::current_dir().unwrap();
        assert_eq!(expected, cwd.join(&relative));
        let display = location.to_string();
        let iri = location.to_iri();

        assert_location_matches_path(&display, &iri, &expected);
    }

    #[test]
    fn file_url_from_str_round_trips_to_path() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("import.ttl");
        std::fs::write(&path, b"").unwrap();
        let url = Url::from_file_path(&path).unwrap().to_string();

        let parsed = OntologyLocation::from_str(&url).unwrap();
        match parsed {
            OntologyLocation::File(parsed_path) => {
                assert_eq!(
                    OntologyLocation::normalized_file_path(&parsed_path),
                    OntologyLocation::normalized_file_path(&path)
                );
            }
            other => panic!("Expected file location, got {other:?}"),
        }
    }

    #[test]
    fn file_url_root_only_path_is_accepted() {
        let parsed = OntologyLocation::from_str("file:///dummy.ttl").unwrap();
        assert!(matches!(parsed, OntologyLocation::File(_)));
    }
}

impl<'de> DeserializeAs<'de, NamedNode> for LocalType {
    fn deserialize_as<D>(deserializer: D) -> Result<NamedNode, D::Error>
    where
        D: Deserializer<'de>,
    {
        namednode_de(deserializer)
    }
}

#[serde_as]
#[derive(Serialize, Deserialize, Clone, Eq, PartialEq, Debug)]
pub struct Ontology {
    id: GraphIdentifier,
    #[serde(serialize_with = "namednode_ser", deserialize_with = "namednode_de")]
    name: NamedNode,
    #[serde_as(as = "Vec<LocalType>")]
    pub imports: Vec<NamedNode>,
    location: Option<OntologyLocation>,
    pub last_updated: Option<DateTime<Utc>>,
    #[serde_as(as = "HashMap<LocalType, _>")]
    version_properties: HashMap<NamedNode, String>,
    #[serde(default)]
    namespace_map: HashMap<String, String>,
    #[serde(default)]
    content_hash: Option<String>,
}

// impl display; name + location + last updated, then indented version properties
impl std::fmt::Display for Ontology {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Ontology: {}\nLocation: {}\nVersion Properties:\n",
            self.name,
            self.id.location.as_str()
        )?;
        for (k, v) in self.version_properties.iter() {
            writeln!(f, "  {k}: {v}")?;
        }
        Ok(())
    }
}

// impl default for Ontology
impl Default for Ontology {
    fn default() -> Self {
        Ontology {
            id: GraphIdentifier {
                location: OntologyLocation::default(),
                name: NamedNode::new("<n/a>").unwrap(),
            },
            name: NamedNode::new("<n/a>").unwrap(),
            imports: vec![],
            location: None,
            last_updated: None,
            version_properties: HashMap::new(),
            namespace_map: HashMap::new(),
            content_hash: None,
        }
    }
}

impl Ontology {
    pub fn with_last_updated(&mut self, last_updated: DateTime<Utc>) {
        // Update timestamp after a successful refresh.
        self.last_updated = Some(last_updated);
    }

    /// Update the ontology's location (and associated identifier) in one step.
    /// Keeps the name stable while swapping in the new location.
    pub fn set_location(&mut self, location: OntologyLocation) {
        // Keep id/location consistent since both are persisted and indexed.
        self.id = GraphIdentifier::new_with_location(self.id.name(), location.clone());
        self.location = Some(location);
    }

    pub fn set_content_hash(&mut self, hash: String) {
        // Record content hash for change detection without re-parsing.
        self.content_hash = Some(hash);
    }

    pub fn content_hash(&self) -> Option<&str> {
        // Return borrowed hash string for lightweight comparisons.
        self.content_hash.as_deref()
    }

    pub fn id(&self) -> &GraphIdentifier {
        // Return a reference to the stable identifier.
        &self.id
    }

    pub fn exists(&self) -> bool {
        // Check presence based on location type without loading the graph.
        match &self.location {
            Some(OntologyLocation::File(p)) => p.exists(),
            Some(OntologyLocation::Url(u)) => {
                let opts = crate::fetch::FetchOptions::default();
                crate::fetch::head_exists(u, &opts).unwrap_or(false)
            }
            Some(OntologyLocation::InMemory { .. }) => false,
            None => false,
        }
    }

    pub fn version_properties(&self) -> &HashMap<NamedNode, String> {
        // Expose collected version metadata for resolution policies.
        &self.version_properties
    }

    pub fn location(&self) -> Option<&OntologyLocation> {
        // Borrow location to avoid cloning in common read paths.
        self.location.as_ref()
    }

    pub fn graph(&self) -> Result<OxigraphGraph> {
        // Load graph from the best available source (explicit location or name).
        if let Some(location) = &self.location {
            return location.graph();
        }
        OntologyLocation::from_str(self.name.as_str()).and_then(|loc| loc.graph())
    }

    pub fn name(&self) -> NamedNode {
        // Clone to preserve internal ownership semantics.
        self.name.clone()
    }

    pub fn dump(&self) -> String {
        // Serialize for debugging or exports.
        serde_json::to_string_pretty(self).unwrap()
    }

    pub fn namespace_map(&self) -> &HashMap<String, String> {
        // Share the cached prefix map for CLI and diagnostics.
        &self.namespace_map
    }

    fn build_from_subject_in_store(
        store: &Store,
        graph_name: GraphNameRef,
        ontology_subject: NamedOrBlankNode,
        location: OntologyLocation,
    ) -> Result<Self> {
        debug!("got ontology name: {ontology_subject}");

        // Extract SHACL prefix declarations into a namespace map for later reuse.
        let mut namespace_map = HashMap::new();

        let declare_prop = NamedNode::new_unchecked("http://www.w3.org/ns/shacl#declare");
        let prefix_prop = NamedNode::new_unchecked("http://www.w3.org/ns/shacl#prefix");
        let namespace_prop = NamedNode::new_unchecked("http://www.w3.org/ns/shacl#namespace");

        let ontology_subject_ref = ontology_subject.as_ref();

        // Walk sh:declare links off the ontology to find prefix/namespace pairs.
        for decl_obj in store
            .quads_for_pattern(
                Some(ontology_subject_ref),
                Some(declare_prop.as_ref()),
                None,
                Some(graph_name),
            )
            .filter_map(Result::ok)
            .map(|q| q.object)
        {
            let decl_subj = match &decl_obj {
                Term::NamedNode(n) => NamedOrBlankNode::NamedNode(n.clone()),
                Term::BlankNode(b) => NamedOrBlankNode::BlankNode(b.clone()),
                _ => continue,
            };

            let prefix_term = store
                .quads_for_pattern(
                    Some(decl_subj.as_ref()),
                    Some(prefix_prop.as_ref()),
                    None,
                    Some(graph_name),
                )
                .filter_map(Result::ok)
                .map(|q| q.object)
                .next();
            let namespace_term = store
                .quads_for_pattern(
                    Some(decl_subj.as_ref()),
                    Some(namespace_prop.as_ref()),
                    None,
                    Some(graph_name),
                )
                .filter_map(Result::ok)
                .map(|q| q.object)
                .next();

            if let (Some(Term::Literal(prefix_lit)), Some(Term::Literal(namespace_lit))) =
                (prefix_term, namespace_term)
            {
                namespace_map.insert(
                    prefix_lit.value().to_string(),
                    namespace_lit.value().to_string(),
                );
            }
        }

        // Collect owl:imports objects from the ontology subject.
        let imports: Vec<Term> = store
            .quads_for_pattern(
                Some(ontology_subject_ref),
                Some(IMPORTS),
                None,
                Some(graph_name),
            )
            .filter_map(Result::ok)
            .map(|q| q.object)
            .collect::<Vec<_>>();

        // Extract version properties directly on the ontology subject.
        let mut version_properties: HashMap<NamedNode, String> =
            ONTOLOGY_VERSION_IRIS
                .iter()
                .fold(HashMap::new(), |mut acc, &iri| {
                    if let Some(o) = store
                        .quads_for_pattern(
                            Some(ontology_subject_ref),
                            Some(iri),
                            None,
                            Some(graph_name),
                        )
                        .filter_map(Result::ok)
                        .map(|q| q.object)
                        .next()
                    {
                        match o {
                            Term::NamedNode(s) => {
                                acc.insert(iri.into(), s.to_string());
                            }
                            Term::Literal(lit) => {
                                acc.insert(iri.into(), lit.to_string());
                            }
                            _ => (),
                        }
                    }
                    acc
                });

        // Check for version properties in linked graph metadata nodes.
        let graph_metadata: Vec<Term> = store
            .quads_for_pattern(
                Some(ontology_subject_ref),
                Some(HAS_GRAPH_METADATA),
                None,
                Some(graph_name),
            )
            .filter_map(Result::ok)
            .map(|q| q.object)
            .collect::<Vec<_>>();
        for value in graph_metadata {
            let graph_iri = match value {
                Term::NamedNode(s) => s,
                _ => continue,
            };
            for iri in ONTOLOGY_VERSION_IRIS.iter() {
                if let Some(value) = store
                    .quads_for_pattern(
                        Some(NamedOrBlankNodeRef::NamedNode(graph_iri.as_ref())),
                        Some(*iri),
                        None,
                        Some(graph_name),
                    )
                    .filter_map(Result::ok)
                    .map(|q| q.object)
                    .next()
                {
                    match value {
                        Term::NamedNode(s) => {
                            version_properties.insert((*iri).into(), s.to_string());
                        }
                        Term::Literal(lit) => {
                            version_properties.insert((*iri).into(), lit.to_string());
                        }
                        _ => (),
                    }
                }
            }
        }
        // Log extracted version properties for debugging.
        for (k, v) in version_properties.iter() {
            debug!("{k}: {v}");
        }

        info!("Fetched graph {ontology_subject} from location: {location:?}");

        let ontology_name: NamedNode = match ontology_subject {
            NamedOrBlankNode::NamedNode(s) => s,
            _ => panic!("Ontology name is not an IRI"),
        };

        // Convert import terms to NamedNodes and drop self-imports.
        let imports: Vec<NamedNode> = imports
            .iter()
            .map(|t| match t {
                Term::NamedNode(s) => s,
                _ => panic!("Import is not an IRI"),
            })
            .filter(|s| **s != ontology_name)
            .cloned()
            .collect();

        Ok(Ontology {
            id: GraphIdentifier {
                location: location.clone(),
                name: ontology_name.clone(),
            },
            name: ontology_name,
            imports,
            location: Some(location),
            version_properties,
            last_updated: None,
            namespace_map,
            content_hash: None,
        })
    }

    /// Creates an `Ontology` from a graph in a `Store`.
    pub fn from_store(
        store: &Store,
        id: &GraphIdentifier,
        require_ontology_names: bool,
    ) -> Result<Self> {
        // Build an Ontology by inspecting triples in the store for the given graph.
        let graph_name = id.graphname()?;
        let graph_name_ref = graph_name.as_ref();
        let location = id.location().clone();

        // get the rdf:type owl:Ontology declarations
        let mut decls: Vec<NamedOrBlankNode> = store
            .quads_for_pattern(
                None,
                Some(TYPE),
                Some(ONTOLOGY.into()),
                Some(graph_name_ref),
            )
            .filter_map(Result::ok)
            .map(|q| q.subject)
            .collect::<Vec<_>>();

        // if decls is empty, then find all subjects of sh:declare
        if decls.is_empty() {
            decls.extend(
                store
                    .quads_for_pattern(None, Some(DECLARE), None, Some(graph_name_ref))
                    .filter_map(Result::ok)
                    .map(|t| t.subject),
            );
        }

        if decls.len() > 1 {
            warn!("Multiple ontology declarations found in {location}, using first one");
        }

        if decls.is_empty() {
            if require_ontology_names {
                return Err(anyhow::anyhow!(
                    "No ontology declaration found in {}",
                    location
                ));
            }
            // Fall back to the location IRI when no explicit ontology declaration exists.
            warn!("No ontology declaration found in {location}. Using this as the ontology name");
            let ontology_subject = NamedOrBlankNode::NamedNode(location.to_iri());
            Self::build_from_subject_in_store(store, graph_name_ref, ontology_subject, location)
        } else {
            let decl = decls.into_iter().next().unwrap();
            let ontology_subject = match decl {
                NamedOrBlankNode::NamedNode(s) => NamedOrBlankNode::NamedNode(s),
                _ => {
                    // Blank nodes are not stable ontology identifiers; fail in strict mode.
                    return Err(anyhow::anyhow!(
                        "Ontology declaration subject is not a NamedNode, skipping."
                    ));
                }
            };
            Self::build_from_subject_in_store(store, graph_name_ref, ontology_subject, location)
        }
    }

    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Result<Self> {
        // Convenience for reading persisted ontology JSON.
        Ok(serde_json::from_str(s)?)
    }
}