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
//! Sorting operations for graph query results.

use crate::graph::{Id, Node, Relationship};
use serde_json::Value;
use std::cmp::Ordering;

/// Sort direction for ordering results.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SortDirection {
    /// Ascending order (A-Z, 0-9)
    Asc,
    /// Descending order (Z-A, 9-0)
    Desc,
}

/// Sort criteria for ordering query results.
#[derive(Debug, Clone, PartialEq)]
pub struct SortCriteria {
    /// Property name to sort by
    pub property: String,
    /// Sort direction
    pub direction: SortDirection,
}

impl SortCriteria {
    /// Create a new sort criteria with ascending order.
    pub fn asc(property: impl Into<String>) -> Self {
        SortCriteria {
            property: property.into(),
            direction: SortDirection::Asc,
        }
    }

    /// Create a new sort criteria with descending order.
    pub fn desc(property: impl Into<String>) -> Self {
        SortCriteria {
            property: property.into(),
            direction: SortDirection::Desc,
        }
    }
}

/// Sorting utilities for graph elements.
pub struct Sorter;

impl Sorter {
    /// Sort a collection of nodes by the given criteria.
    pub fn sort_nodes(mut nodes: Vec<Node>, criteria: &[SortCriteria]) -> Vec<Node> {
        nodes.sort_by(|a, b| Self::compare_nodes(a, b, criteria));
        nodes
    }

    /// Sort a collection of relationships by the given criteria.
    pub fn sort_relationships(
        mut relationships: Vec<Relationship>,
        criteria: &[SortCriteria],
    ) -> Vec<Relationship> {
        relationships.sort_by(|a, b| Self::compare_relationships(a, b, criteria));
        relationships
    }

    /// Sort a collection of node IDs by their corresponding node properties.
    pub fn sort_node_ids_by_properties(
        mut node_ids: Vec<Id>,
        nodes: &[Node],
        criteria: &[SortCriteria],
    ) -> Vec<Id> {
        // Create a lookup map for nodes
        let node_map: std::collections::HashMap<Id, &Node> =
            nodes.iter().map(|node| (node.id, node)).collect();

        node_ids.sort_by(|&a, &b| {
            let node_a = node_map.get(&a);
            let node_b = node_map.get(&b);

            match (node_a, node_b) {
                (Some(a), Some(b)) => Self::compare_nodes(a, b, criteria),
                (Some(_), None) => Ordering::Less,
                (None, Some(_)) => Ordering::Greater,
                (None, None) => Ordering::Equal,
            }
        });

        node_ids
    }

    /// Compare two nodes using the given sort criteria.
    fn compare_nodes(a: &Node, b: &Node, criteria: &[SortCriteria]) -> Ordering {
        for criterion in criteria {
            let value_a = a.get_property(&criterion.property);
            let value_b = b.get_property(&criterion.property);

            let ordering = Self::compare_values(value_a, value_b);

            let final_ordering = match criterion.direction {
                SortDirection::Asc => ordering,
                SortDirection::Desc => ordering.reverse(),
            };

            if final_ordering != Ordering::Equal {
                return final_ordering;
            }
        }

        Ordering::Equal
    }

    /// Compare two relationships using the given sort criteria.
    fn compare_relationships(
        a: &Relationship,
        b: &Relationship,
        criteria: &[SortCriteria],
    ) -> Ordering {
        for criterion in criteria {
            let value_a = a.get_property(&criterion.property);
            let value_b = b.get_property(&criterion.property);

            let ordering = Self::compare_values(value_a, value_b);

            let final_ordering = match criterion.direction {
                SortDirection::Asc => ordering,
                SortDirection::Desc => ordering.reverse(),
            };

            if final_ordering != Ordering::Equal {
                return final_ordering;
            }
        }

        Ordering::Equal
    }

    /// Compare two JSON values.
    fn compare_values(a: Option<&Value>, b: Option<&Value>) -> Ordering {
        match (a, b) {
            (None, None) => Ordering::Equal,
            (None, Some(_)) => Ordering::Greater, // Nulls last
            (Some(_), None) => Ordering::Less,
            (Some(val_a), Some(val_b)) => Self::compare_json_values(val_a, val_b),
        }
    }

    /// Compare two JSON values with type-aware comparison.
    fn compare_json_values(a: &Value, b: &Value) -> Ordering {
        match (a, b) {
            (Value::Number(a), Value::Number(b)) => a
                .as_f64()
                .partial_cmp(&b.as_f64())
                .unwrap_or(Ordering::Equal),
            (Value::String(a), Value::String(b)) => a.cmp(b),
            (Value::Bool(a), Value::Bool(b)) => a.cmp(b),

            // Type mixing: Numbers < Strings < Booleans < Others
            (Value::Number(_), _) => Ordering::Less,
            (_, Value::Number(_)) => Ordering::Greater,
            (Value::String(_), Value::Bool(_)) => Ordering::Less,
            (Value::Bool(_), Value::String(_)) => Ordering::Greater,

            // For complex types, compare as strings
            _ => a.to_string().cmp(&b.to_string()),
        }
    }
}

/// Pagination support for sorted results.
#[derive(Debug, Clone, PartialEq)]
pub struct Pagination {
    /// Number of items to skip
    pub offset: usize,
    /// Maximum number of items to return
    pub limit: usize,
}

impl Pagination {
    /// Create new pagination with offset and limit.
    pub fn new(offset: usize, limit: usize) -> Self {
        Pagination { offset, limit }
    }

    /// Apply pagination to a collection.
    pub fn apply<T>(self, items: Vec<T>) -> Vec<T> {
        items
            .into_iter()
            .skip(self.offset)
            .take(self.limit)
            .collect()
    }
}

/// Combined sorting and pagination result.
#[derive(Debug, Clone)]
pub struct SortedPage<T> {
    /// The items in the current page
    pub items: Vec<T>,
    /// Total number of items before pagination
    pub total_count: usize,
    /// Pagination info
    pub pagination: Pagination,
}

impl<T> SortedPage<T> {
    /// Check if there are more pages available.
    pub fn has_next_page(&self) -> bool {
        self.pagination.offset + self.pagination.limit < self.total_count
    }

    /// Check if there are previous pages available.
    pub fn has_previous_page(&self) -> bool {
        self.pagination.offset > 0
    }

    /// Get the next page pagination parameters.
    pub fn next_page(&self) -> Option<Pagination> {
        if self.has_next_page() {
            Some(Pagination::new(
                self.pagination.offset + self.pagination.limit,
                self.pagination.limit,
            ))
        } else {
            None
        }
    }

    /// Get the previous page pagination parameters.
    pub fn previous_page(&self) -> Option<Pagination> {
        if self.has_previous_page() {
            let offset = self.pagination.offset.saturating_sub(self.pagination.limit);
            Some(Pagination::new(offset, self.pagination.limit))
        } else {
            None
        }
    }
}

/// Advanced sorting utilities.
pub struct AdvancedSorter;

impl AdvancedSorter {
    /// Sort nodes with pagination support.
    pub fn sort_nodes_paginated(
        nodes: Vec<Node>,
        criteria: &[SortCriteria],
        pagination: Pagination,
    ) -> SortedPage<Node> {
        let total_count = nodes.len();
        let sorted_nodes = Sorter::sort_nodes(nodes, criteria);
        let page_items = pagination.clone().apply(sorted_nodes);

        SortedPage {
            items: page_items,
            total_count,
            pagination,
        }
    }

    /// Sort and group nodes by a property value.
    pub fn sort_and_group_nodes(
        nodes: Vec<Node>,
        group_by: &str,
        sort_criteria: &[SortCriteria],
    ) -> std::collections::BTreeMap<String, Vec<Node>> {
        let mut groups: std::collections::BTreeMap<String, Vec<Node>> =
            std::collections::BTreeMap::new();

        // Group nodes
        for node in nodes {
            let group_key = if let Some(value) = node.get_property(group_by) {
                match value {
                    Value::String(s) => s.clone(),
                    Value::Number(n) => n.to_string(),
                    Value::Bool(b) => b.to_string(),
                    _ => "other".to_string(),
                }
            } else {
                "null".to_string()
            };

            groups.entry(group_key).or_default().push(node);
        }

        // Sort within each group
        for group_nodes in groups.values_mut() {
            *group_nodes = Sorter::sort_nodes(group_nodes.clone(), sort_criteria);
        }

        groups
    }
}

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

    fn create_test_nodes() -> Vec<Node> {
        vec![
            Node::new(
                1,
                [
                    ("age".to_string(), json!(30)),
                    ("name".to_string(), json!("Charlie")),
                    ("score".to_string(), json!(85.5)),
                ]
                .into(),
            ),
            Node::new(
                2,
                [
                    ("age".to_string(), json!(25)),
                    ("name".to_string(), json!("Alice")),
                    ("score".to_string(), json!(92.0)),
                ]
                .into(),
            ),
            Node::new(
                3,
                [
                    ("age".to_string(), json!(35)),
                    ("name".to_string(), json!("Bob")),
                    ("score".to_string(), json!(78.5)),
                ]
                .into(),
            ),
        ]
    }

    #[test]
    fn test_sort_by_age_ascending() {
        let nodes = create_test_nodes();
        let criteria = vec![SortCriteria::asc("age")];
        let sorted = Sorter::sort_nodes(nodes, &criteria);

        assert_eq!(sorted[0].id, 2); // Alice, age 25
        assert_eq!(sorted[1].id, 1); // Charlie, age 30
        assert_eq!(sorted[2].id, 3); // Bob, age 35
    }

    #[test]
    fn test_sort_by_name_descending() {
        let nodes = create_test_nodes();
        let criteria = vec![SortCriteria::desc("name")];
        let sorted = Sorter::sort_nodes(nodes, &criteria);

        assert_eq!(sorted[0].id, 1); // Charlie
        assert_eq!(sorted[1].id, 3); // Bob
        assert_eq!(sorted[2].id, 2); // Alice
    }

    #[test]
    fn test_multi_criteria_sorting() {
        let mut nodes = create_test_nodes();
        // Add another node with same age as Alice
        nodes.push(Node::new(
            4,
            [
                ("age".to_string(), json!(25)),
                ("name".to_string(), json!("David")),
                ("score".to_string(), json!(88.0)),
            ]
            .into(),
        ));

        let criteria = vec![SortCriteria::asc("age"), SortCriteria::desc("name")];
        let sorted = Sorter::sort_nodes(nodes, &criteria);

        // First by age (25, 25, 30, 35), then by name desc within same age
        assert_eq!(sorted[0].id, 4); // David, age 25
        assert_eq!(sorted[1].id, 2); // Alice, age 25
        assert_eq!(sorted[2].id, 1); // Charlie, age 30
        assert_eq!(sorted[3].id, 3); // Bob, age 35
    }

    #[test]
    fn test_pagination() {
        let nodes = create_test_nodes();
        let criteria = vec![SortCriteria::asc("age")];
        let pagination = Pagination::new(1, 2);

        let result = AdvancedSorter::sort_nodes_paginated(nodes, &criteria, pagination);

        assert_eq!(result.items.len(), 2);
        assert_eq!(result.total_count, 3);
        assert_eq!(result.items[0].id, 1); // Charlie
        assert_eq!(result.items[1].id, 3); // Bob
        assert!(result.has_previous_page());
        assert!(!result.has_next_page());
    }

    #[test]
    fn test_sort_and_group() {
        let mut nodes = create_test_nodes();
        // Add nodes with same age groups
        nodes.push(Node::new(
            4,
            [
                ("age".to_string(), json!(25)),
                ("name".to_string(), json!("Eve")),
            ]
            .into(),
        ));

        let criteria = vec![SortCriteria::asc("name")];
        let groups = AdvancedSorter::sort_and_group_nodes(nodes, "age", &criteria);

        assert_eq!(groups.len(), 3);

        let age_25_group = groups.get("25").unwrap();
        assert_eq!(age_25_group.len(), 2);
        assert_eq!(
            age_25_group[0].get_property("name").unwrap(),
            &json!("Alice")
        );
        assert_eq!(age_25_group[1].get_property("name").unwrap(), &json!("Eve"));
    }
}