Skip to main content

oxirs_core/
lib.rs

1//! # OxiRS Core - RDF and SPARQL Foundation
2//!
3//! [![Version](https://img.shields.io/badge/version-0.1.0-blue)](https://github.com/cool-japan/oxirs/releases)
4//! [![docs.rs](https://docs.rs/oxirs-core/badge.svg)](https://docs.rs/oxirs-core)
5//!
6//! **Status**: Production Release (v0.1.0)
7//! **Stability**: Public APIs are stabilizing. Production-ready for RDF/SPARQL core operations.
8//!
9//! ## Overview
10//!
11//! `oxirs-core` is a high-performance, zero-dependency Rust-native RDF data model and SPARQL foundation
12//! for the OxiRS semantic web platform. It provides the fundamental types, traits, and operations that
13//! all other OxiRS crates build upon.
14//!
15//! This crate is designed for:
16//! - Building semantic web applications in Rust
17//! - Processing large-scale knowledge graphs with minimal memory overhead
18//! - Developing SPARQL query engines and triple stores
19//! - Creating RDF-based data pipelines and transformations
20//!
21//! ## Key Features
22//!
23//! ### Core RDF Support
24//! - **RDF 1.2 Compliance** - Full implementation of the RDF 1.2 data model
25//! - **Multiple Serialization Formats** - Support for Turtle, N-Triples, TriG, N-Quads, RDF/XML, JSON-LD
26//! - **Named Graphs** - Full quad support with named graph management
27//! - **RDF-star** - Support for quoted triples (statement reification)
28//!
29//! ### Performance & Scalability
30//! - **Memory Efficiency** - Arena-based allocators and optimized data structures
31//! - **Concurrent Operations** - Lock-free data structures for high-throughput workloads
32//! - **Parallel Processing** - SIMD and multi-threaded query execution
33//! - **Zero-Copy Parsing** - Streaming parsers with minimal allocations
34//!
35//! ### SPARQL Foundation
36//! - **SPARQL 1.1 Query** - SELECT, CONSTRUCT, ASK, DESCRIBE queries
37//! - **SPARQL 1.1 Update** - INSERT, DELETE, LOAD, CLEAR operations
38//! - **SPARQL 1.2 Features** - Enhanced property paths, aggregations, and functions
39//! - **Federation** - SERVICE clause support for distributed queries
40//!
41//! ### Storage & Persistence
42//! - **Pluggable Backends** - In-memory and disk-based storage options
43//! - **Persistent Storage** - Automatic N-Quads serialization for durability
44//! - **Indexed Access** - Multi-index support (SPO, POS, OSP) for fast pattern matching
45//! - **Transaction Support** - ACID-compliant transactions for data integrity
46//!
47//! ### Production Features
48//! - **Monitoring & Metrics** - Built-in performance instrumentation via SciRS2
49//! - **Error Handling** - Rich error types with context and suggestions
50//! - **Health Checks** - Circuit breakers and resource quotas
51//! - **Benchmarking** - Comprehensive benchmark suite for performance validation
52//!
53//! ## Quick Start
54//!
55//! ### Creating a Store and Adding Data
56//!
57//! ```rust,no_run
58//! use oxirs_core::RdfStore;
59//! use oxirs_core::model::{NamedNode, Triple, Literal};
60//!
61//! # fn example() -> Result<(), oxirs_core::OxirsError> {
62//! // Create an in-memory RDF store
63//! let mut store = RdfStore::new()?;
64//!
65//! // Create RDF terms
66//! let alice = NamedNode::new("http://example.org/alice")?;
67//! let knows = NamedNode::new("http://xmlns.com/foaf/0.1/knows")?;
68//! let bob = NamedNode::new("http://example.org/bob")?;
69//! let name = NamedNode::new("http://xmlns.com/foaf/0.1/name")?;
70//!
71//! // Insert triples
72//! store.insert_triple(Triple::new(alice.clone(), knows, bob))?;
73//! store.insert_triple(Triple::new(alice, name, Literal::new("Alice")))?;
74//!
75//! println!("Store contains {} triples", store.len()?);
76//! # Ok(())
77//! # }
78//! ```
79//!
80//! ### Querying with Pattern Matching
81//!
82//! ```rust,no_run
83//! use oxirs_core::RdfStore;
84//! use oxirs_core::model::{NamedNode, Subject, Predicate};
85//!
86//! # fn query_example() -> Result<(), oxirs_core::OxirsError> {
87//! # let mut store = RdfStore::new()?;
88//! // Query all triples with a specific predicate
89//! let knows = NamedNode::new("http://xmlns.com/foaf/0.1/knows")?;
90//! let predicate = Predicate::NamedNode(knows);
91//!
92//! let triples = store.query_triples(None, Some(&predicate), None)?;
93//! for triple in triples {
94//!     println!("{:?} knows {:?}", triple.subject(), triple.object());
95//! }
96//! # Ok(())
97//! # }
98//! ```
99//!
100//! ### Executing SPARQL Queries
101//!
102//! ```rust,no_run
103//! use oxirs_core::RdfStore;
104//!
105//! # fn sparql_example() -> Result<(), oxirs_core::OxirsError> {
106//! # let store = RdfStore::new()?;
107//! // Execute a SPARQL SELECT query
108//! let query = r#"
109//!     PREFIX foaf: <http://xmlns.com/foaf/0.1/>
110//!     SELECT ?name WHERE {
111//!         ?person foaf:name ?name .
112//!     }
113//! "#;
114//!
115//! let results = store.query(query)?;
116//! println!("Query returned {} results", results.len());
117//! # Ok(())
118//! # }
119//! ```
120//!
121//! ### Loading Data from Files
122//!
123//! ```rust,no_run
124//! use oxirs_core::RdfStore;
125//! use oxirs_core::parser::{Parser, RdfFormat};
126//! use std::fs;
127//!
128//! # fn load_example() -> Result<(), oxirs_core::OxirsError> {
129//! # let mut store = RdfStore::new()?;
130//! // Load RDF data from a Turtle file
131//! let content = fs::read_to_string("data.ttl")
132//!     .map_err(|e| oxirs_core::OxirsError::Io(e.to_string()))?;
133//!
134//! let parser = Parser::new(RdfFormat::Turtle);
135//! let quads = parser.parse_str_to_quads(&content)?;
136//!
137//! for quad in quads {
138//!     store.insert_quad(quad)?;
139//! }
140//!
141//! println!("Loaded {} quads from file", store.len()?);
142//! # Ok(())
143//! # }
144//! ```
145//!
146//! ### Persistent Storage
147//!
148//! ```rust,no_run
149//! use oxirs_core::RdfStore;
150//! use oxirs_core::model::{NamedNode, Triple, Literal};
151//!
152//! # fn persistent_example() -> Result<(), oxirs_core::OxirsError> {
153//! // Create a persistent store (data saved to disk)
154//! let mut store = RdfStore::open("./my_rdf_store")?;
155//!
156//! // Add data - automatically persisted
157//! let subject = NamedNode::new("http://example.org/resource")?;
158//! let predicate = NamedNode::new("http://purl.org/dc/terms/title")?;
159//! let object = Literal::new("My Resource");
160//!
161//! store.insert_triple(Triple::new(subject, predicate, object))?;
162//!
163//! // Data is automatically saved to disk on modifications
164//! println!("Data persisted to disk");
165//! # Ok(())
166//! # }
167//! ```
168//!
169//! ## Advanced Features
170//!
171//! ### Named Graphs (Quads)
172//!
173//! ```rust,no_run
174//! use oxirs_core::RdfStore;
175//! use oxirs_core::model::{NamedNode, Quad, GraphName, Literal};
176//!
177//! # fn quads_example() -> Result<(), oxirs_core::OxirsError> {
178//! # let mut store = RdfStore::new()?;
179//! // Create a quad with a named graph
180//! let graph = GraphName::NamedNode(NamedNode::new("http://example.org/graph1")?);
181//! let subject = NamedNode::new("http://example.org/subject")?;
182//! let predicate = NamedNode::new("http://example.org/predicate")?;
183//! let object = Literal::new("value");
184//!
185//! let quad = Quad::new(subject, predicate, object, graph);
186//! store.insert_quad(quad)?;
187//!
188//! // Query specific graph
189//! let graph_node = NamedNode::new("http://example.org/graph1")?;
190//! let quads = store.graph_quads(Some(&graph_node))?;
191//! println!("Graph contains {} quads", quads.len());
192//! # Ok(())
193//! # }
194//! ```
195//!
196//! ### Bulk Operations for Performance
197//!
198//! ```rust,ignore
199//! use oxirs_core::RdfStore;
200//! use oxirs_core::model::{NamedNode, Quad, Literal};
201//!
202//! # fn bulk_example() -> Result<(), oxirs_core::OxirsError> {
203//! # let mut store = RdfStore::new()?;
204//! // Prepare many quads for bulk insert
205//! let mut quads = Vec::new();
206//! for i in 0..1000 {
207//!     let subject = NamedNode::new(&format!("http://example.org/item{}", i))?;
208//!     let predicate = NamedNode::new("http://example.org/value")?;
209//!     let object = Literal::new(&i.to_string());
210//!     quads.push(Quad::from_triple(Triple::new(subject, predicate, object)));
211//! }
212//!
213//! // Bulk insert for better performance
214//! let ids = store.bulk_insert_quads(quads)?;
215//! println!("Inserted {} quads with IDs: {:?}", ids.len(), &ids[..5]);
216//! # Ok(())
217//! # }
218//! ```
219//!
220//! ## Module Organization
221//!
222//! - [`model`] - Core RDF data model types (IRI, Literal, Blank Node, Triple, Quad)
223//! - [`rdf_store`] - RDF store implementations with pluggable storage backends
224//! - [`parser`] - RDF parsers for multiple serialization formats
225//! - [`serializer`] - RDF serializers for exporting data
226//! - [`query`] - SPARQL query algebra and execution engine
227//! - [`sparql`] - SPARQL query processing and federation
228//! - [`storage`] - Storage backends (memory, disk, columnar)
229//! - [`indexing`] - Multi-index structures for fast pattern matching
230//! - [`concurrent`] - Lock-free data structures for concurrent access
231//! - [`optimization`] - Query optimization and execution planning
232//! - [`federation`] - SPARQL federation for distributed queries
233//! - [`production`] - Production features (monitoring, health checks, circuit breakers)
234//!
235//! ## Feature Flags
236//!
237//! - `serde` - Enable serialization support (default)
238//! - `parallel` - Enable parallel processing with rayon (default)
239//! - `simd` - Enable SIMD optimizations for x86_64
240//! - `async` - Enable async I/O support
241//! - `rocksdb` - Enable RocksDB storage backend
242//! - `rdf-star` - Enable RDF-star (quoted triples) support
243//! - `sparql-12` - Enable SPARQL 1.2 features
244//!
245//! ## Performance Tips
246//!
247//! 1. **Use bulk operations** - `bulk_insert_quads()` is faster than individual inserts
248//! 2. **Choose the right backend** - UltraMemory backend for maximum performance
249//! 3. **Enable parallel feature** - Leverage multi-core CPUs for query execution
250//! 4. **Use indexed queries** - Pattern matching benefits from multi-index structures
251//! 5. **Profile with built-in metrics** - Use SciRS2 metrics for bottleneck identification
252//!
253//! ## API Stability
254//!
255//! As of Beta 1 (v0.1.0):
256//! - **Stable APIs**: Core RDF model types (`NamedNode`, `Literal`, `Triple`, `Quad`)
257//! - **Stable APIs**: Store operations (`RdfStore`, `insert`, `query`, `remove`)
258//! - **Stable APIs**: Parser and serializer interfaces
259//! - **Unstable APIs**: Advanced optimization features (may change)
260//! - **Experimental**: Consciousness, molecular, and quantum modules
261//!
262//! See [MIGRATION_GUIDE.md](../MIGRATION_GUIDE.md) for migration from alpha versions.
263//!
264//! ## Architecture
265//!
266//! For detailed architecture documentation, see [ARCHITECTURE.md](../ARCHITECTURE.md).
267//!
268//! ## Examples
269//!
270//! More examples are available in the `examples/` directory:
271//! - `basic_store.rs` - Basic store operations
272//! - `sparql_query.rs` - SPARQL query examples
273//! - `persistent_store.rs` - Persistent storage usage
274//! - `bulk_loading.rs` - High-performance bulk data loading
275//! - `federation.rs` - Federated SPARQL queries
276
277pub mod ai;
278pub mod concurrent;
279pub mod consciousness; // Consciousness-inspired computing for intuitive query optimization
280pub mod distributed;
281pub mod federation;
282pub mod format;
283pub mod graph;
284pub mod indexing;
285pub mod interning;
286pub mod io;
287pub mod model;
288pub mod molecular;
289pub mod optimization;
290pub mod parser;
291pub mod production;
292pub mod quantum;
293pub mod query;
294pub mod rdf_store;
295pub mod serializer;
296pub mod sparql; // SPARQL query processing modules
297pub mod storage;
298pub mod store;
299pub mod transaction;
300pub mod vocab;
301// pub mod config;
302pub mod jsonld; // Re-enabled after fixing StringInterner method calls
303pub mod oxigraph_compat;
304pub mod rdfxml; // Oxigraph compatibility layer
305
306// Core abstractions for OxiRS ecosystem
307pub mod error;
308#[cfg(feature = "parallel")]
309pub mod parallel;
310pub mod platform;
311#[cfg(feature = "simd")]
312pub mod simd;
313pub mod simd_triple_matching; // SIMD-optimized triple pattern matching using SciRS2
314pub mod zero_copy_rdf; // Zero-copy RDF operations using SciRS2-core memory management
315
316// Query optimization enhancements
317pub mod cache; // Core-level query result cache with LRU and delta invalidation
318pub mod data_factory;
319pub mod named_graph; // Named Graph Management API (Jena Dataset-compatible)
320pub mod optimizer; // Runtime feedback-based adaptive query optimization
321pub mod provenance; // W3C PROV-O ontology support for RDF data provenance tracking
322pub mod rdf;
323pub mod stability; // API stability markers and LTS compatibility matrix
324pub mod statistics; // Equi-depth histogram statistics for cardinality estimation
325pub mod view; // Incremental view maintenance with delta propagation // W3C DataFactory API for programmatic RDF term construction
326pub mod views; // Incremental view maintenance (new: DeltaChange-based API with IncrementalViewMaintainer) // RDF dataset utilities (diff, patch)
327
328// Re-export core types for convenience
329pub use model::*;
330pub use rdf_store::{ConcreteStore, RdfStore, Store};
331pub use transaction::{
332    AcidTransaction, IsolationLevel, TransactionId, TransactionManager, TransactionState,
333};
334
335/// Core error type for OxiRS operations
336#[derive(Debug, Clone, thiserror::Error)]
337pub enum OxirsError {
338    #[error("Store error: {0}")]
339    Store(String),
340    #[error("Query error: {0}")]
341    Query(String),
342    #[error("Parse error: {0}")]
343    Parse(String),
344    #[error("Serialization error: {0}")]
345    Serialize(String),
346    #[error("IO error: {0}")]
347    Io(String),
348    #[error("Concurrency error: {0}")]
349    ConcurrencyError(String),
350    #[error("Quantum computing error: {0}")]
351    QuantumError(String),
352    #[error("Molecular optimization error: {0}")]
353    MolecularError(String),
354    #[error("Neural-symbolic fusion error: {0}")]
355    NeuralSymbolicError(String),
356    #[error("Operation not supported: {0}")]
357    NotSupported(String),
358    #[error("Update error: {0}")]
359    Update(String),
360    #[error("Federation error: {0}")]
361    Federation(String),
362}
363
364impl From<std::io::Error> for OxirsError {
365    fn from(err: std::io::Error) -> Self {
366        OxirsError::Io(err.to_string())
367    }
368}
369
370// Additional error conversions
371impl From<oxicode::Error> for OxirsError {
372    fn from(err: oxicode::Error) -> Self {
373        OxirsError::Serialize(err.to_string())
374    }
375}
376
377impl From<serde_json::Error> for OxirsError {
378    fn from(err: serde_json::Error) -> Self {
379        OxirsError::Serialize(err.to_string())
380    }
381}
382
383#[cfg(feature = "rocksdb")]
384impl From<rocksdb::Error> for OxirsError {
385    fn from(err: rocksdb::Error) -> Self {
386        OxirsError::Store(err.to_string())
387    }
388}
389
390// Note: DataFusion, Arrow, and Parquet error conversions removed
391// Add these features to Cargo.toml if these integrations are needed
392
393impl From<std::time::SystemTimeError> for OxirsError {
394    fn from(err: std::time::SystemTimeError) -> Self {
395        OxirsError::Io(format!("System time error: {err}"))
396    }
397}
398
399/// Result type alias for OxiRS operations
400pub type Result<T> = std::result::Result<T, OxirsError>;
401
402/// Version information for OxiRS Core
403pub const VERSION: &str = env!("CARGO_PKG_VERSION");
404
405/// Initialize OxiRS Core with default configuration
406pub fn init() -> Result<()> {
407    tracing::info!("Initializing OxiRS Core v{}", VERSION);
408    Ok(())
409}