graph_d 1.3.2

A native graph database implementation in Rust with built-in JSON support and SQLite-like simplicity
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
//! Query engine for graph traversal and filtering.
//!
//! This module provides a fluent API for building and executing graph queries.
//! It supports common graph traversal patterns, filtering, aggregation, and
//! path finding operations.
//!
//! # Query Building
//!
//! The [`QueryBuilder`] provides a fluent interface for constructing complex
//! graph traversals. Queries are built by chaining operations and executed
//! lazily when results are requested.
//!
//! # Path Finding
//!
//! The [`PathFinder`] implements graph algorithms for finding paths between
//! nodes, including shortest path calculations using breadth-first search.
//!
//! # Example
//!
//! ```rust
//! use graph_d::{Graph, query::QueryBuilder};
//! use serde_json::json;
//! use std::collections::HashMap;
//!
//! # fn main() -> graph_d::Result<()> {
//! let mut graph = Graph::new()?;
//!
//! // Create nodes
//! let alice_id = graph.create_node([
//!     ("name".to_string(), json!("Alice")),
//!     ("age".to_string(), json!(30))
//! ].into())?;
//!
//! let bob_id = graph.create_node([
//!     ("name".to_string(), json!("Bob")),
//!     ("age".to_string(), json!(25))
//! ].into())?;
//!
//! // Create relationship
//! graph.create_relationship(alice_id, bob_id, "KNOWS".to_string(), HashMap::new())?;
//!
//! // Query: Find all people Alice knows who are under 30
//! let young_friends = QueryBuilder::from_node(&graph, alice_id)
//!     .outgoing("KNOWS")?
//!     .filter_by_property("age", &json!(25))?
//!     .nodes()?;
//!
//! assert_eq!(young_friends.len(), 1);
//! assert_eq!(young_friends[0].id, bob_id);
//! # Ok(())
//! # }
//! ```

pub mod aggregation;
pub mod sorting;

use crate::error::Result;
use crate::graph::{Graph, Id, Node};
use serde_json::Value;

pub use aggregation::{
    AggregateFunction, AggregateResult, Aggregator, Statistics, StatisticsResult,
};
pub use sorting::{AdvancedSorter, Pagination, SortCriteria, SortDirection, SortedPage, Sorter};

/// A fluent query builder for graph traversals.
///
/// The [`QueryBuilder`] provides a chainable API for constructing complex graph
/// queries. It maintains a current set of nodes and allows traversing relationships,
/// filtering by properties, and applying aggregation functions.
///
/// # Design Principles
///
/// - **Fluent Interface**: Method chaining for readable query construction
/// - **Lazy Evaluation**: Operations are applied when results are requested
/// - **Type Safety**: Compile-time verification of query structure
/// - **Memory Efficient**: Only stores node IDs until final materialization
///
/// # Query Operations
///
/// - **Traversal**: [`outgoing`], [`incoming`], [`either`]
/// - **Filtering**: [`filter_by_property`]
/// - **Aggregation**: [`aggregate`], [`statistics`]
/// - **Sorting**: [`sort`], [`sorted_page`]
/// - **Pagination**: [`paginate`]
/// - **Grouping**: [`group_by_sorted`]
///
/// # Performance Considerations
///
/// - Use indexed properties for filtering when possible
/// - Apply filters early to reduce intermediate result sets
/// - Consider pagination for large result sets
/// - Group operations are expensive on large datasets
///
/// # Example
///
/// ```rust
/// use graph_d::{Graph, query::QueryBuilder};
/// use serde_json::json;
/// use std::collections::HashMap;
///
/// # fn main() -> graph_d::Result<()> {
/// let mut graph = Graph::new()?;
/// let start_node = graph.create_node(HashMap::new())?;
///
/// // Multi-hop traversal with filtering
/// let result = QueryBuilder::from_node(&graph, start_node)
///     .outgoing("FOLLOWS")?
///     .outgoing("LIKES")?
///     .filter_by_property("category", &json!("music"))?
///     .nodes()?;
/// # Ok(())
/// # }
/// ```
///
/// # Future Enhancements
///
/// A production system would include:
/// - Query optimization and planning
/// - Cost-based execution strategies
/// - Support for complex predicates
/// - Join operations across multiple starting points
///
/// [`outgoing`]: QueryBuilder::outgoing
/// [`incoming`]: QueryBuilder::incoming
/// [`either`]: QueryBuilder::either
/// [`filter_by_property`]: QueryBuilder::filter_by_property
/// [`aggregate`]: QueryBuilder::aggregate
/// [`statistics`]: QueryBuilder::statistics
/// [`sort`]: QueryBuilder::sort
/// [`sorted_page`]: QueryBuilder::sorted_page
/// [`paginate`]: QueryBuilder::paginate
/// [`group_by_sorted`]: QueryBuilder::group_by_sorted
pub struct QueryBuilder<'a> {
    graph: &'a Graph,
    current_nodes: Vec<Id>,
}

impl<'a> QueryBuilder<'a> {
    /// Create a new query builder starting from the given node IDs.
    pub fn new(graph: &'a Graph, start_nodes: Vec<Id>) -> Self {
        QueryBuilder {
            graph,
            current_nodes: start_nodes,
        }
    }

    /// Start a query from a single node.
    pub fn from_node(graph: &'a Graph, node_id: Id) -> Self {
        Self::new(graph, vec![node_id])
    }

    /// Traverse outgoing relationships of the given type.
    pub fn outgoing(mut self, rel_type: &str) -> Result<Self> {
        let mut next_nodes = Vec::new();

        for &node_id in &self.current_nodes {
            let relationships = self.graph.get_relationships_for_node(node_id)?;

            for rel in relationships {
                if rel.rel_type == rel_type && rel.is_outgoing_from(node_id) {
                    next_nodes.push(rel.to_id);
                }
            }
        }

        self.current_nodes = next_nodes;
        Ok(self)
    }

    /// Traverse incoming relationships of the given type.
    pub fn incoming(mut self, rel_type: &str) -> Result<Self> {
        let mut next_nodes = Vec::new();

        for &node_id in &self.current_nodes {
            let relationships = self.graph.get_relationships_for_node(node_id)?;

            for rel in relationships {
                if rel.rel_type == rel_type && rel.is_incoming_to(node_id) {
                    next_nodes.push(rel.from_id);
                }
            }
        }

        self.current_nodes = next_nodes;
        Ok(self)
    }

    /// Traverse relationships in either direction.
    pub fn either(mut self, rel_type: &str) -> Result<Self> {
        let mut next_nodes = Vec::new();

        for &node_id in &self.current_nodes {
            let relationships = self.graph.get_relationships_for_node(node_id)?;

            for rel in relationships {
                if rel.rel_type == rel_type {
                    if rel.is_outgoing_from(node_id) {
                        next_nodes.push(rel.to_id);
                    } else if rel.is_incoming_to(node_id) {
                        next_nodes.push(rel.from_id);
                    }
                }
            }
        }

        self.current_nodes = next_nodes;
        Ok(self)
    }

    /// Filter nodes by a property condition.
    pub fn filter_by_property(mut self, key: &str, value: &Value) -> Result<Self> {
        let mut filtered_nodes = Vec::new();

        for &node_id in &self.current_nodes {
            if let Some(node) = self.graph.get_node(node_id)? {
                if node.get_property(key) == Some(value) {
                    filtered_nodes.push(node_id);
                }
            }
        }

        self.current_nodes = filtered_nodes;
        Ok(self)
    }

    /// Get the current node IDs in the query result.
    pub fn node_ids(&self) -> &[Id] {
        &self.current_nodes
    }

    /// Get the current nodes in the query result.
    pub fn nodes(&self) -> Result<Vec<Node>> {
        let mut nodes = Vec::new();

        for &node_id in &self.current_nodes {
            if let Some(node) = self.graph.get_node(node_id)? {
                nodes.push(node);
            }
        }

        Ok(nodes)
    }

    /// Count the number of nodes in the current result.
    pub fn count(&self) -> usize {
        self.current_nodes.len()
    }

    /// Check if the query result is empty.
    pub fn is_empty(&self) -> bool {
        self.current_nodes.is_empty()
    }

    /// Apply an aggregation function to the current nodes.
    pub fn aggregate(&self, function: AggregateFunction) -> Result<AggregateResult> {
        let nodes = self.nodes()?;
        Aggregator::aggregate(&nodes, &function)
    }

    /// Sort the current nodes by the given criteria.
    pub fn sort(mut self, criteria: Vec<SortCriteria>) -> Result<Self> {
        let nodes = self.nodes()?;
        let sorted_nodes = Sorter::sort_nodes(nodes, &criteria);

        self.current_nodes = sorted_nodes.into_iter().map(|node| node.id).collect();
        Ok(self)
    }

    /// Apply pagination to the current results.
    pub fn paginate(mut self, pagination: Pagination) -> Result<Self> {
        let paginated_ids = pagination.apply(self.current_nodes);
        self.current_nodes = paginated_ids;
        Ok(self)
    }

    /// Get sorted and paginated nodes.
    pub fn sorted_page(
        &self,
        criteria: Vec<SortCriteria>,
        pagination: Pagination,
    ) -> Result<SortedPage<Node>> {
        let nodes = self.nodes()?;
        Ok(AdvancedSorter::sort_nodes_paginated(
            nodes, &criteria, pagination,
        ))
    }

    /// Calculate statistics for a numeric property.
    pub fn statistics(&self, property: &str) -> Result<StatisticsResult> {
        let nodes = self.nodes()?;
        Statistics::calculate(&nodes, property)
    }

    /// Group nodes by a property and sort within groups.
    pub fn group_by_sorted(
        &self,
        group_property: &str,
        sort_criteria: Vec<SortCriteria>,
    ) -> Result<std::collections::BTreeMap<String, Vec<Node>>> {
        let nodes = self.nodes()?;
        Ok(AdvancedSorter::sort_and_group_nodes(
            nodes,
            group_property,
            &sort_criteria,
        ))
    }
}

/// Path finding algorithms for graph connectivity analysis.
///
/// The [`PathFinder`] implements various graph algorithms for finding paths
/// and analyzing connectivity between nodes. It provides efficient implementations
/// of common graph traversal algorithms.
///
/// # Algorithms
///
/// - **Shortest Path**: Breadth-first search for unweighted shortest paths
/// - **Path Existence**: Quick connectivity checks
/// - **Multi-hop Traversal**: Support for relationship type filtering
///
/// # Performance
///
/// - **Time Complexity**: O(V + E) for BFS where V=nodes, E=relationships
/// - **Space Complexity**: O(V) for visited set and queue
/// - **Memory Efficient**: Only stores necessary state during traversal
///
/// # Example
///
/// ```rust
/// use graph_d::{Graph, query::PathFinder};
/// use std::collections::HashMap;
///
/// # fn main() -> graph_d::Result<()> {
/// let mut graph = Graph::new()?;
///
/// // Create a path: A -> B -> C
/// let node_a = graph.create_node(HashMap::new())?;
/// let node_b = graph.create_node(HashMap::new())?;
/// let node_c = graph.create_node(HashMap::new())?;
///
/// graph.create_relationship(node_a, node_b, "CONNECTS".to_string(), HashMap::new())?;
/// graph.create_relationship(node_b, node_c, "CONNECTS".to_string(), HashMap::new())?;
///
/// let path_finder = PathFinder::new(&graph);
/// let path = path_finder.shortest_path(node_a, node_c)?;
///
/// assert_eq!(path, Some(vec![node_a, node_b, node_c]));
/// # Ok(())
/// # }
/// ```
///
/// # Use Cases
///
/// - **Social Networks**: Find connection paths between users
/// - **Recommendation Systems**: Discover related items through associations
/// - **Dependency Analysis**: Trace dependencies in system graphs
/// - **Network Analysis**: Analyze connectivity in infrastructure graphs
///
/// # Future Extensions
///
/// - Weighted shortest paths (Dijkstra's algorithm)
/// - All-pairs shortest paths (Floyd-Warshall)
/// - Relationship type filtering during traversal
/// - K-shortest paths algorithms
pub struct PathFinder<'a> {
    graph: &'a Graph,
}

impl<'a> PathFinder<'a> {
    /// Create a new path finder.
    pub fn new(graph: &'a Graph) -> Self {
        PathFinder { graph }
    }

    /// Find the shortest path between two nodes (BFS).
    /// Returns the sequence of node IDs in the path, or None if no path exists.
    pub fn shortest_path(&self, from_id: Id, to_id: Id) -> Result<Option<Vec<Id>>> {
        if from_id == to_id {
            return Ok(Some(vec![from_id]));
        }

        let mut queue = std::collections::VecDeque::new();
        let mut visited = std::collections::HashSet::new();
        let mut parent = std::collections::HashMap::new();

        queue.push_back(from_id);
        visited.insert(from_id);

        while let Some(current_id) = queue.pop_front() {
            let relationships = self.graph.get_relationships_for_node(current_id)?;

            for rel in relationships {
                let next_id = if rel.is_outgoing_from(current_id) {
                    rel.to_id
                } else if rel.is_incoming_to(current_id) {
                    rel.from_id
                } else {
                    continue;
                };

                if next_id == to_id {
                    // Found the target, reconstruct path
                    let mut path = vec![to_id, current_id];
                    let mut current = current_id;

                    while let Some(&prev) = parent.get(&current) {
                        path.push(prev);
                        current = prev;
                    }

                    path.reverse();
                    return Ok(Some(path));
                }

                if !visited.contains(&next_id) {
                    visited.insert(next_id);
                    parent.insert(next_id, current_id);
                    queue.push_back(next_id);
                }
            }
        }

        Ok(None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::collections::HashMap;

    #[test]
    fn test_query_builder() {
        let mut graph = Graph::new().unwrap();

        // Create nodes
        let node1_id = graph
            .create_node([("name".to_string(), json!("Alice"))].into())
            .unwrap();
        let node2_id = graph
            .create_node([("name".to_string(), json!("Bob"))].into())
            .unwrap();
        let node3_id = graph
            .create_node([("name".to_string(), json!("Charlie"))].into())
            .unwrap();

        // Create relationships
        graph
            .create_relationship(node1_id, node2_id, "KNOWS".to_string(), HashMap::new())
            .unwrap();
        graph
            .create_relationship(node2_id, node3_id, "KNOWS".to_string(), HashMap::new())
            .unwrap();

        // Query: find all nodes that Alice knows
        let query_result = QueryBuilder::from_node(&graph, node1_id)
            .outgoing("KNOWS")
            .unwrap();
        let result = query_result.node_ids();

        assert_eq!(result.len(), 1);
        assert_eq!(result[0], node2_id);

        // Query: find all nodes that know someone named "Charlie"
        let query_result = QueryBuilder::new(&graph, vec![node1_id, node2_id, node3_id])
            .outgoing("KNOWS")
            .unwrap()
            .filter_by_property("name", &json!("Charlie"))
            .unwrap();
        let result = query_result.count();

        assert_eq!(result, 1);
    }

    #[test]
    fn test_path_finder() {
        let mut graph = Graph::new().unwrap();

        // Create a simple path: 1 -> 2 -> 3
        let node1_id = graph.create_node(HashMap::new()).unwrap();
        let node2_id = graph.create_node(HashMap::new()).unwrap();
        let node3_id = graph.create_node(HashMap::new()).unwrap();

        graph
            .create_relationship(node1_id, node2_id, "CONNECTS".to_string(), HashMap::new())
            .unwrap();
        graph
            .create_relationship(node2_id, node3_id, "CONNECTS".to_string(), HashMap::new())
            .unwrap();

        let path_finder = PathFinder::new(&graph);
        let path = path_finder.shortest_path(node1_id, node3_id).unwrap();

        assert_eq!(path, Some(vec![node1_id, node2_id, node3_id]));
    }
}