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
//! Basic graph operations for creating and reading nodes and edges.
//!
//! Contains convenience methods for the most common graph operations.
use crate::api::transaction::WriteOps;
use crate::core::error::{Result, ResultExt};
use crate::core::graph::{Edge, Node};
use crate::core::id::{EdgeId, NodeId};
use crate::core::property::{PropertyMap, PropertyValue};
use crate::db::AletheiaDB;
use crate::storage::current::{IncomingEdgesIter, OutgoingEdgesIter};
impl AletheiaDB {
/// Create a node with the given label and properties.
///
/// This is a convenience method that internally uses a write transaction.
/// For multiple operations, prefer using `write()` or `write_transaction()`.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::{AletheiaDB, PropertyMapBuilder};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// let node_id = db.create_node(
/// "Person",
/// PropertyMapBuilder::new()
/// .insert("name", "Alice")
/// .build()
/// )?;
/// # Ok(())
/// # }
/// ```
///
/// # See Also
///
/// * [`write`](Self::write) - For batched write operations.
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn create_node(&self, label: &str, properties: PropertyMap) -> Result<NodeId> {
self.write(|tx| tx.create_node(label, properties))
}
/// Create an edge between two nodes.
///
/// This is a convenience method that internally uses a write transaction.
/// For multiple operations, prefer using `write()` or `write_transaction()`.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::{AletheiaDB, PropertyMapBuilder, core::NodeId};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let source_id = NodeId::new(1)?;
/// # let target_id = NodeId::new(2)?;
/// let edge_id = db.create_edge(
/// source_id,
/// target_id,
/// "KNOWS",
/// PropertyMapBuilder::new().insert("since", 2024).build()
/// )?;
/// # Ok(())
/// # }
/// ```
///
/// # See Also
///
/// * [`write`](Self::write) - For batched write operations.
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn create_edge(
&self,
source: NodeId,
target: NodeId,
label: &str,
properties: PropertyMap,
) -> Result<EdgeId> {
self.write(|tx| tx.create_edge(source, target, label, properties))
}
/// Get the current state of a node.
///
/// This uses the fast path (current storage) for O(1) lookup.
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_node(&self, node_id: NodeId) -> Result<Node> {
self.current.get_node(node_id).record_error_metric()
}
/// Access a node without cloning, executing a closure on the node data.
///
/// This method provides zero-copy read access to node data for hot paths
/// where only specific fields are needed.
///
/// # Performance
///
/// - **No allocation**: Does not clone the Node
/// - **No Arc increment**: Does not increment PropertyMap reference count (unless cloned in closure)
/// - **Lock duration**: Holds DashMap read lock only during closure execution
///
/// # Safety & Deadlocks
///
/// **WARNING**: The closure is executed while holding a read lock on the node shard.
/// Do NOT attempt to modify the graph or perform operations that might acquire a
/// write lock on the same shard (e.g., `update_node`, `delete_node`) within the closure.
/// Doing so will cause a deadlock (lock re-entrancy hazard).
#[inline]
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn with_node<F, R>(&self, id: NodeId, f: F) -> Result<R>
where
F: FnOnce(&Node) -> R,
{
self.current.with_node(id, f).record_error_metric()
}
/// Get the current state of an edge.
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_edge(&self, edge_id: EdgeId) -> Result<Edge> {
self.current.get_edge(edge_id).record_error_metric()
}
/// Scan all nodes with a specific label, returning an iterator over node IDs.
///
/// This method provides efficient iteration over all nodes matching a given label/type.
/// Useful for operations that need to process all entities of a certain type.
///
/// # Arguments
///
/// * `label` - The label/type to filter by (e.g., "Person", "Product", "Event")
///
/// # Returns
///
/// An iterator yielding `NodeId` for all nodes with the specified label.
///
/// # Performance
///
/// - **Time**: O(n) scan of all nodes with efficient label filtering
/// - **Space**: O(1) - lazy iterator, no allocation
/// - **Comparison**: Uses interned string pointer equality (very fast)
///
/// # Examples
///
/// ```rust,no_run
/// # use aletheiadb::AletheiaDB;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// // Process all Person nodes
/// for node_id in db.scan_nodes_by_label("Person") {
/// let node = db.get_node(node_id)?;
/// println!("Person: {:?}", node.properties.get("name"));
/// }
///
/// // Count nodes by label
/// let person_count = db.scan_nodes_by_label("Person").count();
/// let product_count = db.scan_nodes_by_label("Product").count();
/// # Ok(())
/// # }
/// ```
///
/// # See Also
///
/// - [`find_nodes_by_property`](Self::find_nodes_by_property) - Find nodes by label + property value
/// - [`node_count`](Self::node_count) - Total node count across all labels
pub fn scan_nodes_by_label(&self, label: &str) -> impl Iterator<Item = NodeId> + '_ {
self.current.scan_nodes_by_label(label)
}
// ========================================================================
// Zero-copy access methods (Issue #190)
// ========================================================================
/// Get the target node of an edge without cloning the entire edge.
///
/// # Performance
///
/// - **Zero-copy**: Only reads and returns the target NodeId (8 bytes)
/// - **No allocation**: Does not clone Edge or PropertyMap
#[inline]
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_edge_target(&self, edge_id: EdgeId) -> Result<NodeId> {
self.current.get_edge_target(edge_id).record_error_metric()
}
/// Get the source node of an edge without cloning the entire edge.
///
/// # Performance
///
/// - **Zero-copy**: Only reads and returns the source NodeId (8 bytes)
/// - **No allocation**: Does not clone Edge or PropertyMap
#[inline]
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_edge_source(&self, edge_id: EdgeId) -> Result<NodeId> {
self.current.get_edge_source(edge_id).record_error_metric()
}
/// Get outgoing edges from a node (current state).
pub fn get_outgoing_edges(&self, node_id: NodeId) -> Vec<EdgeId> {
self.current.get_outgoing_edges(node_id)
}
/// Get outgoing edges from a node as an iterator (current state).
///
/// This provides zero-allocation traversal.
pub fn get_outgoing_edges_iter(&self, node_id: NodeId) -> OutgoingEdgesIter<'_> {
self.current.get_outgoing_edges_iter(node_id)
}
/// Get incoming edges to a node (current state).
pub fn get_incoming_edges(&self, node_id: NodeId) -> Vec<EdgeId> {
self.current.get_incoming_edges(node_id)
}
/// Get incoming edges to a node as an iterator (current state).
///
/// This provides zero-allocation traversal.
pub fn get_incoming_edges_iter(&self, node_id: NodeId) -> IncomingEdgesIter<'_> {
self.current.get_incoming_edges_iter(node_id)
}
/// Get incoming edges with a specific label (current state).
pub fn get_incoming_edges_with_label(&self, node_id: NodeId, label: &str) -> Vec<EdgeId> {
self.current.get_incoming_edges_with_label(node_id, label)
}
/// Get outgoing edges with a specific label (current state).
pub fn get_outgoing_edges_with_label(&self, node_id: NodeId, label: &str) -> Vec<EdgeId> {
self.current.get_outgoing_edges_with_label(node_id, label)
}
/// Get the number of nodes in the current state.
#[inline]
pub fn node_count(&self) -> usize {
self.current.node_count()
}
/// Get all node IDs currently in the database.
///
/// Returns a snapshot of all live node IDs. For large graphs prefer
/// [`scan_nodes_by_label`](Self::scan_nodes_by_label) to avoid loading
/// the full set into memory.
#[inline]
pub fn get_all_node_ids(&self) -> Vec<NodeId> {
self.current.get_all_node_ids()
}
/// Get the number of edges in the current state.
#[inline]
pub fn edge_count(&self) -> usize {
self.current.edge_count()
}
/// Get the out-degree of a node (current state).
#[inline]
pub fn out_degree(&self, node_id: NodeId) -> usize {
self.current.out_degree(node_id)
}
/// Get the in-degree of a node (current state).
#[inline]
pub fn in_degree(&self, node_id: NodeId) -> usize {
self.current.in_degree(node_id)
}
/// Find nodes by label and property value (current state).
///
/// Returns the IDs of all nodes with the given label whose specified property
/// equals the given value.
#[inline]
pub fn find_nodes_by_property(
&self,
label: &str,
property_key: &str,
property_value: &PropertyValue,
) -> Vec<NodeId> {
self.current
.find_nodes_by_property(label, property_key, property_value)
}
}
#[cfg(test)]
mod tests {
use crate::PropertyMapBuilder;
use crate::test_utils::create_test_db;
#[test]
fn get_all_node_ids_empty_db() {
let (_tmp, db) = create_test_db().unwrap();
assert!(db.get_all_node_ids().is_empty());
}
#[test]
fn get_all_node_ids_returns_created_nodes() {
let (_tmp, db) = create_test_db().unwrap();
let a = db
.create_node("X", PropertyMapBuilder::new().build())
.unwrap();
let b = db
.create_node("X", PropertyMapBuilder::new().build())
.unwrap();
let ids = db.get_all_node_ids();
assert_eq!(ids.len(), 2);
assert!(ids.contains(&a));
assert!(ids.contains(&b));
}
}