tensorlogic-oxirs-bridge 0.1.0

RDF/GraphQL/SHACL integration and provenance tracking for TensorLogic
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
//! GraphQL integration for RDF knowledge graphs.
//!
//! This module provides a bridge between OxiRS's RDF capabilities and GraphQL,
//! enabling GraphQL queries over knowledge graphs stored in RDF format.
//!
//! # Overview
//!
//! The `OxirsGraphQLBridge` provides:
//! - Automatic GraphQL schema generation from RDF ontologies
//! - Query execution translating GraphQL to SPARQL
//! - Type mapping between RDF classes and GraphQL types
//!
//! # Example
//!
//! ```no_run
//! use tensorlogic_oxirs_bridge::oxirs_graphql::OxirsGraphQLBridge;
//!
//! let mut bridge = OxirsGraphQLBridge::new().expect("Failed to create bridge");
//!
//! // Load RDF data
//! bridge.load_turtle(r#"
//!     @prefix ex: <http://example.org/> .
//!     @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
//!     ex:Person a rdfs:Class .
//!     ex:Alice a ex:Person .
//!     ex:Alice ex:name "Alice" .
//! "#).unwrap();
//!
//! // Generate GraphQL schema from the data
//! bridge.generate_schema().unwrap();
//! ```

use crate::oxirs_executor::OxirsSparqlExecutor;
use anyhow::Result;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tensorlogic_adapters::{DomainInfo, PredicateInfo, SymbolTable};
use tensorlogic_ir::{TLExpr, Term};

/// GraphQL type definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphQLType {
    /// Type name
    pub name: String,
    /// Whether this is a scalar type
    pub is_scalar: bool,
    /// Whether this is a list type
    pub is_list: bool,
    /// Whether this is non-null
    pub is_non_null: bool,
    /// Inner type for lists
    pub inner_type: Option<Box<GraphQLType>>,
}

impl GraphQLType {
    /// Create a scalar type.
    pub fn scalar(name: &str) -> Self {
        Self {
            name: name.to_string(),
            is_scalar: true,
            is_list: false,
            is_non_null: false,
            inner_type: None,
        }
    }

    /// Create an object type reference.
    pub fn object(name: &str) -> Self {
        Self {
            name: name.to_string(),
            is_scalar: false,
            is_list: false,
            is_non_null: false,
            inner_type: None,
        }
    }

    /// Create a list type.
    pub fn list(inner: GraphQLType) -> Self {
        Self {
            name: format!("[{}]", inner.name),
            is_scalar: false,
            is_list: true,
            is_non_null: false,
            inner_type: Some(Box::new(inner)),
        }
    }

    /// Make this type non-null.
    pub fn non_null(mut self) -> Self {
        self.is_non_null = true;
        self
    }

    /// Convert to SDL type string.
    pub fn to_sdl(&self) -> String {
        let base = if self.is_list {
            format!("[{}]", self.inner_type.as_ref().map_or("ID", |t| &t.name))
        } else {
            self.name.clone()
        };
        if self.is_non_null {
            format!("{}!", base)
        } else {
            base
        }
    }
}

/// GraphQL field definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphQLField {
    /// Field name
    pub name: String,
    /// Field type
    pub field_type: GraphQLType,
    /// Optional description
    pub description: Option<String>,
    /// Arguments
    pub arguments: Vec<GraphQLArgument>,
}

/// GraphQL argument definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphQLArgument {
    /// Argument name
    pub name: String,
    /// Argument type
    pub arg_type: GraphQLType,
    /// Default value
    pub default_value: Option<String>,
}

/// GraphQL object type definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphQLObjectType {
    /// Type name
    pub name: String,
    /// Description
    pub description: Option<String>,
    /// Fields
    pub fields: IndexMap<String, GraphQLField>,
    /// Interfaces this type implements
    pub interfaces: Vec<String>,
}

impl GraphQLObjectType {
    /// Create a new object type.
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            description: None,
            fields: IndexMap::new(),
            interfaces: Vec::new(),
        }
    }

    /// Add a field to this type.
    pub fn add_field(&mut self, field: GraphQLField) {
        self.fields.insert(field.name.clone(), field);
    }

    /// Convert to SDL.
    pub fn to_sdl(&self) -> String {
        let mut sdl = format!("type {} {{\n", self.name);
        for (_, field) in &self.fields {
            if let Some(desc) = &field.description {
                sdl.push_str(&format!("  \"\"\"{}\"\"\"\n", desc));
            }
            sdl.push_str(&format!(
                "  {}: {}\n",
                field.name,
                field.field_type.to_sdl()
            ));
        }
        sdl.push_str("}\n");
        sdl
    }
}

/// GraphQL schema definition (internal representation).
#[derive(Debug, Clone, Default)]
pub struct GraphQLSchema {
    /// Type definitions
    pub types: IndexMap<String, GraphQLObjectType>,
    /// Query type name
    pub query_type: Option<String>,
    /// Mutation type name
    pub mutation_type: Option<String>,
    /// Schema SDL string
    pub sdl: String,
}

impl GraphQLSchema {
    /// Create a new empty schema.
    pub fn new() -> Self {
        Self::default()
    }

    /// Parse schema from SDL (simplified - stores the SDL string).
    pub fn parse(sdl: &str) -> Result<Self> {
        Ok(Self {
            types: IndexMap::new(),
            query_type: Some("Query".to_string()),
            mutation_type: None,
            sdl: sdl.to_string(),
        })
    }

    /// Add a type to the schema.
    pub fn add_type(&mut self, object_type: GraphQLObjectType) {
        self.types.insert(object_type.name.clone(), object_type);
    }

    /// Generate SDL from types.
    pub fn to_sdl(&self) -> String {
        if !self.sdl.is_empty() {
            return self.sdl.clone();
        }

        let mut sdl = String::new();
        for (_, object_type) in &self.types {
            sdl.push_str(&object_type.to_sdl());
            sdl.push('\n');
        }
        sdl
    }
}

/// OxiRS GraphQL Bridge.
///
/// Bridges RDF data access through a GraphQL interface.
pub struct OxirsGraphQLBridge {
    /// Internal SPARQL executor
    executor: OxirsSparqlExecutor,
    /// Generated GraphQL schema
    schema: Option<GraphQLSchema>,
    /// Type definitions
    types: IndexMap<String, GraphQLObjectType>,
    /// IRI to type name mappings
    iri_to_type: HashMap<String, String>,
    /// Prefix mappings
    prefixes: HashMap<String, String>,
}

impl OxirsGraphQLBridge {
    /// Create a new GraphQL bridge.
    pub fn new() -> Result<Self> {
        Ok(Self {
            executor: OxirsSparqlExecutor::new()?,
            schema: None,
            types: IndexMap::new(),
            iri_to_type: HashMap::new(),
            prefixes: HashMap::new(),
        })
    }

    /// Load RDF data from Turtle format.
    pub fn load_turtle(&mut self, turtle: &str) -> Result<usize> {
        self.executor.load_turtle(turtle)
    }

    /// Add a prefix mapping.
    pub fn add_prefix(&mut self, prefix: &str, iri: &str) {
        self.prefixes.insert(prefix.to_string(), iri.to_string());
    }

    /// Generate GraphQL schema from loaded RDF data.
    pub fn generate_schema(&mut self) -> Result<()> {
        // Query for all classes
        let classes_query = r#"
            PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
            PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
            SELECT DISTINCT ?class WHERE {
                ?class a rdfs:Class .
            }
        "#;

        let class_results = self.executor.execute(classes_query)?;

        // Create types for each class
        if let crate::oxirs_executor::QueryResults::Select { bindings, .. } = class_results {
            for binding in bindings {
                if let Some(class_value) = binding.get("class") {
                    let class_iri = class_value.as_str();
                    let type_name = Self::iri_to_type_name(class_iri);
                    self.iri_to_type
                        .insert(class_iri.to_string(), type_name.clone());

                    let object_type = GraphQLObjectType::new(&type_name);
                    self.types.insert(type_name, object_type);
                }
            }
        }

        // Query for properties of each class
        for (iri, type_name) in &self.iri_to_type.clone() {
            let props_query = format!(
                r#"
                PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                SELECT DISTINCT ?prop WHERE {{
                    ?prop rdfs:domain <{}> .
                }}
            "#,
                iri
            );

            let prop_results = self.executor.execute(&props_query)?;

            if let crate::oxirs_executor::QueryResults::Select { bindings, .. } = prop_results {
                for binding in bindings {
                    if let Some(prop_value) = binding.get("prop") {
                        let prop_iri = prop_value.as_str();
                        let field_name = Self::iri_to_field_name(prop_iri);

                        let field = GraphQLField {
                            name: field_name,
                            field_type: GraphQLType::scalar("String"),
                            description: None,
                            arguments: Vec::new(),
                        };

                        if let Some(object_type) = self.types.get_mut(type_name) {
                            object_type.add_field(field);
                        }
                    }
                }
            }
        }

        // Build Query type
        let mut query_type = GraphQLObjectType::new("Query");

        // Add a query field for each type
        for (type_name, _) in &self.types {
            if type_name == "Query" {
                continue;
            }

            // Singular query
            let field = GraphQLField {
                name: Self::type_to_query_name(type_name),
                field_type: GraphQLType::object(type_name),
                description: Some(format!("Get a single {} by ID", type_name)),
                arguments: vec![GraphQLArgument {
                    name: "id".to_string(),
                    arg_type: GraphQLType::scalar("ID").non_null(),
                    default_value: None,
                }],
            };
            query_type.add_field(field);

            // Plural query
            let list_field = GraphQLField {
                name: format!("all{}s", type_name),
                field_type: GraphQLType::list(GraphQLType::object(type_name)),
                description: Some(format!("List all {}s", type_name)),
                arguments: vec![
                    GraphQLArgument {
                        name: "limit".to_string(),
                        arg_type: GraphQLType::scalar("Int"),
                        default_value: Some("10".to_string()),
                    },
                    GraphQLArgument {
                        name: "offset".to_string(),
                        arg_type: GraphQLType::scalar("Int"),
                        default_value: Some("0".to_string()),
                    },
                ],
            };
            query_type.add_field(list_field);
        }

        self.types.insert("Query".to_string(), query_type);

        // Generate SDL
        let mut schema = GraphQLSchema::new();
        for (_, obj_type) in &self.types {
            schema.add_type(obj_type.clone());
        }
        schema.query_type = Some("Query".to_string());

        self.schema = Some(schema);

        Ok(())
    }

    /// Execute a GraphQL query.
    pub fn execute_query(&self, query: &str) -> Result<serde_json::Value> {
        // Parse the GraphQL query (simplified - just handle basic queries)
        let query_trimmed = query.trim();

        // Extract operation (simplified parser)
        if query_trimmed.starts_with("query") || query_trimmed.starts_with('{') {
            // This is a query operation
            self.execute_graphql_query(query_trimmed)
        } else {
            Err(anyhow::anyhow!("Unsupported GraphQL operation"))
        }
    }

    /// Execute a parsed GraphQL query (simplified).
    fn execute_graphql_query(&self, query: &str) -> Result<serde_json::Value> {
        // Very simplified GraphQL parser - just extract field names
        // In production, you'd want to use a proper GraphQL parser

        let mut result = serde_json::Map::new();
        let data = serde_json::Map::new();

        // For now, return an empty result with the schema info
        result.insert("data".to_string(), serde_json::Value::Object(data));

        // If introspection query, return schema info
        if query.contains("__schema") || query.contains("__type") {
            if let Some(schema) = &self.schema {
                let mut schema_info = serde_json::Map::new();
                let types: Vec<serde_json::Value> = schema
                    .types
                    .keys()
                    .map(|k| serde_json::json!({"name": k}))
                    .collect();
                schema_info.insert("types".to_string(), serde_json::Value::Array(types));
                result.insert(
                    "data".to_string(),
                    serde_json::json!({"__schema": schema_info}),
                );
            }
        }

        Ok(serde_json::Value::Object(result))
    }

    /// Convert schema to TensorLogic symbol table.
    pub fn schema_to_symbol_table(&self) -> Result<SymbolTable> {
        let mut symbol_table = SymbolTable::new();

        // Add a default "Entity" domain for RDF entities
        // Using a large cardinality as placeholder (unknown actual count)
        let entity_domain = DomainInfo::new("Entity", usize::MAX);
        let _domain_added = symbol_table.add_domain(entity_domain);

        for (name, object_type) in &self.types {
            // Add type as a unary predicate
            let pred_info = PredicateInfo::new(name.clone(), vec!["Entity".to_string()]);
            let _result = symbol_table.add_predicate(pred_info);

            // Add fields as binary predicates
            for (field_name, _field) in &object_type.fields {
                let pred_name = format!("{}_{}", name, field_name);
                let field_pred_info =
                    PredicateInfo::new(pred_name, vec!["Entity".to_string(), "Entity".to_string()]);
                let _result = symbol_table.add_predicate(field_pred_info);
            }
        }

        Ok(symbol_table)
    }

    /// Get the generated GraphQL schema as SDL.
    pub fn get_schema_sdl(&self) -> Option<String> {
        self.schema.as_ref().map(|s: &GraphQLSchema| s.to_sdl())
    }

    /// Convert IRI to GraphQL type name.
    fn iri_to_type_name(iri: &str) -> String {
        let local = iri.split(['/', '#']).next_back().unwrap_or(iri);
        // Capitalize first letter
        let mut chars = local.chars();
        match chars.next() {
            None => String::new(),
            Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
        }
    }

    /// Convert IRI to GraphQL field name.
    fn iri_to_field_name(iri: &str) -> String {
        let local = iri.split(['/', '#']).next_back().unwrap_or(iri);
        // Keep as lowercase
        local.to_lowercase()
    }

    /// Convert type name to query field name.
    fn type_to_query_name(type_name: &str) -> String {
        // Lowercase first letter
        let mut chars = type_name.chars();
        match chars.next() {
            None => String::new(),
            Some(first) => first.to_lowercase().collect::<String>() + chars.as_str(),
        }
    }

    /// Convert a GraphQL query result to TensorLogic expression.
    pub fn result_to_tlexpr(&self, result: &serde_json::Value) -> Result<TLExpr> {
        // Convert JSON result to TLExpr
        match result {
            serde_json::Value::Object(obj) => {
                if let Some(data) = obj.get("data") {
                    self.json_to_tlexpr(data)
                } else {
                    Ok(TLExpr::pred("empty", vec![]))
                }
            }
            _ => Ok(TLExpr::pred("empty", vec![])),
        }
    }

    /// Convert JSON value to TensorLogic expression.
    fn json_to_tlexpr(&self, value: &serde_json::Value) -> Result<TLExpr> {
        match value {
            serde_json::Value::Null => Ok(TLExpr::pred("null", vec![])),
            serde_json::Value::Bool(b) => {
                if *b {
                    Ok(TLExpr::pred("true", vec![]))
                } else {
                    Ok(TLExpr::pred("false", vec![]))
                }
            }
            serde_json::Value::Number(n) => {
                Ok(TLExpr::pred("number", vec![Term::constant(n.to_string())]))
            }
            serde_json::Value::String(s) => Ok(TLExpr::pred("string", vec![Term::constant(s)])),
            serde_json::Value::Array(arr) => {
                let mut exprs = Vec::new();
                for item in arr {
                    exprs.push(self.json_to_tlexpr(item)?);
                }
                exprs
                    .into_iter()
                    .reduce(TLExpr::and)
                    .ok_or_else(|| anyhow::anyhow!("Empty array"))
            }
            serde_json::Value::Object(obj) => {
                let mut exprs = Vec::new();
                for (key, val) in obj {
                    let val_expr = self.json_to_tlexpr(val)?;
                    let pred = TLExpr::pred(key, vec![]);
                    exprs.push(TLExpr::and(pred, val_expr));
                }
                exprs
                    .into_iter()
                    .reduce(TLExpr::and)
                    .ok_or_else(|| anyhow::anyhow!("Empty object"))
            }
        }
    }
}

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

    #[test]
    fn test_bridge_creation() {
        let bridge = OxirsGraphQLBridge::new();
        assert!(bridge.is_ok());
    }

    #[test]
    fn test_graphql_type_scalar() {
        let t = GraphQLType::scalar("String");
        assert!(t.is_scalar);
        assert_eq!(t.to_sdl(), "String");
    }

    #[test]
    fn test_graphql_type_list() {
        let inner = GraphQLType::object("Person");
        let t = GraphQLType::list(inner);
        assert!(t.is_list);
        assert_eq!(t.to_sdl(), "[Person]");
    }

    #[test]
    fn test_graphql_type_non_null() {
        let t = GraphQLType::scalar("ID").non_null();
        assert!(t.is_non_null);
        assert_eq!(t.to_sdl(), "ID!");
    }

    #[test]
    fn test_object_type_creation() {
        let mut object_type = GraphQLObjectType::new("Person");
        object_type.add_field(GraphQLField {
            name: "name".to_string(),
            field_type: GraphQLType::scalar("String"),
            description: None,
            arguments: Vec::new(),
        });

        assert_eq!(object_type.name, "Person");
        assert!(object_type.fields.contains_key("name"));
    }

    #[test]
    fn test_iri_to_type_name() {
        assert_eq!(
            OxirsGraphQLBridge::iri_to_type_name("http://example.org/Person"),
            "Person"
        );
        assert_eq!(
            OxirsGraphQLBridge::iri_to_type_name("http://example.org/schema#person"),
            "Person"
        );
    }

    #[test]
    fn test_type_to_query_name() {
        assert_eq!(OxirsGraphQLBridge::type_to_query_name("Person"), "person");
        assert_eq!(
            OxirsGraphQLBridge::type_to_query_name("BookAuthor"),
            "bookAuthor"
        );
    }

    #[test]
    fn test_execute_introspection_query() {
        let mut bridge = OxirsGraphQLBridge::new().expect("Failed to create bridge");

        // Generate a minimal schema
        bridge
            .types
            .insert("Person".to_string(), GraphQLObjectType::new("Person"));
        bridge.schema = Some(GraphQLSchema {
            types: bridge.types.clone(),
            query_type: Some("Query".to_string()),
            mutation_type: None,
            sdl: String::new(),
        });

        let result = bridge.execute_query("{ __schema { types { name } } }");
        assert!(result.is_ok());
    }

    #[test]
    fn test_schema_to_symbol_table() {
        let mut bridge = OxirsGraphQLBridge::new().expect("Failed to create bridge");

        let mut person_type = GraphQLObjectType::new("Person");
        person_type.add_field(GraphQLField {
            name: "name".to_string(),
            field_type: GraphQLType::scalar("String"),
            description: None,
            arguments: Vec::new(),
        });
        bridge.types.insert("Person".to_string(), person_type);

        let result = bridge.schema_to_symbol_table();
        assert!(result.is_ok());
    }
}