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
//! Ontology Schema Representation
//!
//! Core types for representing RDF ontologies extracted from OWL/SKOS definitions.
//! These types serve as the semantic schema used throughout the platform generation pipeline.
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// Complete ontology schema extracted from RDF/OWL definitions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OntologySchema {
/// All classes (owl:Class) in the ontology
pub classes: Vec<OntClass>,
/// All properties (owl:ObjectProperty, owl:DatatypeProperty) in the ontology
pub properties: Vec<OntProperty>,
/// Relationships between classes (derived from properties)
pub relationships: Vec<OntRelationship>,
/// Ontology namespace (e.g., `http://example.org/schema#`)
pub namespace: String,
/// Ontology version (rdfs:comment or owl:versionInfo)
pub version: String,
/// Human-readable label for the ontology
pub label: String,
/// Description of the ontology purpose
pub description: Option<String>,
/// Metadata key-value pairs
pub metadata: BTreeMap<String, String>,
}
/// Class definition extracted from owl:Class
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct OntClass {
/// Full URI of the class (e.g., `http://example.org/schema#Product`)
pub uri: String,
/// Short name extracted from URI (e.g., "Product")
pub name: String,
/// Human-readable label (rdfs:label)
pub label: String,
/// Description of the class purpose (rdfs:comment)
pub description: Option<String>,
/// Parent classes (rdfs:subClassOf)
pub parent_classes: Vec<String>,
/// Property URIs that are applicable to this class
pub properties: Vec<String>,
/// Whether this is an abstract class
pub is_abstract: bool,
/// Additional OWL restrictions on this class
pub restrictions: Vec<OwlRestriction>,
}
/// Property definition extracted from owl:ObjectProperty or owl:DatatypeProperty
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct OntProperty {
/// Full URI of the property (e.g., `http://example.org/schema#hasAuthor`)
pub uri: String,
/// Short name extracted from URI (e.g., "hasAuthor")
pub name: String,
/// Human-readable label (rdfs:label)
pub label: String,
/// Description of the property (rdfs:comment)
pub description: Option<String>,
/// Domain classes (rdfs:domain) - classes that have this property
pub domain: Vec<String>,
/// Range of values this property can take
pub range: PropertyRange,
/// Cardinality constraints for this property
pub cardinality: Cardinality,
/// Whether this property is required
pub required: bool,
/// Whether this property is a functional property (at most one value)
pub is_functional: bool,
/// Whether this property is inverse-functional
pub is_inverse_functional: bool,
/// Inverse property URI if this is a bidirectional relationship
pub inverse_of: Option<String>,
}
/// Type range of a property - what values it can hold
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum PropertyRange {
/// String literal
String,
/// Integer literal
Integer,
/// Floating point literal
Float,
/// Boolean literal
Boolean,
/// Date/DateTime literal
DateTime,
/// Date literal (YYYY-MM-DD)
Date,
/// Time literal
Time,
/// IRI/Reference to another class (ObjectProperty)
Reference(String),
/// Custom/literal type (e.g., JSON, UUID)
Literal(String),
/// Enumeration with fixed values
Enum(Vec<String>),
}
/// Cardinality constraints for a property
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum Cardinality {
/// Exactly one value (owl:cardinality 1)
One,
/// Zero or one value (owl:maxCardinality 1)
ZeroOrOne,
/// Zero or more values (default)
Many,
/// One or more values (owl:minCardinality 1)
OneOrMore,
/// Specific range (min, max)
Range { min: u32, max: Option<u32> },
}
impl Cardinality {
/// Get minimum cardinality
pub fn min(&self) -> u32 {
match self {
Self::One => 1,
Self::ZeroOrOne => 0,
Self::Many => 0,
Self::OneOrMore => 1,
Self::Range { min, .. } => *min,
}
}
/// Get maximum cardinality (None = unbounded)
pub fn max(&self) -> Option<u32> {
match self {
Self::One => Some(1),
Self::ZeroOrOne => Some(1),
Self::Many => None,
Self::OneOrMore => None,
Self::Range { max, .. } => *max,
}
}
/// Whether this property can have multiple values
pub fn is_multi_valued(&self) -> bool {
self.max().is_none() || self.max() > Some(1)
}
}
/// OWL Restriction on a class (e.g., owl:someValuesFrom, owl:allValuesFrom)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum OwlRestriction {
/// owl:someValuesFrom - at least one value must be from the specified class
SomeValuesFrom(String), // class URI
/// owl:allValuesFrom - all values must be from the specified class
AllValuesFrom(String), // class URI
/// owl:hasValue - property must have this exact value
HasValue(String), // value
/// owl:minCardinality - minimum number of values
MinCardinality(u32),
/// owl:maxCardinality - maximum number of values
MaxCardinality(u32),
/// owl:cardinality - exact number of values
Cardinality(u32),
}
/// Relationship between two classes (derived from properties)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OntRelationship {
/// Source class URI
pub from_class: String,
/// Destination class URI
pub to_class: String,
/// Property URI that defines this relationship
pub property: String,
/// Type of relationship (one-to-one, one-to-many, many-to-many)
pub relationship_type: RelationshipType,
/// Whether this is a bidirectional relationship
pub bidirectional: bool,
/// Label for the relationship
pub label: String,
}
/// Type of relationship between classes
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum RelationshipType {
/// One instance of source relates to one instance of target
OneToOne,
/// One instance of source relates to many instances of target
OneToMany,
/// Many instances of source relate to one instance of target
ManyToOne,
/// Many instances of source relate to many instances of target
ManyToMany,
/// Inheritance/subclass relationship
Inheritance,
/// Composition relationship
Composition,
/// Aggregation relationship
Aggregation,
}
impl OntologySchema {
/// Create a new empty ontology schema
pub fn new(namespace: impl Into<String>, version: impl Into<String>) -> Self {
Self {
classes: Vec::new(),
properties: Vec::new(),
relationships: Vec::new(),
namespace: namespace.into(),
version: version.into(),
label: String::new(),
description: None,
metadata: BTreeMap::new(),
}
}
/// Find a class by name
pub fn find_class(&self, name: &str) -> Option<&OntClass> {
self.classes.iter().find(|c| c.name == name)
}
/// Find a class by URI
pub fn find_class_by_uri(&self, uri: &str) -> Option<&OntClass> {
self.classes.iter().find(|c| c.uri == uri)
}
/// Find a property by name
pub fn find_property(&self, name: &str) -> Option<&OntProperty> {
self.properties.iter().find(|p| p.name == name)
}
/// Find a property by URI
pub fn find_property_by_uri(&self, uri: &str) -> Option<&OntProperty> {
self.properties.iter().find(|p| p.uri == uri)
}
/// Get all properties applicable to a class
pub fn properties_for_class(&self, class_uri: &str) -> Vec<&OntProperty> {
self.properties
.iter()
.filter(|p| p.domain.contains(&class_uri.to_string()))
.collect()
}
/// Get parent class chain for inheritance
pub fn get_class_hierarchy(&self, class_uri: &str) -> Vec<String> {
let mut hierarchy = vec![class_uri.to_string()];
if let Some(class) = self.find_class_by_uri(class_uri) {
for parent in &class.parent_classes {
let parent_hierarchy = self.get_class_hierarchy(parent);
hierarchy.extend(parent_hierarchy);
}
}
hierarchy.sort();
hierarchy.dedup();
hierarchy
}
}
impl PropertyRange {
/// Convert PropertyRange to TypeScript type string
pub fn to_typescript_type(&self) -> String {
match self {
Self::String => "string".to_string(),
Self::Integer => "number".to_string(),
Self::Float => "number".to_string(),
Self::Boolean => "boolean".to_string(),
Self::DateTime => "Date".to_string(),
Self::Date => "string".to_string(), // ISO date string
Self::Time => "string".to_string(),
Self::Reference(class_uri) => {
// Extract class name from URI
class_uri
.split('#')
.next_back()
.unwrap_or("unknown")
.to_string()
}
Self::Literal(type_name) => type_name.clone(),
Self::Enum(values) => format!("'{}'", values.join("' | '")),
}
}
/// Convert PropertyRange to GraphQL type string
pub fn to_graphql_type(&self, cardinality: &Cardinality) -> String {
let base_type = match self {
Self::String => "String".to_string(),
Self::Integer => "Int".to_string(),
Self::Float => "Float".to_string(),
Self::Boolean => "Boolean".to_string(),
Self::DateTime => "DateTime".to_string(),
Self::Date => "Date".to_string(),
Self::Time => "Time".to_string(),
Self::Reference(class_uri) => class_uri
.split('#')
.next_back()
.unwrap_or("Unknown")
.to_string(),
Self::Literal(type_name) => type_name.clone(),
// Represent the full set of enum values (joined as a union), mirroring
// the TypeScript codegen which emits every value (see codegen/typescript.rs).
Self::Enum(values) => values.join(" | "),
};
match cardinality {
Cardinality::Many | Cardinality::OneOrMore => format!("[{}]!", base_type),
Cardinality::One => format!("{}!", base_type),
Cardinality::ZeroOrOne => base_type,
Cardinality::Range { .. } => {
if cardinality.is_multi_valued() {
format!("[{}]!", base_type)
} else {
format!("{}!", base_type)
}
}
}
}
/// Convert PropertyRange to SQL type string
pub fn to_sql_type(&self) -> String {
match self {
Self::String => "VARCHAR(255)".to_string(),
Self::Integer => "INTEGER".to_string(),
Self::Float => "DECIMAL(10,2)".to_string(),
Self::Boolean => "BOOLEAN".to_string(),
Self::DateTime => "TIMESTAMPTZ".to_string(),
Self::Date => "DATE".to_string(),
Self::Time => "TIME".to_string(),
Self::Reference(_) => "UUID".to_string(),
Self::Literal(type_name) => match type_name.as_str() {
"json" | "JSON" => "JSONB".to_string(),
"uuid" | "UUID" => "UUID".to_string(),
_ => "VARCHAR(255)".to_string(),
},
Self::Enum(_) => "VARCHAR(50)".to_string(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cardinality_bounds() {
assert_eq!(Cardinality::One.min(), 1);
assert_eq!(Cardinality::One.max(), Some(1));
assert_eq!(Cardinality::Many.max(), None);
assert!(!Cardinality::One.is_multi_valued());
assert!(Cardinality::Many.is_multi_valued());
}
#[test]
fn test_property_range_conversion() {
assert_eq!(PropertyRange::String.to_typescript_type(), "string");
assert_eq!(PropertyRange::Integer.to_typescript_type(), "number");
assert_eq!(PropertyRange::DateTime.to_typescript_type(), "Date");
assert_eq!(PropertyRange::String.to_sql_type(), "VARCHAR(255)");
assert_eq!(PropertyRange::DateTime.to_sql_type(), "TIMESTAMPTZ");
}
#[test]
fn test_ontology_schema() {
let mut schema = OntologySchema::new("http://example.org/", "1.0.0");
schema.classes.push(OntClass {
uri: "http://example.org/#Product".to_string(),
name: "Product".to_string(),
label: "Product".to_string(),
description: Some("A product in the catalog".to_string()),
parent_classes: vec![],
properties: vec!["http://example.org/#name".to_string()],
is_abstract: false,
restrictions: vec![],
});
assert!(schema.find_class("Product").is_some());
assert!(schema.find_class("Unknown").is_none());
}
}