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
// Copyright 2019-2026 Apilium Technologies OÜ. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR Commercial
//! The core graph storage engine.
//!
//! `GraphStore` orchestrates operations between the storage backend and the in-memory triple indexes.
use crate::{
backends::StorageBackend, index::TripleIndex, Error, GraphStats, NodeId, Predicate, Result,
Triple, TripleId, TriplePattern,
};
use std::collections::HashSet;
use std::sync::{Arc, RwLock};
/// The main storage engine for the graph database.
///
/// `GraphStore` provides a transactional interface for inserting, deleting,
/// and querying triples, while managing the underlying storage backend and
/// in-memory indexes for efficient lookups.
pub struct GraphStore {
/// The pluggable storage backend (e.g., Sled, RocksDB, Memory).
backend: Box<dyn StorageBackend>,
/// The in-memory indexes (SPO, POS, OSP) for fast triple pattern matching.
index: Arc<RwLock<TripleIndex>>,
}
impl GraphStore {
/// Creates a new `GraphStore` with the given storage backend.
///
/// This will also build the initial in-memory indexes from the data
/// already present in the backend.
pub fn new(backend: Box<dyn StorageBackend>) -> Result<Self> {
let store = Self {
backend,
index: Arc::new(RwLock::new(TripleIndex::new())),
};
store.rebuild_indexes()?;
Ok(store)
}
/// Rebuilds the in-memory indexes from the storage backend.
fn rebuild_indexes(&self) -> Result<()> {
let mut index = self
.index
.write()
.map_err(|_| Error::Index("lock poisoned".into()))?;
index.clear();
for triple in self.backend.iter_all()? {
let id = triple.id();
index.insert(&triple, id);
}
Ok(())
}
/// Inserts a single `Triple` into the store.
///
/// # Errors
///
/// Returns an `Error::Duplicate` if a triple with the same content already exists.
pub fn insert(&self, triple: Triple) -> Result<TripleId> {
let id = triple.id();
// Check for duplicates
if self.backend.get(&id)?.is_some() {
return Err(Error::Duplicate(format!("triple {} already exists", id)));
}
// Store in backend
self.backend.put(&id, &triple)?;
// Update indexes
let mut index = self
.index
.write()
.map_err(|_| Error::Index("lock poisoned".into()))?;
index.insert(&triple, id.clone());
Ok(id)
}
/// Inserts a batch of `Triple`s into the store.
///
/// In batch mode, duplicates are silently skipped instead of returning an error.
/// Uses an atomic batch write when supported by the backend (e.g., Sled).
pub fn insert_batch(&self, triples: Vec<Triple>) -> Result<Vec<TripleId>> {
// Phase 1: Collect non-duplicate triples and their IDs
let mut new_triples: Vec<(TripleId, Triple)> = Vec::with_capacity(triples.len());
let mut all_ids = Vec::with_capacity(triples.len());
for triple in triples {
let id = triple.id();
if self.backend.get(&id)?.is_some() {
// Duplicate — keep the ID but don't re-insert
all_ids.push((id, true));
} else {
all_ids.push((id.clone(), false));
new_triples.push((id, triple));
}
}
// Phase 2: Atomic batch write to backend
if !new_triples.is_empty() {
let batch_items: Vec<(&TripleId, &Triple)> = new_triples
.iter()
.map(|(id, triple)| (id, triple))
.collect();
self.backend.apply_batch(&batch_items)?;
}
// Phase 3: Update indexes only after successful backend write
if !new_triples.is_empty() {
let mut index = self
.index
.write()
.map_err(|_| Error::Index("lock poisoned".into()))?;
for (id, triple) in &new_triples {
index.insert(triple, id.clone());
}
}
Ok(all_ids.into_iter().map(|(id, _)| id).collect())
}
/// Retrieves a `Triple` by its `TripleId`.
pub fn get(&self, id: &TripleId) -> Result<Option<Triple>> {
self.backend.get(id)
}
/// Deletes a `Triple` by its `TripleId`.
///
/// # Returns
///
/// `Ok(true)` if the triple was found and deleted, `Ok(false)` otherwise.
pub fn delete(&self, id: &TripleId) -> Result<bool> {
// Get the triple first to update indexes
if let Some(triple) = self.backend.get(id)? {
self.backend.delete(id)?;
let mut index = self
.index
.write()
.map_err(|_| Error::Index("lock poisoned".into()))?;
index.remove(&triple, id);
Ok(true)
} else {
Ok(false)
}
}
/// Finds all triples that match a given `TriplePattern`.
///
/// The store will attempt to use the most efficient index based on the
/// components specified in the pattern.
pub fn find(&self, pattern: TriplePattern) -> Result<Vec<Triple>> {
let index = self
.index
.read()
.map_err(|_| Error::Index("lock poisoned".into()))?;
// Determine the best index to use based on pattern
let ids = match (&pattern.subject, &pattern.predicate, &pattern.object) {
// Exact match - use SPO with all components
(Some(s), Some(p), Some(o)) => {
if let Some(id) = index.find_exact(s, p, o) {
vec![id]
} else {
vec![]
}
}
// Subject + Predicate - use SPO
(Some(s), Some(p), None) => index.find_by_subject_predicate(s, p),
// Predicate + Object - use POS
(None, Some(p), Some(o)) => index.find_by_predicate_object(p, o),
// Object + Subject - use OSP
(Some(s), None, Some(o)) => index.find_by_object_subject(o, s),
// Subject only - use SPO
(Some(s), None, None) => index.find_by_subject(s),
// Predicate only - use POS
(None, Some(p), None) => index.find_by_predicate(p),
// Object only - use OSP
(None, None, Some(o)) => index.find_by_object(o),
// Wildcard - scan all
(None, None, None) => {
return self.backend.iter_all();
}
};
// Fetch full triples from the backend using the retrieved IDs.
let mut triples = Vec::with_capacity(ids.len());
for id in ids {
if let Some(triple) = self.backend.get(&id)? {
triples.push(triple);
}
}
Ok(triples)
}
/// Returns `true` if a triple with the same content already exists in the store.
pub fn contains(&self, triple: &Triple) -> Result<bool> {
let id = triple.id();
Ok(self.backend.get(&id)?.is_some())
}
/// Traverses the graph starting from a node and following a set of predicates.
pub fn traverse(&self, start: &NodeId, predicates: &[Predicate]) -> Result<Vec<NodeId>> {
let mut visited = HashSet::new();
let mut result = Vec::new();
let mut frontier = vec![start.clone()];
visited.insert(start.clone());
while let Some(current) = frontier.pop() {
// Find all outgoing edges
let triples = if predicates.is_empty() {
// Follow all predicates
self.find(TriplePattern::subject(current.clone()))?
} else {
// Follow specific predicates
let mut all_triples = Vec::new();
for pred in predicates {
let pattern =
TriplePattern::subject(current.clone()).with_predicate(pred.clone());
all_triples.extend(self.find(pattern)?);
}
all_triples
};
// Collect connected nodes
for triple in triples {
if let Some(node) = triple.object.as_node() {
if !visited.contains(node) {
visited.insert(node.clone());
result.push(node.clone());
frontier.push(node.clone());
}
}
}
}
Ok(result)
}
/// Returns the total number of triples in the store.
pub fn count(&self) -> usize {
self.backend.count()
}
/// Access the underlying storage backend as `Any` for downcasting
/// (e.g. to reach the Sled `Db` for the shared persistent DAG).
pub fn backend_as_any(&self) -> &dyn std::any::Any {
self.backend.as_any()
}
/// Flushes any buffered writes to the underlying storage backend.
///
/// For persistent backends (e.g., Sled), this ensures all data is
/// written to disk. For in-memory backends, this is a no-op.
pub fn flush(&self) -> Result<()> {
self.backend.flush()
}
/// Returns statistics about the graph, such as triple and node counts.
pub fn stats(&self) -> GraphStats {
let index = self.index.read().ok();
GraphStats {
triple_count: self.count(),
subject_count: index.as_ref().map(|i| i.subject_count()).unwrap_or(0),
predicate_count: index.as_ref().map(|i| i.predicate_count()).unwrap_or(0),
object_count: index.as_ref().map(|i| i.object_count()).unwrap_or(0),
storage_bytes: self.backend.size_bytes(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::backends::memory::MemoryBackend;
use crate::Value;
fn test_store() -> GraphStore {
let backend = MemoryBackend::new();
GraphStore::new(Box::new(backend)).unwrap()
}
#[test]
fn test_insert_and_get() {
let store = test_store();
let triple = Triple::new(
NodeId::named("user:alice"),
Predicate::named("has_name"),
Value::literal("Alice"),
);
let id = store.insert(triple.clone()).unwrap();
let retrieved = store.get(&id).unwrap().unwrap();
assert_eq!(retrieved.subject, triple.subject);
assert_eq!(retrieved.predicate, triple.predicate);
assert_eq!(retrieved.object, triple.object);
}
#[test]
fn test_duplicate_insert() {
let store = test_store();
let triple = Triple::new(
NodeId::named("a"),
Predicate::named("p"),
Value::literal("b"),
);
store.insert(triple.clone()).unwrap();
let result = store.insert(triple);
assert!(matches!(result, Err(Error::Duplicate(_))));
}
#[test]
fn test_find_by_subject() {
let store = test_store();
store
.insert(Triple::new(
NodeId::named("user:alice"),
Predicate::named("has_name"),
Value::literal("Alice"),
))
.unwrap();
store
.insert(Triple::new(
NodeId::named("user:alice"),
Predicate::named("has_age"),
Value::integer(30),
))
.unwrap();
store
.insert(Triple::new(
NodeId::named("user:bob"),
Predicate::named("has_name"),
Value::literal("Bob"),
))
.unwrap();
let alice_triples = store
.find(TriplePattern::subject(NodeId::named("user:alice")))
.unwrap();
assert_eq!(alice_triples.len(), 2);
}
#[test]
fn test_delete() {
let store = test_store();
let triple = Triple::new(
NodeId::named("a"),
Predicate::named("p"),
Value::literal("b"),
);
let id = store.insert(triple).unwrap();
assert_eq!(store.count(), 1);
let deleted = store.delete(&id).unwrap();
assert!(deleted);
assert_eq!(store.count(), 0);
}
#[test]
fn test_traverse() {
let store = test_store();
// Create a simple graph: alice -> bob -> charlie
store
.insert(Triple::link(
NodeId::named("user:alice"),
Predicate::named("knows"),
NodeId::named("user:bob"),
))
.unwrap();
store
.insert(Triple::link(
NodeId::named("user:bob"),
Predicate::named("knows"),
NodeId::named("user:charlie"),
))
.unwrap();
let reachable = store
.traverse(&NodeId::named("user:alice"), &[Predicate::named("knows")])
.unwrap();
assert_eq!(reachable.len(), 2);
assert!(reachable.contains(&NodeId::named("user:bob")));
assert!(reachable.contains(&NodeId::named("user:charlie")));
}
}