oxirs-core 0.2.4

Core RDF and SPARQL functionality for OxiRS - native Rust implementation with zero dependencies
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
//! RDF store implementation with pluggable storage backends
//!
//! **Stability**: ✅ **Stable** - Core store APIs are production-ready.
//!
//! This module provides the primary interface for storing, querying, and manipulating RDF data.
//! It includes multiple storage backends optimized for different use cases.
//!
//! ## Overview
//!
//! The RDF store is the central component for managing RDF data. It provides:
//! - **Quad storage** - Store RDF quads (triples with named graphs)
//! - **Pattern matching** - Query data using SPARQL-like patterns
//! - **SPARQL execution** - Execute SPARQL queries directly
//! - **Persistence** - Optional disk-based storage with automatic saving
//! - **Named graphs** - Full support for RDF datasets with named graphs
//!
//! ## Core Types
//!
//! - **[`RdfStore`]** - Primary store implementation with pluggable backends
//! - **[`ConcreteStore`]** - Convenience wrapper (alias for RdfStore)
//! - **[`Store`]** - Trait defining the store interface
//! - **[`StorageBackend`]** - Enum of available storage backends
//!
//! ## Storage Backends
//!
//! ### Memory Backend
//! - Fast in-memory storage
//! - No persistence (data lost on shutdown)
//! - Good for: testing, temporary data, small datasets
//!
//! ### Persistent Backend
//! - Disk-backed storage with automatic save
//! - Data persisted as N-Quads format
//! - Good for: long-running applications, data preservation
//!
//! ### UltraMemory Backend
//! - High-performance with arena allocators
//! - Multi-index support (SPO, POS, OSP)
//! - Good for: large datasets, query-heavy workloads
//!
//! ## Examples
//!
//! ### Basic Store Creation and Usage
//!
//! ```rust
//! use oxirs_core::RdfStore;
//! use oxirs_core::model::{NamedNode, Triple, Literal};
//!
//! # fn main() -> Result<(), oxirs_core::OxirsError> {
//! // Create an in-memory store
//! let mut store = RdfStore::new()?;
//!
//! // Add a triple
//! let subject = NamedNode::new("http://example.org/alice")?;
//! let predicate = NamedNode::new("http://xmlns.com/foaf/0.1/name")?;
//! let object = Literal::new("Alice");
//!
//! let triple = Triple::new(subject, predicate, object);
//! store.insert_triple(triple)?;
//!
//! // Check the store
//! assert_eq!(store.len()?, 1);
//! assert!(!store.is_empty()?);
//! # Ok(())
//! # }
//! ```
//!
//! ### Persistent Storage
//!
//! ```rust,no_run
//! use oxirs_core::RdfStore;
//! use oxirs_core::model::{NamedNode, Triple, Literal};
//!
//! # fn main() -> Result<(), oxirs_core::OxirsError> {
//! // Open or create a persistent store
//! let mut store = RdfStore::open("./my_knowledge_base")?;
//!
//! // Add data - automatically saved to disk
//! let triple = Triple::new(
//!     NamedNode::new("http://example.org/resource")?,
//!     NamedNode::new("http://purl.org/dc/terms/title")?,
//!     Literal::new("My Resource"),
//! );
//! store.insert_triple(triple)?;
//!
//! // Data persists across restarts
//! drop(store);
//!
//! // Reopen - data is still there
//! let store = RdfStore::open("./my_knowledge_base")?;
//! assert_eq!(store.len()?, 1);
//! # Ok(())
//! # }
//! ```
//!
//! ### Pattern Matching Queries
//!
//! ```rust
//! use oxirs_core::RdfStore;
//! use oxirs_core::model::{NamedNode, Triple, Literal, Predicate};
//!
//! # fn main() -> Result<(), oxirs_core::OxirsError> {
//! # let mut store = RdfStore::new()?;
//! # let alice = NamedNode::new("http://example.org/alice")?;
//! # let bob = NamedNode::new("http://example.org/bob")?;
//! # let knows = NamedNode::new("http://xmlns.com/foaf/0.1/knows")?;
//! # let name = NamedNode::new("http://xmlns.com/foaf/0.1/name")?;
//! # store.insert_triple(Triple::new(alice.clone(), knows.clone(), bob.clone()))?;
//! # store.insert_triple(Triple::new(alice.clone(), name.clone(), Literal::new("Alice")))?;
//! # store.insert_triple(Triple::new(bob.clone(), name.clone(), Literal::new("Bob")))?;
//! // Query all triples with foaf:knows predicate
//! let knows_pred = Predicate::NamedNode(knows);
//! let results = store.query_triples(None, Some(&knows_pred), None)?;
//!
//! for triple in results {
//!     println!("{:?} knows {:?}", triple.subject(), triple.object());
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ### SPARQL Queries
//!
//! ```rust
//! use oxirs_core::RdfStore;
//!
//! # fn main() -> Result<(), oxirs_core::OxirsError> {
//! # let store = RdfStore::new()?;
//! // Execute a SPARQL SELECT query
//! let query = r#"
//!     PREFIX foaf: <http://xmlns.com/foaf/0.1/>
//!     SELECT ?person ?name WHERE {
//!         ?person foaf:name ?name .
//!     }
//! "#;
//!
//! let results = store.query(query)?;
//! println!("Found {} results", results.len());
//! # Ok(())
//! # }
//! ```
//!
//! ### Working with Named Graphs
//!
//! ```rust
//! use oxirs_core::RdfStore;
//! use oxirs_core::model::{NamedNode, Quad, GraphName, Literal};
//!
//! # fn main() -> Result<(), oxirs_core::OxirsError> {
//! # let mut store = RdfStore::new()?;
//! // Create a named graph
//! let graph = GraphName::NamedNode(NamedNode::new("http://example.org/graph1")?);
//!
//! // Add a quad to the named graph
//! let quad = Quad::new(
//!     NamedNode::new("http://example.org/subject")?,
//!     NamedNode::new("http://example.org/predicate")?,
//!     Literal::new("value"),
//!     graph,
//! );
//! store.insert_quad(quad)?;
//!
//! // Query the named graph
//! let graph_node = NamedNode::new("http://example.org/graph1")?;
//! let quads = store.graph_quads(Some(&graph_node))?;
//! println!("Graph contains {} quads", quads.len());
//!
//! // List all graphs
//! let graphs = store.named_graphs()?;
//! println!("Store has {} named graphs", graphs.len());
//! # Ok(())
//! # }
//! ```
//!
//! ### Bulk Operations for Performance
//!
//! ```rust
//! use oxirs_core::RdfStore;
//! use oxirs_core::model::{NamedNode, Quad, Literal, Triple, GraphName};
//!
//! # fn main() -> Result<(), oxirs_core::OxirsError> {
//! # let mut store = RdfStore::new()?;
//! // Prepare many quads
//! let mut quads = Vec::new();
//! for i in 0..10_000 {
//!     let subject = NamedNode::new(&format!("http://example.org/item{}", i))?;
//!     let predicate = NamedNode::new("http://example.org/value")?;
//!     let object = Literal::new(&i.to_string());
//!     let triple = Triple::new(subject, predicate, object);
//!     quads.push(Quad::from_triple(triple));
//! }
//!
//! // Bulk insert - much faster than individual inserts
//! let ids = store.bulk_insert_quads(quads)?;
//! println!("Bulk inserted {} quads", ids.len());
//! # Ok(())
//! # }
//! ```
//!
//! ### Loading Data from URLs
//!
//! ```rust,no_run
//! use oxirs_core::RdfStore;
//! use oxirs_core::model::NamedNode;
//!
//! # fn main() -> Result<(), oxirs_core::OxirsError> {
//! # let mut store = RdfStore::new()?;
//! // Load RDF data from a URL
//! let url = "https://example.org/data.ttl";
//! let graph = Some(NamedNode::new("http://example.org/imported-graph")?);
//!
//! let count = store.load_from_url(url, graph.as_ref())?;
//! println!("Loaded {} triples from {}", count, url);
//! # Ok(())
//! # }
//! ```
//!
//! ### Graph Management
//!
//! ```rust
//! use oxirs_core::RdfStore;
//! use oxirs_core::model::{NamedNode, GraphName};
//!
//! # fn main() -> Result<(), oxirs_core::OxirsError> {
//! # let mut store = RdfStore::new()?;
//! // Create an empty named graph
//! let graph_name = NamedNode::new("http://example.org/my-graph")?;
//! store.create_graph(Some(&graph_name))?;
//!
//! // Clear a specific graph
//! let graph = GraphName::NamedNode(graph_name.clone());
//! store.clear_graph(Some(&graph))?;
//!
//! // Drop a graph entirely
//! store.drop_graph(Some(&graph))?;
//!
//! // Clear all named graphs
//! let cleared = store.clear_named_graphs()?;
//! println!("Cleared {} quads from named graphs", cleared);
//!
//! // Clear everything
//! let total_cleared = store.clear_all()?;
//! println!("Cleared {} total quads", total_cleared);
//! # Ok(())
//! # }
//! ```
//!
//! ## Performance Characteristics
//!
//! | Operation | Memory | Persistent | UltraMemory |
//! |-----------|--------|------------|-------------|
//! | Insert (single) | Fast | Medium | Very Fast |
//! | Insert (bulk) | Fast | Medium | Ultra Fast |
//! | Query (pattern) | Fast | Fast | Very Fast |
//! | Query (SPARQL) | Fast | Fast | Fast |
//! | Persistence | None | Automatic | None |
//! | Memory Usage | Low | Low | Medium |
//! | Startup Time | Instant | Fast | Fast |
//!
//! ## Best Practices
//!
//! 1. **Use bulk operations** - For inserting many quads, use `bulk_insert_quads()`
//! 2. **Choose the right backend** - Use persistent storage for long-running apps
//! 3. **Use named graphs** - Organize data into logical graphs
//! 4. **Check return values** - Insert operations return `true` if the quad was new
//! 5. **Pattern matching first** - Try pattern matching before SPARQL for simple queries
//!
//! ## Error Handling
//!
//! Store operations return `Result<T, OxirsError>`. Common errors:
//! - **Store errors** - Internal storage failures
//! - **Query errors** - Invalid SPARQL or pattern queries
//! - **IO errors** - File system errors (persistent storage)
//! - **Parse errors** - Invalid IRI or term formats
//!
//! ## Thread Safety
//!
//! The `Store` trait is `Send + Sync`, allowing stores to be shared across threads:
//!
//! ```rust,no_run
//! use oxirs_core::RdfStore;
//! use std::sync::Arc;
//!
//! # fn main() -> Result<(), oxirs_core::OxirsError> {
//! let store = Arc::new(RdfStore::new()?);
//!
//! // Share store across threads
//! let store_clone = Arc::clone(&store);
//! std::thread::spawn(move || {
//!     // Use store in another thread
//!     let _ = store_clone.len();
//! });
//! # Ok(())
//! # }
//! ```
//!
//! ## Related Modules
//!
//! - [`crate::model`] - RDF data model types
//! - [`crate::parser`] - Parse RDF from files
//! - [`crate::serializer`] - Serialize RDF to files
//! - [`crate::query`] - SPARQL query execution

pub mod concrete;
pub mod storage;
pub mod types;

#[cfg(feature = "async-tokio")]
pub mod async_store;

pub use concrete::*;
pub use storage::*;
pub use types::*;

#[cfg(feature = "async-tokio")]
pub use async_store::AsyncRdfStore;

use crate::indexing::{IndexStats, MemoryUsage};
use crate::model::*;
use crate::parser::RdfFormat;
use crate::serializer::Serializer;
use crate::sparql::extract_and_expand_prefixes; // SPARQL execution engine
use crate::{OxirsError, Result};
use async_trait::async_trait;
use std::collections::HashSet;
use std::path::Path;
use std::sync::{Arc, RwLock};

/// Store trait for RDF operations
#[async_trait]
pub trait Store: Send + Sync {
    /// Insert a quad into the store
    fn insert_quad(&self, quad: Quad) -> Result<bool>;

    /// Remove a quad from the store  
    fn remove_quad(&self, quad: &Quad) -> Result<bool>;

    /// Find quads matching the given pattern
    fn find_quads(
        &self,
        subject: Option<&Subject>,
        predicate: Option<&Predicate>,
        object: Option<&Object>,
        graph_name: Option<&GraphName>,
    ) -> Result<Vec<Quad>>;

    /// Check if the store is ready for operations
    fn is_ready(&self) -> bool;

    /// Get the number of quads in the store
    fn len(&self) -> Result<usize>;

    /// Check if the store is empty
    fn is_empty(&self) -> Result<bool>;

    /// Query the store with SPARQL
    fn query(&self, sparql: &str) -> Result<OxirsQueryResults>;

    /// Prepare a SPARQL query for execution
    fn prepare_query(&self, sparql: &str) -> Result<PreparedQuery>;

    /// Insert a triple into the default graph
    fn insert_triple(&self, triple: Triple) -> Result<bool> {
        let quad = Quad::from_triple(triple);
        self.insert_quad(quad)
    }

    /// Insert a quad (compatibility method)
    fn insert(&self, quad: &Quad) -> Result<()> {
        self.insert_quad(quad.clone())?;
        Ok(())
    }

    /// Remove a quad (compatibility method)
    fn remove(&self, quad: &Quad) -> Result<bool> {
        self.remove_quad(quad)
    }

    /// Get all quads in the store
    fn quads(&self) -> Result<Vec<Quad>> {
        self.find_quads(None, None, None, None)
    }

    /// Get all named graphs
    fn named_graphs(&self) -> Result<Vec<NamedNode>> {
        // Default implementation - subclasses should override
        Ok(Vec::new())
    }

    /// Get all graphs
    fn graphs(&self) -> Result<Vec<NamedNode>> {
        self.named_graphs()
    }

    /// Get quads from named graphs only
    fn named_graph_quads(&self) -> Result<Vec<Quad>> {
        // Default implementation - get all quads except default graph
        let all_quads = self.quads()?;
        Ok(all_quads
            .into_iter()
            .filter(|quad| matches!(quad.graph_name(), GraphName::NamedNode(_)))
            .collect())
    }

    /// Get quads from the default graph only
    fn default_graph_quads(&self) -> Result<Vec<Quad>> {
        let default_graph = GraphName::DefaultGraph;
        self.find_quads(None, None, None, Some(&default_graph))
    }

    /// Get quads from a specific graph
    fn graph_quads(&self, graph: Option<&NamedNode>) -> Result<Vec<Quad>> {
        let graph_name = graph
            .map(|g| GraphName::NamedNode(g.clone()))
            .unwrap_or(GraphName::DefaultGraph);
        self.find_quads(None, None, None, Some(&graph_name))
    }

    /// Clear all data from all graphs
    fn clear_all(&self) -> Result<usize> {
        // Default implementation - not supported in trait
        Err(OxirsError::NotSupported(
            "clear_all requires mutable access".to_string(),
        ))
    }

    /// Clear all named graphs (but not the default graph)
    fn clear_named_graphs(&self) -> Result<usize> {
        // Default implementation - not supported in trait
        Err(OxirsError::NotSupported(
            "clear_named_graphs requires mutable access".to_string(),
        ))
    }

    /// Clear the default graph only
    fn clear_default_graph(&self) -> Result<usize> {
        // Default implementation - not supported in trait
        Err(OxirsError::NotSupported(
            "clear_default_graph requires mutable access".to_string(),
        ))
    }

    /// Clear a specific graph
    fn clear_graph(&self, _graph: Option<&GraphName>) -> Result<usize> {
        // Default implementation - not supported in trait
        Err(OxirsError::NotSupported(
            "clear_graph requires mutable access".to_string(),
        ))
    }

    /// Create a new graph (if it doesn't exist)
    fn create_graph(&self, _graph: Option<&NamedNode>) -> Result<()> {
        // Default implementation - not supported in trait
        Err(OxirsError::NotSupported(
            "create_graph requires mutable access".to_string(),
        ))
    }

    /// Drop a graph (remove the graph and all its quads)
    fn drop_graph(&self, _graph: Option<&GraphName>) -> Result<()> {
        // Default implementation - not supported in trait
        Err(OxirsError::NotSupported(
            "drop_graph requires mutable access".to_string(),
        ))
    }

    /// Load data from a URL into a graph
    fn load_from_url(&self, _url: &str, _graph: Option<&NamedNode>) -> Result<usize> {
        // Default implementation - not supported in trait
        Err(OxirsError::NotSupported(
            "load_from_url requires mutable access".to_string(),
        ))
    }

    /// Get all triples in the store (converts quads to triples)
    fn triples(&self) -> Result<Vec<Triple>> {
        let quads = self.find_quads(None, None, None, None)?;
        Ok(quads
            .into_iter()
            .map(|quad| {
                Triple::new(
                    quad.subject().clone(),
                    quad.predicate().clone(),
                    quad.object().clone(),
                )
            })
            .collect())
    }
}

/// Prepared SPARQL query
pub struct PreparedQuery {
    #[allow(dead_code)]
    sparql: String,
}

impl PreparedQuery {
    pub fn new(sparql: String) -> Self {
        Self { sparql }
    }

    /// Execute the prepared query
    pub fn exec(&self) -> Result<QueryResultsIterator> {
        // Simplified implementation - in reality this would parse and execute SPARQL
        Ok(QueryResultsIterator::empty())
    }
}

/// Iterator over query results
pub struct QueryResultsIterator {
    results: Vec<SolutionMapping>,
    index: usize,
}

impl QueryResultsIterator {
    pub fn empty() -> Self {
        Self {
            results: Vec::new(),
            index: 0,
        }
    }
}

impl Iterator for QueryResultsIterator {
    type Item = SolutionMapping;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.results.len() {
            let result = self.results[self.index].clone();
            self.index += 1;
            Some(result)
        } else {
            None
        }
    }
}

/// Solution mapping for SPARQL query results
#[derive(Debug, Clone, Default)]
pub struct SolutionMapping {
    bindings: std::collections::HashMap<String, Term>,
}

impl SolutionMapping {
    pub fn new() -> Self {
        Self {
            bindings: std::collections::HashMap::new(),
        }
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &Term)> {
        self.bindings.iter()
    }
}

/// Main RDF store implementation
#[derive(Debug)]
pub struct RdfStore {
    backend: StorageBackend,
}

impl RdfStore {
    /// Create a new ultra-high performance in-memory store
    pub fn new() -> Result<Self> {
        Ok(RdfStore {
            backend: StorageBackend::Memory(Arc::new(RwLock::new(MemoryStorage::new()))),
        })
    }

    /// Create a new legacy in-memory store for compatibility
    pub fn new_legacy() -> Result<Self> {
        Ok(RdfStore {
            backend: StorageBackend::Memory(Arc::new(RwLock::new(MemoryStorage::new()))),
        })
    }

    /// Create a new persistent store at the given path
    ///
    /// Loads existing data from disk if present, otherwise creates a new store.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path_buf = path.as_ref().to_path_buf();
        let data_file = path_buf.join("data.nq");

        let storage = if data_file.exists() {
            // Load existing data from disk
            Self::load_from_disk(&data_file)?
        } else {
            MemoryStorage::new()
        };

        Ok(RdfStore {
            backend: StorageBackend::Persistent(Arc::new(RwLock::new(storage)), path_buf),
        })
    }

    /// Load data from disk (N-Quads format)
    fn load_from_disk(data_file: &Path) -> Result<MemoryStorage> {
        use crate::format::{RdfFormat, RdfParser};
        use std::io::BufReader;

        let mut storage = MemoryStorage::new();

        if let Ok(file) = std::fs::File::open(data_file) {
            let reader = BufReader::new(file);
            let parser = RdfParser::new(RdfFormat::NQuads);

            for quad in parser.for_reader(reader).flatten() {
                storage.insert_quad(quad);
            }
        }

        Ok(storage)
    }

    /// Save data to disk (N-Quads format)
    fn save_to_disk(&self) -> Result<()> {
        if let StorageBackend::Persistent(storage, path) = &self.backend {
            use std::io::Write;

            let data_file = path.join("data.nq");

            // Ensure directory exists
            if let Some(parent) = data_file.parent() {
                std::fs::create_dir_all(parent)
                    .map_err(|e| OxirsError::Store(format!("Failed to create directory: {e}")))?;
            }

            let storage_guard = storage
                .read()
                .map_err(|e| OxirsError::Store(format!("Failed to acquire read lock: {e}")))?;

            // Create file
            let mut file = std::fs::File::create(&data_file)
                .map_err(|e| OxirsError::Store(format!("Failed to create data file: {e}")))?;

            // Write each quad as N-Quads line
            let serializer = Serializer::new(RdfFormat::NQuads);
            for quad in &storage_guard.quads {
                let line = serializer.serialize_quad_to_nquads(quad)?;
                writeln!(file, "{}", line)
                    .map_err(|e| OxirsError::Store(format!("Failed to write quad: {e}")))?;
            }
        }

        Ok(())
    }

    /// Insert a quad into the store
    pub fn insert_quad(&mut self, quad: Quad) -> Result<bool> {
        match &self.backend {
            StorageBackend::UltraMemory(index, _arena) => {
                // Check if quad already exists
                let existing = index.find_quads(
                    Some(quad.subject()),
                    Some(quad.predicate()),
                    Some(quad.object()),
                    Some(quad.graph_name()),
                );
                if !existing.is_empty() {
                    return Ok(false); // Quad already exists
                }

                let _id = index.insert_quad(&quad);
                Ok(true) // New quad inserted
            }
            StorageBackend::Memory(storage) => {
                let mut storage = storage
                    .write()
                    .map_err(|e| OxirsError::Store(format!("Failed to acquire write lock: {e}")))?;
                Ok(storage.insert_quad(quad))
            }
            StorageBackend::Persistent(storage, _) => {
                let mut storage = storage
                    .write()
                    .map_err(|e| OxirsError::Store(format!("Failed to acquire write lock: {e}")))?;
                let result = storage.insert_quad(quad);
                drop(storage); // Release lock before saving

                // Save to disk after insertion
                if result {
                    self.save_to_disk()?;
                }
                Ok(result)
            }
        }
    }

    /// Bulk insert quads for maximum performance
    pub fn bulk_insert_quads(&mut self, quads: Vec<Quad>) -> Result<Vec<u64>> {
        match &self.backend {
            StorageBackend::UltraMemory(index, _arena) => {
                let ids = index.bulk_insert_quads(&quads);
                Ok(ids)
            }
            _ => {
                // Fallback to individual inserts for legacy backend
                let mut ids = Vec::new();
                for quad in quads {
                    self.insert_quad(quad)?;
                    ids.push(0); // Dummy ID for legacy mode
                }
                Ok(ids)
            }
        }
    }

    /// Insert a triple into the default graph
    pub fn insert_triple(&mut self, triple: Triple) -> Result<bool> {
        self.insert_quad(Quad::from_triple(triple))
    }

    /// Insert a triple into the store (legacy string interface)
    pub fn insert_string_triple(
        &mut self,
        subject: &str,
        predicate: &str,
        object: &str,
    ) -> Result<bool> {
        let subject_node = NamedNode::new(subject)?;
        let predicate_node = NamedNode::new(predicate)?;
        let object_literal = Literal::new(object);

        let triple = Triple::new(subject_node, predicate_node, object_literal);
        self.insert_triple(triple)
    }

    /// Remove a quad from the store
    pub fn remove_quad(&mut self, quad: &Quad) -> Result<bool> {
        match &self.backend {
            StorageBackend::UltraMemory(index, _arena) => Ok(index.remove_quad(quad)),
            StorageBackend::Memory(storage) | StorageBackend::Persistent(storage, _) => {
                let mut storage = storage
                    .write()
                    .map_err(|e| OxirsError::Store(format!("Failed to acquire write lock: {e}")))?;
                Ok(storage.remove_quad(quad))
            }
        }
    }

    /// Check if a quad exists in the store
    pub fn contains_quad(&self, quad: &Quad) -> Result<bool> {
        match &self.backend {
            StorageBackend::Memory(storage) | StorageBackend::Persistent(storage, _) => {
                let storage = storage
                    .read()
                    .map_err(|e| OxirsError::Store(format!("Failed to acquire read lock: {e}")))?;
                Ok(storage.contains_quad(quad))
            }
            StorageBackend::UltraMemory(index, _) => {
                let results = index.find_quads(
                    Some(quad.subject()),
                    Some(quad.predicate()),
                    Some(quad.object()),
                    Some(quad.graph_name()),
                );
                Ok(!results.is_empty())
            }
        }
    }

    /// Query quads matching the given pattern
    ///
    /// None values act as wildcards matching any term.
    pub fn query_quads(
        &self,
        subject: Option<&Subject>,
        predicate: Option<&Predicate>,
        object: Option<&Object>,
        graph_name: Option<&GraphName>,
    ) -> Result<Vec<Quad>> {
        match &self.backend {
            StorageBackend::UltraMemory(index, _arena) => {
                let results = index.find_quads(subject, predicate, object, graph_name);
                Ok(results)
            }
            StorageBackend::Memory(storage) | StorageBackend::Persistent(storage, _) => {
                let storage = storage
                    .read()
                    .map_err(|e| OxirsError::Store(format!("Failed to acquire read lock: {e}")))?;
                Ok(storage.query_quads(subject, predicate, object, graph_name))
            }
        }
    }

    /// Query triples in the default graph matching the given pattern
    pub fn query_triples(
        &self,
        subject: Option<&Subject>,
        predicate: Option<&Predicate>,
        object: Option<&Object>,
    ) -> Result<Vec<Triple>> {
        let default_graph = GraphName::DefaultGraph;
        let quads = self.query_quads(subject, predicate, object, Some(&default_graph))?;
        Ok(quads.into_iter().map(|quad| quad.to_triple()).collect())
    }

    /// Get all quads in the store
    pub fn iter_quads(&self) -> Result<Vec<Quad>> {
        self.query_quads(None, None, None, None)
    }

    /// Get all triples in the default graph
    pub fn triples(&self) -> Result<Vec<Triple>> {
        self.query_triples(None, None, None)
    }

    /// Get the number of quads in the store
    pub fn len(&self) -> Result<usize> {
        match &self.backend {
            StorageBackend::UltraMemory(index, _arena) => Ok(index.len()),
            StorageBackend::Memory(storage) | StorageBackend::Persistent(storage, _) => {
                let storage = storage
                    .read()
                    .map_err(|e| OxirsError::Store(format!("Failed to acquire read lock: {e}")))?;
                Ok(storage.len())
            }
        }
    }

    /// Check if the store is empty
    pub fn is_empty(&self) -> Result<bool> {
        match &self.backend {
            StorageBackend::UltraMemory(index, _arena) => Ok(index.is_empty()),
            StorageBackend::Memory(storage) | StorageBackend::Persistent(storage, _) => {
                let storage = storage
                    .read()
                    .map_err(|e| OxirsError::Store(format!("Failed to acquire read lock: {e}")))?;
                Ok(storage.is_empty())
            }
        }
    }

    /// Get performance statistics (ultra-performance mode only)
    pub fn stats(&self) -> Option<Arc<IndexStats>> {
        match &self.backend {
            StorageBackend::UltraMemory(index, _arena) => Some(index.stats()),
            _ => None,
        }
    }

    /// Get memory usage statistics (ultra-performance mode only)
    pub fn memory_usage(&self) -> Option<MemoryUsage> {
        match &self.backend {
            StorageBackend::UltraMemory(index, arena) => {
                let mut usage = index.memory_usage();
                usage.arena_bytes = arena.allocated_bytes();
                Some(usage)
            }
            _ => None,
        }
    }

    /// Clear memory arena to reclaim memory (ultra-performance mode only)
    pub fn clear_arena(&self) {
        if let StorageBackend::UltraMemory(index, _arena) = &self.backend {
            index.clear_arena();
        }
    }

    /// Clear all data from the store
    pub fn clear(&mut self) -> Result<()> {
        match &self.backend {
            StorageBackend::UltraMemory(index, _arena) => {
                index.clear();
                Ok(())
            }
            StorageBackend::Memory(storage) | StorageBackend::Persistent(storage, _) => {
                let mut storage = storage
                    .write()
                    .map_err(|e| OxirsError::Store(format!("Failed to acquire write lock: {e}")))?;
                *storage = MemoryStorage::new();
                Ok(())
            }
        }
    }

    /// Extract PREFIX declarations and expand prefixed names in the query
    #[allow(dead_code)]
    fn extract_and_expand_prefixes(
        &self,
        sparql: &str,
    ) -> Result<(std::collections::HashMap<String, String>, String)> {
        extract_and_expand_prefixes(sparql)
    }

    /// Query the store with SPARQL (delegates to QueryExecutor)
    pub fn query(&self, sparql: &str) -> Result<OxirsQueryResults> {
        let executor = crate::sparql::QueryExecutor::new(&self.backend);
        executor.execute(sparql)
    }

    pub fn insert(&mut self, quad: &Quad) -> Result<()> {
        self.insert_quad(quad.clone())?;
        Ok(())
    }

    /// Remove a quad (compatibility alias for remove_quad)
    pub fn remove(&mut self, quad: &Quad) -> Result<bool> {
        self.remove_quad(quad)
    }

    /// Get all quads in the store
    pub fn quads(&self) -> Result<Vec<Quad>> {
        self.iter_quads()
    }

    /// Get all quads from named graphs only
    pub fn named_graph_quads(&self) -> Result<Vec<Quad>> {
        match &self.backend {
            StorageBackend::UltraMemory(index, _arena) => {
                let mut result = Vec::new();
                // Get all named graphs
                let graphs = self.named_graphs()?;
                for graph in graphs {
                    let graph_name = GraphName::NamedNode(graph);
                    let quads = index.find_quads(None, None, None, Some(&graph_name));
                    result.extend(quads);
                }
                Ok(result)
            }
            StorageBackend::Memory(storage) | StorageBackend::Persistent(storage, _) => {
                let storage = storage
                    .read()
                    .map_err(|e| OxirsError::Store(format!("Failed to acquire read lock: {e}")))?;
                let mut result = Vec::new();
                for graph in &storage.named_graphs {
                    let graph_name = GraphName::NamedNode(graph.clone());
                    let quads = storage.query_quads(None, None, None, Some(&graph_name));
                    result.extend(quads);
                }
                Ok(result)
            }
        }
    }

    /// Get all quads from the default graph only
    pub fn default_graph_quads(&self) -> Result<Vec<Quad>> {
        let default_graph = GraphName::DefaultGraph;
        self.query_quads(None, None, None, Some(&default_graph))
    }

    /// Get quads from a specific graph
    pub fn graph_quads(&self, graph: Option<&NamedNode>) -> Result<Vec<Quad>> {
        let graph_name = graph
            .map(|g| GraphName::NamedNode(g.clone()))
            .unwrap_or(GraphName::DefaultGraph);
        self.query_quads(None, None, None, Some(&graph_name))
    }

    /// Clear all data from all graphs
    pub fn clear_all(&mut self) -> Result<usize> {
        let count = self.len()?;
        self.clear()?;
        Ok(count)
    }

    /// Clear all named graphs (but not the default graph)
    pub fn clear_named_graphs(&mut self) -> Result<usize> {
        let mut deleted = 0;
        let graphs = self.named_graphs()?;

        for graph in graphs {
            let graph_name = GraphName::NamedNode(graph);
            deleted += self.clear_graph(Some(&graph_name))?;
        }

        Ok(deleted)
    }

    /// Clear the default graph only
    pub fn clear_default_graph(&mut self) -> Result<usize> {
        self.clear_graph(None)
    }

    /// Clear a specific graph
    pub fn clear_graph(&mut self, graph: Option<&GraphName>) -> Result<usize> {
        let graph_name = graph.cloned().unwrap_or(GraphName::DefaultGraph);
        let quads = self.query_quads(None, None, None, Some(&graph_name))?;
        let count = quads.len();

        for quad in quads {
            self.remove_quad(&quad)?;
        }

        Ok(count)
    }

    /// Get all graphs (including default if it contains data)
    pub fn graphs(&self) -> Result<Vec<NamedNode>> {
        let mut graphs = self.named_graphs()?;

        // Check if default graph has any data
        let default_graph = GraphName::DefaultGraph;
        let default_quads = self.query_quads(None, None, None, Some(&default_graph))?;
        if !default_quads.is_empty() {
            // Add a special marker for default graph
            if let Ok(default_marker) = NamedNode::new("urn:x-oxirs:default-graph") {
                graphs.push(default_marker);
            }
        }

        Ok(graphs)
    }

    /// Get all named graphs
    pub fn named_graphs(&self) -> Result<Vec<NamedNode>> {
        match &self.backend {
            StorageBackend::UltraMemory(index, _arena) => {
                // Get unique graph names from all quads
                let mut graphs = HashSet::new();
                let all_quads = index.find_quads(None, None, None, None);
                for quad in all_quads {
                    if let GraphName::NamedNode(graph) = quad.graph_name() {
                        graphs.insert(graph.clone());
                    }
                }
                Ok(graphs.into_iter().collect())
            }
            StorageBackend::Memory(storage) | StorageBackend::Persistent(storage, _) => {
                let storage = storage
                    .read()
                    .map_err(|e| OxirsError::Store(format!("Failed to acquire read lock: {e}")))?;
                Ok(storage.named_graphs.iter().cloned().collect())
            }
        }
    }

    /// Create a new graph (if it doesn't exist)
    pub fn create_graph(&mut self, graph: Option<&NamedNode>) -> Result<()> {
        if let Some(graph_name) = graph {
            match &self.backend {
                StorageBackend::Memory(storage) | StorageBackend::Persistent(storage, _) => {
                    let mut storage = storage.write().map_err(|e| {
                        OxirsError::Store(format!("Failed to acquire write lock: {e}"))
                    })?;
                    storage.named_graphs.insert(graph_name.clone());
                }
                StorageBackend::UltraMemory(_, _) => {
                    // Graphs are created implicitly when quads are added
                }
            }
        }
        Ok(())
    }

    /// Drop a graph (remove the graph and all its quads)
    pub fn drop_graph(&mut self, graph: Option<&GraphName>) -> Result<()> {
        self.clear_graph(graph)?;

        // Remove from named graphs set if it's a named graph
        if let Some(GraphName::NamedNode(graph_name)) = graph {
            match &self.backend {
                StorageBackend::Memory(storage) | StorageBackend::Persistent(storage, _) => {
                    let mut storage = storage.write().map_err(|e| {
                        OxirsError::Store(format!("Failed to acquire write lock: {e}"))
                    })?;
                    storage.named_graphs.remove(graph_name);
                }
                StorageBackend::UltraMemory(_, _) => {
                    // Graph is dropped implicitly when all quads are removed
                }
            }
        }

        Ok(())
    }

    /// Load data from a URL into a graph
    pub fn load_from_url(&mut self, url: &str, graph: Option<&NamedNode>) -> Result<usize> {
        use crate::parser::Parser;

        // Parse URL to extract file extension if present
        let url_path = url.split('?').next().unwrap_or(url);
        let extension = url_path
            .split('/')
            .next_back()
            .and_then(|filename| filename.rsplit('.').next());

        // Fetch data from URL using reqwest
        let runtime = tokio::runtime::Runtime::new()
            .map_err(|e| OxirsError::Store(format!("Failed to create runtime: {e}")))?;

        let (content, content_type) = runtime.block_on(async {
            let response = reqwest::get(url)
                .await
                .map_err(|e| OxirsError::Store(format!("Failed to fetch URL {url}: {e}")))?;

            if !response.status().is_success() {
                return Err(OxirsError::Store(format!(
                    "HTTP error {} when fetching {url}",
                    response.status()
                )));
            }

            // Get content type from headers
            let content_type = response
                .headers()
                .get("content-type")
                .and_then(|v| v.to_str().ok())
                .map(|s| s.split(';').next().unwrap_or(s).trim().to_string());

            // Get response body as text
            let text = response
                .text()
                .await
                .map_err(|e| OxirsError::Store(format!("Failed to read response body: {e}")))?;

            Ok::<_, OxirsError>((text, content_type))
        })?;

        // Detect RDF format from content type or file extension
        let format = Self::detect_format_from_url(&content_type, extension, &content)?;

        // Parse the content
        let parser = Parser::new(format);
        let quads = parser
            .parse_str_to_quads(&content)
            .map_err(|e| OxirsError::Store(format!("Failed to parse RDF data from {url}: {e}")))?;

        // Insert quads into the specified graph
        let target_graph = graph.cloned().map(GraphName::NamedNode);
        let mut inserted_count = 0;

        for quad in quads {
            // Override graph name if a target graph is specified
            let final_quad = if let Some(ref target) = target_graph {
                Quad::new(
                    quad.subject().clone(),
                    quad.predicate().clone(),
                    quad.object().clone(),
                    target.clone(),
                )
            } else {
                quad
            };

            if self.insert_quad(final_quad)? {
                inserted_count += 1;
            }
        }

        Ok(inserted_count)
    }

    /// Detect RDF format from content type, file extension, or content
    fn detect_format_from_url(
        content_type: &Option<String>,
        extension: Option<&str>,
        content: &str,
    ) -> Result<RdfFormat> {
        // Try to detect from content type first
        if let Some(ct) = content_type {
            let ct_lower = ct.to_lowercase();
            if let Some(format) = Self::format_from_media_type(&ct_lower) {
                return Ok(format);
            }
        }

        // Try to detect from file extension
        if let Some(ext) = extension {
            if let Some(format) = RdfFormat::from_extension(ext) {
                return Ok(format);
            }
        }

        // Try to detect from content
        if let Some(format) = crate::parser::detect_format_from_content(content) {
            return Ok(format);
        }

        // Default to N-Triples if we can't detect
        Err(OxirsError::Store(
            "Could not detect RDF format from URL, content type, or content".to_string(),
        ))
    }

    /// Map media type to RDF format
    fn format_from_media_type(media_type: &str) -> Option<RdfFormat> {
        match media_type {
            "text/turtle" | "application/x-turtle" => Some(RdfFormat::Turtle),
            "application/n-triples" | "text/plain" => Some(RdfFormat::NTriples),
            "application/trig" | "application/x-trig" => Some(RdfFormat::TriG),
            "application/n-quads" | "text/x-nquads" => Some(RdfFormat::NQuads),
            "application/rdf+xml" | "application/xml" | "text/xml" => Some(RdfFormat::RdfXml),
            "application/ld+json" | "application/json" => Some(RdfFormat::JsonLd),
            _ => None,
        }
    }

    /// Convert string to Subject term
    #[allow(dead_code)]
    fn string_to_subject(s: &str) -> Option<Subject> {
        if s.starts_with('<') && s.ends_with('>') {
            let iri = &s[1..s.len() - 1];
            NamedNode::new(iri).ok().map(Subject::NamedNode)
        } else if let Some(blank_id) = s.strip_prefix("_:") {
            BlankNode::new(blank_id).ok().map(Subject::BlankNode)
        } else {
            None
        }
    }

    /// Convert string to Predicate term
    #[allow(dead_code)]
    fn string_to_predicate(p: &str) -> Option<Predicate> {
        if p.starts_with('<') && p.ends_with('>') {
            let iri = &p[1..p.len() - 1];
            NamedNode::new(iri).ok().map(Predicate::NamedNode)
        } else {
            None
        }
    }

    /// Convert string to Object term
    #[allow(dead_code)]
    fn string_to_object(o: &str) -> Option<Object> {
        if o.starts_with('<') && o.ends_with('>') {
            let iri = &o[1..o.len() - 1];
            NamedNode::new(iri).ok().map(Object::NamedNode)
        } else if let Some(blank_id) = o.strip_prefix("_:") {
            BlankNode::new(blank_id).ok().map(Object::BlankNode)
        } else if o.starts_with('"') {
            // Simple literal parsing - more sophisticated parsing would be needed for real use
            let literal_content = &o[1..o.len() - 1];
            Some(Object::Literal(Literal::new(literal_content)))
        } else {
            None
        }
    }
}

impl Default for RdfStore {
    fn default() -> Self {
        RdfStore::new().expect("RdfStore::new() should not fail")
    }
}

// Implement the Store trait for RdfStore using interior mutability
#[async_trait]
impl Store for RdfStore {
    fn insert_quad(&self, quad: Quad) -> Result<bool> {
        let inserted = match &self.backend {
            StorageBackend::UltraMemory(index, _arena) => {
                // Check if quad already exists
                let existing = index.find_quads(
                    Some(quad.subject()),
                    Some(quad.predicate()),
                    Some(quad.object()),
                    Some(quad.graph_name()),
                );
                if !existing.is_empty() {
                    return Ok(false); // Quad already exists
                }

                let _id = index.insert_quad(&quad);
                true // New quad inserted
            }
            StorageBackend::Memory(storage) => {
                let mut storage = storage.write().map_err(|e| {
                    crate::OxirsError::Store(format!("Failed to acquire write lock: {e}"))
                })?;
                storage.insert_quad(quad)
            }
            StorageBackend::Persistent(storage, _) => {
                let mut storage = storage.write().map_err(|e| {
                    crate::OxirsError::Store(format!("Failed to acquire write lock: {e}"))
                })?;
                let result = storage.insert_quad(quad);
                drop(storage); // Release lock before saving

                // Save to disk after insertion
                if result {
                    self.save_to_disk()?;
                }
                result
            }
        };

        Ok(inserted)
    }

    fn remove_quad(&self, quad: &Quad) -> Result<bool> {
        match &self.backend {
            StorageBackend::UltraMemory(index, _arena) => Ok(index.remove_quad(quad)),
            StorageBackend::Memory(storage) | StorageBackend::Persistent(storage, _) => {
                let mut storage = storage.write().map_err(|e| {
                    crate::OxirsError::Store(format!("Failed to acquire write lock: {e}"))
                })?;
                Ok(storage.remove_quad(quad))
            }
        }
    }

    fn find_quads(
        &self,
        subject: Option<&Subject>,
        predicate: Option<&Predicate>,
        object: Option<&Object>,
        graph_name: Option<&GraphName>,
    ) -> Result<Vec<Quad>> {
        self.query_quads(subject, predicate, object, graph_name)
    }

    fn is_ready(&self) -> bool {
        true // Simple implementation
    }

    fn len(&self) -> Result<usize> {
        self.len()
    }

    fn is_empty(&self) -> Result<bool> {
        self.is_empty()
    }

    fn query(&self, sparql: &str) -> Result<OxirsQueryResults> {
        self.query(sparql)
    }

    fn prepare_query(&self, sparql: &str) -> Result<PreparedQuery> {
        Ok(PreparedQuery::new(sparql.to_string()))
    }
}