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
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
1324
1325
1326
1327
1328
1329
1330
1331
1332
//! Core graph data structures and operations.
//!
//! This module provides the main [`Graph`] database interface along with
//! the fundamental data types [`Node`] and [`Relationship`]. The graph
//! supports arbitrary JSON properties on both nodes and relationships,
//! providing flexibility while maintaining performance.
//!
//! # Example
//!
//! ```rust
//! use graph_d::{Graph, Result};
//! use serde_json::json;
//! use std::collections::HashMap;
//!
//! # fn main() -> Result<()> {
//! let mut graph = Graph::new()?;
//!
//! // Create nodes
//! let mut alice_props = HashMap::new();
//! alice_props.insert("name".to_string(), json!("Alice"));
//! alice_props.insert("age".to_string(), json!(30));
//! let alice_id = graph.create_node(alice_props)?;
//!
//! let mut bob_props = HashMap::new();
//! bob_props.insert("name".to_string(), json!("Bob"));
//! let bob_id = graph.create_node(bob_props)?;
//!
//! // Create relationship
//! let rel_id = graph.create_relationship(
//!     alice_id,
//!     bob_id,
//!     "KNOWS".to_string(),
//!     HashMap::new()
//! )?;
//!
//! // Query the graph
//! let alice = graph.get_node(alice_id)?.unwrap();
//! let relationships = graph.get_relationships_for_node(alice_id)?;
//! # Ok(())
//! # }
//! ```

pub mod node;
pub mod relationship;

pub use node::Node;
pub use relationship::Relationship;

use crate::error::{GraphError, Result};
use crate::storage::Storage;
use serde_json::Value;
use std::collections::HashMap;

/// Unique identifier type for nodes and relationships.
///
/// IDs are auto-incrementing 64-bit unsigned integers that uniquely identify
/// entities within a graph database instance. Node and relationship IDs are
/// from separate namespaces, so a node and relationship can have the same ID value.
///
/// # Example
///
/// ```rust
/// use graph_d::graph::Id;
///
/// let node_id: Id = 42;
/// let relationship_id: Id = 42; // Same value is OK - different namespaces
/// ```
pub type Id = u64;

/// Main graph database interface.
///
/// The [`Graph`] struct provides the primary API for interacting with the graph database.
/// It manages nodes, relationships, and their properties, while coordinating with the
/// underlying storage and indexing systems.
///
/// # Features
///
/// - **CRUD Operations**: Create, read, update, and delete nodes and relationships
/// - **JSON Properties**: Store arbitrary JSON data on nodes and relationships
/// - **Indexing**: Create secondary indexes for fast property-based queries
/// - **Persistence**: Optional persistent storage using memory-mapped files
/// - **Transactions**: Thread-safe operations with ACID guarantees
///
/// # Storage Backends
///
/// The graph supports two storage backends:
/// - **In-Memory**: Fast, non-persistent storage for testing and small datasets
/// - **Persistent**: Memory-mapped file storage for durability across restarts
///
/// # Thread Safety
///
/// While the graph itself is not `Send + Sync`, the underlying storage layer
/// provides thread-safe read operations. Write operations require mutable access
/// and should be coordinated through the transaction system.
pub struct Graph {
    /// Storage backend for nodes and relationships
    pub storage: Storage,
    /// Next ID to assign to a new node
    next_node_id: Id,
    /// Next ID to assign to a new relationship
    next_relationship_id: Id,
}

impl Graph {
    /// Creates a new in-memory graph database.
    ///
    /// This creates a graph that stores all data in memory. Data will be lost
    /// when the graph is dropped. Use this for testing, temporary graphs, or
    /// when persistence is not required.
    ///
    /// # Returns
    ///
    /// Returns a new [`Graph`] instance with in-memory storage.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if the storage backend cannot be initialized.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// // Graph is ready for use
    /// # Ok(())
    /// # }
    /// ```
    pub fn new() -> Result<Self> {
        Ok(Graph {
            storage: Storage::new()?,
            next_node_id: 1,
            next_relationship_id: 1,
        })
    }

    /// Opens or creates a persistent graph database at the specified path.
    ///
    /// This creates a graph that persists data to disk using memory-mapped files.
    /// If the file already exists, it will be opened and existing data loaded.
    /// If the file doesn't exist, a new database will be created.
    ///
    /// # Arguments
    ///
    /// * `path` - File system path where the database should be stored
    ///
    /// # Returns
    ///
    /// Returns a new [`Graph`] instance with persistent storage.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if:
    /// - The file cannot be created or opened
    /// - The file exists but is corrupted
    /// - Insufficient permissions to access the file
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use graph_d::Graph;
    /// use std::path::Path;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// // Open or create a persistent graph database
    /// let mut graph = Graph::open(Path::new("my_graph.db"))?;
    /// // Graph data will persist across program restarts
    /// # Ok(())
    /// # }
    /// ```
    pub fn open<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
        Ok(Graph {
            storage: Storage::open(path)?,
            next_node_id: 1,
            next_relationship_id: 1,
        })
    }

    /// Creates a new node with the specified properties.
    ///
    /// Nodes are the fundamental entities in the graph, capable of storing
    /// arbitrary JSON properties. Each node receives a unique ID that can
    /// be used to reference it in relationships and queries.
    ///
    /// # Arguments
    ///
    /// * `properties` - HashMap of property names to JSON values
    ///
    /// # Returns
    ///
    /// Returns the unique [`Id`] assigned to the new node.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if the node cannot be persisted.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    ///
    /// let mut properties = HashMap::new();
    /// properties.insert("name".to_string(), json!("Alice"));
    /// properties.insert("age".to_string(), json!(30));
    /// properties.insert("hobbies".to_string(), json!(["reading", "hiking"]));
    ///
    /// let node_id = graph.create_node(properties)?;
    /// println!("Created node with ID: {}", node_id);
    /// # Ok(())
    /// # }
    /// ```
    pub fn create_node(&mut self, properties: HashMap<String, Value>) -> Result<Id> {
        let id = self.next_node_id;
        self.next_node_id += 1;

        let node = Node::new(id, properties);
        self.storage.store_node(node)?;

        Ok(id)
    }

    /// Retrieves a node by its unique ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the node to retrieve
    ///
    /// # Returns
    ///
    /// Returns `Some(Node)` if the node exists, `None` if it doesn't exist.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's an error accessing storage.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// let node_id = graph.create_node(HashMap::new())?;
    ///
    /// match graph.get_node(node_id)? {
    ///     Some(node) => println!("Found node: {:?}", node),
    ///     None => println!("Node not found"),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_node(&self, id: Id) -> Result<Option<Node>> {
        self.storage.get_node(id)
    }

    /// Creates a new relationship between two existing nodes.
    ///
    /// Relationships are directed edges that connect nodes in the graph.
    /// Each relationship has a type (like "KNOWS", "OWNS", etc.) and can
    /// store arbitrary JSON properties.
    ///
    /// # Arguments
    ///
    /// * `from_id` - ID of the source node
    /// * `to_id` - ID of the target node  
    /// * `rel_type` - Type/label for the relationship (e.g., "KNOWS", "FOLLOWS")
    /// * `properties` - HashMap of property names to JSON values
    ///
    /// # Returns
    ///
    /// Returns the unique [`Id`] assigned to the new relationship.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::NotFound`] if either node doesn't exist.
    /// Returns [`GraphError::Storage`] if the relationship cannot be persisted.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    ///
    /// let alice_id = graph.create_node(HashMap::new())?;
    /// let bob_id = graph.create_node(HashMap::new())?;
    ///
    /// let mut rel_props = HashMap::new();
    /// rel_props.insert("since".to_string(), json!("2020-01-01"));
    /// rel_props.insert("strength".to_string(), json!(0.8));
    ///
    /// let rel_id = graph.create_relationship(
    ///     alice_id,
    ///     bob_id,
    ///     "KNOWS".to_string(),
    ///     rel_props
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn create_relationship(
        &mut self,
        from_id: Id,
        to_id: Id,
        rel_type: String,
        properties: HashMap<String, Value>,
    ) -> Result<Id> {
        // Verify that both nodes exist
        if self.get_node(from_id)?.is_none() {
            return Err(GraphError::NotFound(format!("Node {from_id} not found")));
        }
        if self.get_node(to_id)?.is_none() {
            return Err(GraphError::NotFound(format!("Node {to_id} not found")));
        }

        let id = self.next_relationship_id;
        self.next_relationship_id += 1;

        let relationship = Relationship::new(id, from_id, to_id, rel_type, properties);
        self.storage.store_relationship(relationship)?;

        Ok(id)
    }

    /// Retrieves a relationship by its unique ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the relationship to retrieve
    ///
    /// # Returns
    ///
    /// Returns `Some(Relationship)` if found, `None` if not found.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's an error accessing storage.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// let node1 = graph.create_node(HashMap::new())?;
    /// let node2 = graph.create_node(HashMap::new())?;
    /// let rel_id = graph.create_relationship(node1, node2, "TEST".to_string(), HashMap::new())?;
    ///
    /// if let Some(relationship) = graph.get_relationship(rel_id)? {
    ///     println!("Relationship type: {}", relationship.rel_type);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_relationship(&self, id: Id) -> Result<Option<Relationship>> {
        self.storage.get_relationship(id)
    }

    /// Retrieves all relationships connected to a specific node.
    ///
    /// This includes both incoming and outgoing relationships. For directed
    /// relationships, a node may appear as either the source or target.
    ///
    /// # Arguments
    ///
    /// * `node_id` - ID of the node to find relationships for
    ///
    /// # Returns
    ///
    /// Returns a vector of all relationships connected to the node.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's an error accessing storage.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// let alice_id = graph.create_node(HashMap::new())?;
    /// let bob_id = graph.create_node(HashMap::new())?;
    /// let charlie_id = graph.create_node(HashMap::new())?;
    ///
    /// graph.create_relationship(alice_id, bob_id, "KNOWS".to_string(), HashMap::new())?;
    /// graph.create_relationship(charlie_id, alice_id, "FOLLOWS".to_string(), HashMap::new())?;
    ///
    /// let alice_relationships = graph.get_relationships_for_node(alice_id)?;
    /// println!("Alice has {} relationships", alice_relationships.len());
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_relationships_for_node(&self, node_id: Id) -> Result<Vec<Relationship>> {
        self.storage.get_relationships_for_node(node_id)
    }

    /// Creates a property index for fast exact-value lookups.
    ///
    /// Property indexes enable O(1) lookups for nodes and relationships based on
    /// specific property values. Only properties that are explicitly indexed will
    /// be included in the index.
    ///
    /// # Arguments
    ///
    /// * `property_key` - Name of the property to index
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    ///
    /// // Create an index on the "name" property
    /// graph.create_property_index("name".to_string());
    ///
    /// // Add some nodes
    /// let mut props = HashMap::new();
    /// props.insert("name".to_string(), json!("Alice"));
    /// graph.create_node(props)?;
    ///
    /// // Fast lookup by property value
    /// let alice_nodes = graph.find_nodes_by_property("name", &json!("Alice"))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn create_property_index(&mut self, property_key: String) {
        self.storage.create_property_index(property_key);
    }

    /// Creates a range index for efficient range queries.
    ///
    /// Range indexes support queries like "find all nodes where age > 25" or
    /// "find nodes with names between 'A' and 'M'". The current implementation
    /// uses string-based comparisons for all value types.
    ///
    /// # Arguments
    ///
    /// * `property_key` - Name of the property to index for range queries
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    ///
    /// // Create a range index on the "age" property
    /// graph.create_range_index("age".to_string());
    ///
    /// // Add nodes with age properties
    /// let mut props = HashMap::new();
    /// props.insert("age".to_string(), json!(25));
    /// graph.create_node(props)?;
    ///
    /// // Range query (finds nodes with age between 20 and 30)
    /// let young_nodes = graph.find_nodes_in_range("age", &json!(20), &json!(30))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn create_range_index(&mut self, property_key: String) {
        self.storage.create_range_index(property_key);
    }

    /// Creates a composite index for efficient multi-property queries.
    ///
    /// Composite indexes allow fast queries on combinations of properties,
    /// such as "find all users with name='Alice' AND age=30". They are most
    /// efficient when all indexed properties are specified in the query.
    ///
    /// # Arguments
    ///
    /// * `property_keys` - Vector of property names to include in the composite index
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    ///
    /// // Create a composite index on name and age
    /// graph.create_composite_index(vec!["name".to_string(), "age".to_string()]);
    ///
    /// // Add a node with both properties
    /// let mut props = HashMap::new();
    /// props.insert("name".to_string(), json!("Alice"));
    /// props.insert("age".to_string(), json!(30));
    /// graph.create_node(props)?;
    ///
    /// // Efficient multi-property queries are now possible
    /// // (This would require direct access to the index manager)
    /// # Ok(())
    /// # }
    /// ```
    pub fn create_composite_index(&mut self, property_keys: Vec<String>) {
        self.storage.create_composite_index(property_keys);
    }

    /// Finds nodes with a specific property value using indexes.
    ///
    /// This method performs an indexed lookup for nodes that have the exact
    /// property value specified. The property must have been indexed using
    /// [`create_property_index`] for this query to be efficient.
    ///
    /// # Arguments
    ///
    /// * `property_key` - Name of the property to search
    /// * `property_value` - Exact value to match
    ///
    /// # Returns
    ///
    /// Returns a vector of all nodes with the specified property value.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's an error accessing storage.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// graph.create_property_index("name".to_string());
    ///
    /// let mut props = HashMap::new();
    /// props.insert("name".to_string(), json!("Alice"));
    /// graph.create_node(props)?;
    ///
    /// let alice_nodes = graph.find_nodes_by_property("name", &json!("Alice"))?;
    /// assert_eq!(alice_nodes.len(), 1);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`create_property_index`]: Self::create_property_index
    pub fn find_nodes_by_property(
        &self,
        property_key: &str,
        property_value: &Value,
    ) -> Result<Vec<Node>> {
        let node_ids = self.storage.find_by_property(property_key, property_value);
        let mut nodes = Vec::new();

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

        Ok(nodes)
    }

    /// Finds nodes with property values within a specified range.
    ///
    /// This method performs a range query using range indexes. The property
    /// must have been indexed using [`create_range_index`] for this query
    /// to be efficient. The current implementation uses string comparison.
    ///
    /// # Arguments
    ///
    /// * `property_key` - Name of the property to search
    /// * `min_value` - Minimum value (inclusive)
    /// * `max_value` - Maximum value (inclusive)
    ///
    /// # Returns
    ///
    /// Returns a vector of all nodes with property values in the range.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's an error accessing storage.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// graph.create_range_index("age".to_string());
    ///
    /// // Add nodes with different ages
    /// for age in [25, 30, 35] {
    ///     let mut props = HashMap::new();
    ///     props.insert("age".to_string(), json!(age));
    ///     graph.create_node(props)?;
    /// }
    ///
    /// // Find nodes with age between 28 and 32
    /// let middle_aged = graph.find_nodes_in_range("age", &json!(28), &json!(32))?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`create_range_index`]: Self::create_range_index
    pub fn find_nodes_in_range(
        &self,
        property_key: &str,
        min_value: &Value,
        max_value: &Value,
    ) -> Result<Vec<Node>> {
        let node_ids = self
            .storage
            .find_in_range(property_key, min_value, max_value);
        let mut nodes = Vec::new();

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

        Ok(nodes)
    }

    /// Finds all relationships of a specific type.
    ///
    /// This method uses the built-in relationship type index to efficiently
    /// find all relationships with the specified type label.
    ///
    /// # Arguments
    ///
    /// * `rel_type` - The relationship type to search for (e.g., "KNOWS", "FOLLOWS")
    ///
    /// # Returns
    ///
    /// Returns a vector of all relationships with the specified type.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's an error accessing storage.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    ///
    /// let node1 = graph.create_node(HashMap::new())?;
    /// let node2 = graph.create_node(HashMap::new())?;
    /// let node3 = graph.create_node(HashMap::new())?;
    ///
    /// graph.create_relationship(node1, node2, "KNOWS".to_string(), HashMap::new())?;
    /// graph.create_relationship(node2, node3, "KNOWS".to_string(), HashMap::new())?;
    /// graph.create_relationship(node1, node3, "FOLLOWS".to_string(), HashMap::new())?;
    ///
    /// let knows_relationships = graph.find_relationships_by_type("KNOWS")?;
    /// assert_eq!(knows_relationships.len(), 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn find_relationships_by_type(&self, rel_type: &str) -> Result<Vec<Relationship>> {
        let rel_ids = self.storage.find_relationships_by_type(rel_type);
        let mut relationships = Vec::new();

        for rel_id in rel_ids {
            if let Some(relationship) = self.get_relationship(rel_id)? {
                relationships.push(relationship);
            }
        }

        Ok(relationships)
    }

    /// Finds outgoing relationships of a specific type from a node.
    ///
    /// This method finds all relationships where the specified node is the source
    /// and the relationship has the specified type. This is useful for graph
    /// traversal patterns like "find all people that Alice knows".
    ///
    /// # Arguments
    ///
    /// * `from_id` - ID of the source node
    /// * `rel_type` - Type of relationships to find
    ///
    /// # Returns
    ///
    /// Returns a vector of outgoing relationships from the node.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's an error accessing storage.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    ///
    /// let alice_id = graph.create_node(HashMap::new())?;
    /// let bob_id = graph.create_node(HashMap::new())?;
    /// let charlie_id = graph.create_node(HashMap::new())?;
    ///
    /// graph.create_relationship(alice_id, bob_id, "KNOWS".to_string(), HashMap::new())?;
    /// graph.create_relationship(alice_id, charlie_id, "KNOWS".to_string(), HashMap::new())?;
    /// graph.create_relationship(bob_id, alice_id, "KNOWS".to_string(), HashMap::new())?;
    ///
    /// // Find who Alice knows (outgoing KNOWS relationships)
    /// let alice_knows = graph.find_outgoing_relationships(alice_id, "KNOWS")?;
    /// assert_eq!(alice_knows.len(), 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn find_outgoing_relationships(
        &self,
        from_id: Id,
        rel_type: &str,
    ) -> Result<Vec<Relationship>> {
        let rel_ids = self.storage.find_outgoing_relationships(from_id, rel_type);
        let mut relationships = Vec::new();

        for rel_id in rel_ids {
            if let Some(relationship) = self.get_relationship(rel_id)? {
                relationships.push(relationship);
            }
        }

        Ok(relationships)
    }

    /// Finds incoming relationships of a specific type to a node.
    ///
    /// This method finds all relationships where the specified node is the target
    /// and the relationship has the specified type. This is useful for graph
    /// traversal patterns like "find all people who know Alice".
    ///
    /// # Arguments
    ///
    /// * `to_id` - ID of the target node
    /// * `rel_type` - Type of relationships to find
    ///
    /// # Returns
    ///
    /// Returns a vector of incoming relationships to the node.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's an error accessing storage.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    ///
    /// let alice_id = graph.create_node(HashMap::new())?;
    /// let bob_id = graph.create_node(HashMap::new())?;
    /// let charlie_id = graph.create_node(HashMap::new())?;
    ///
    /// graph.create_relationship(bob_id, alice_id, "KNOWS".to_string(), HashMap::new())?;
    /// graph.create_relationship(charlie_id, alice_id, "KNOWS".to_string(), HashMap::new())?;
    /// graph.create_relationship(alice_id, bob_id, "KNOWS".to_string(), HashMap::new())?;
    ///
    /// // Find who knows Alice (incoming KNOWS relationships)
    /// let knows_alice = graph.find_incoming_relationships(alice_id, "KNOWS")?;
    /// assert_eq!(knows_alice.len(), 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn find_incoming_relationships(
        &self,
        to_id: Id,
        rel_type: &str,
    ) -> Result<Vec<Relationship>> {
        let rel_ids = self.storage.find_incoming_relationships(to_id, rel_type);
        let mut relationships = Vec::new();

        for rel_id in rel_ids {
            if let Some(relationship) = self.get_relationship(rel_id)? {
                relationships.push(relationship);
            }
        }

        Ok(relationships)
    }

    /// Retrieves statistics about the indexing system.
    ///
    /// This method returns information about the current state of all indexes,
    /// including counts of different index types and total indexed entities.
    /// Useful for monitoring and optimization purposes.
    ///
    /// # Returns
    ///
    /// Returns [`IndexStats`] with current indexing metrics.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// graph.create_property_index("name".to_string());
    /// graph.create_range_index("age".to_string());
    ///
    /// let stats = graph.get_index_stats();
    /// println!("Property indexes: {}", stats.property_index_count);
    /// println!("Range indexes: {}", stats.range_index_count);
    /// println!("Total indexed entities: {}", stats.total_indexed_entities);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`IndexStats`]: crate::index::IndexStats
    pub fn get_index_stats(&self) -> crate::index::IndexStats {
        self.storage.get_index_stats()
    }

    /// Flushes any pending writes to disk.
    ///
    /// For persistent storage backends, this ensures all data is written to disk.
    /// For in-memory storage, this is a no-op. It's good practice to call this
    /// method before shutting down to ensure data durability.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's an error writing to disk.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use graph_d::Graph;
    /// use std::path::Path;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::open(Path::new("my_graph.db"))?;
    ///
    /// // ... perform operations ...
    ///
    /// // Ensure all data is written to disk
    /// graph.flush()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn flush(&self) -> Result<()> {
        self.storage.flush()
    }

    /// Deletes a node by its unique ID.
    ///
    /// The node will only be deleted if it has no relationships.
    /// To delete a node with relationships, first delete all its relationships.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the node to delete
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(Node))` if the node was deleted, `Ok(None)` if it didn't exist.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if the node has relationships or there's
    /// a storage error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// let node_id = graph.create_node(HashMap::new())?;
    ///
    /// // Delete the node
    /// if let Some(node) = graph.delete_node(node_id)? {
    ///     println!("Deleted node: {:?}", node);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn delete_node(&mut self, id: Id) -> Result<Option<Node>> {
        // Check if node has relationships - if so, refuse to delete
        if self.storage.node_has_relationships(id) {
            return Err(crate::error::GraphError::Storage(
                "Cannot delete node with existing relationships".into(),
            ));
        }
        self.storage.delete_node(id)
    }

    /// Deletes a node and all its relationships (detach delete).
    ///
    /// This is a convenience method that first deletes all relationships
    /// connected to the node, then deletes the node itself.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the node to delete
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(Node))` if the node was deleted, `Ok(None)` if it didn't exist.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's a storage error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// let node1 = graph.create_node(HashMap::new())?;
    /// let node2 = graph.create_node(HashMap::new())?;
    /// graph.create_relationship(node1, node2, "KNOWS".to_string(), HashMap::new())?;
    ///
    /// // Detach delete removes node and all its relationships
    /// if let Some(node) = graph.detach_delete_node(node1)? {
    ///     println!("Deleted node and its relationships: {:?}", node);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn detach_delete_node(&mut self, id: Id) -> Result<Option<Node>> {
        // First, delete all relationships connected to this node
        let rel_ids: Vec<Id> = self
            .storage
            .get_relationships_for_node(id)?
            .iter()
            .map(|r| r.id)
            .collect();

        for rel_id in rel_ids {
            self.storage.delete_relationship(rel_id)?;
        }

        // Now delete the node itself
        self.storage.delete_node(id)
    }

    /// Deletes a relationship by its unique ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the relationship to delete
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(Relationship))` if deleted, `Ok(None)` if it didn't exist.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's a storage error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// let node1 = graph.create_node(HashMap::new())?;
    /// let node2 = graph.create_node(HashMap::new())?;
    /// let rel_id = graph.create_relationship(node1, node2, "KNOWS".to_string(), HashMap::new())?;
    ///
    /// // Delete the relationship
    /// if let Some(rel) = graph.delete_relationship(rel_id)? {
    ///     println!("Deleted relationship: {:?}", rel);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn delete_relationship(&mut self, id: Id) -> Result<Option<Relationship>> {
        self.storage.delete_relationship(id)
    }

    /// Updates properties on a node.
    ///
    /// This merges the provided properties with existing ones.
    /// Existing properties not in the update map are preserved.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the node to update
    /// * `properties` - HashMap of property names to JSON values to set
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(Node))` with the updated node, `Ok(None)` if node doesn't exist.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's a storage error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// let mut props = HashMap::new();
    /// props.insert("name".to_string(), json!("Alice"));
    /// let node_id = graph.create_node(props)?;
    ///
    /// // Update the node's properties
    /// let mut updates = HashMap::new();
    /// updates.insert("age".to_string(), json!(30));
    /// if let Some(node) = graph.update_node_properties(node_id, updates)? {
    ///     println!("Updated node: {:?}", node);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn update_node_properties(
        &mut self,
        id: Id,
        properties: HashMap<String, Value>,
    ) -> Result<Option<Node>> {
        if let Some(mut node) = self.storage.get_node(id)? {
            // Merge properties
            for (key, value) in properties {
                node.properties.insert(key, value);
            }
            self.storage.store_node(node.clone())?;
            Ok(Some(node))
        } else {
            Ok(None)
        }
    }

    /// Updates properties on a relationship.
    ///
    /// This merges the provided properties with existing ones.
    /// Existing properties not in the update map are preserved.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the relationship to update
    /// * `properties` - HashMap of property names to JSON values to set
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(Relationship))` with the updated relationship, `Ok(None)` if not found.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's a storage error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// let node1 = graph.create_node(HashMap::new())?;
    /// let node2 = graph.create_node(HashMap::new())?;
    /// let rel_id = graph.create_relationship(node1, node2, "KNOWS".to_string(), HashMap::new())?;
    ///
    /// // Update the relationship's properties
    /// let mut updates = HashMap::new();
    /// updates.insert("since".to_string(), json!(2020));
    /// if let Some(rel) = graph.update_relationship_properties(rel_id, updates)? {
    ///     println!("Updated relationship: {:?}", rel);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn update_relationship_properties(
        &mut self,
        id: Id,
        properties: HashMap<String, Value>,
    ) -> Result<Option<Relationship>> {
        if let Some(mut rel) = self.storage.get_relationship(id)? {
            // Merge properties
            for (key, value) in properties {
                rel.properties.insert(key, value);
            }
            self.storage.store_relationship(rel.clone())?;
            Ok(Some(rel))
        } else {
            Ok(None)
        }
    }

    /// Removes specific properties from a node.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the node
    /// * `property_names` - Names of properties to remove
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(Node))` with the updated node, `Ok(None)` if node doesn't exist.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's a storage error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// let mut props = HashMap::new();
    /// props.insert("name".to_string(), json!("Alice"));
    /// props.insert("temp".to_string(), json!("to_remove"));
    /// let node_id = graph.create_node(props)?;
    ///
    /// // Remove a property
    /// if let Some(node) = graph.remove_node_properties(node_id, &["temp"])? {
    ///     println!("Updated node: {:?}", node);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn remove_node_properties(
        &mut self,
        id: Id,
        property_names: &[&str],
    ) -> Result<Option<Node>> {
        if let Some(mut node) = self.storage.get_node(id)? {
            for name in property_names {
                node.properties.remove(*name);
            }
            self.storage.store_node(node.clone())?;
            Ok(Some(node))
        } else {
            Ok(None)
        }
    }

    /// Removes specific properties from a relationship.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the relationship
    /// * `property_names` - Names of properties to remove
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(Relationship))` with the updated relationship, `Ok(None)` if not found.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError::Storage`] if there's a storage error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use graph_d::Graph;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> graph_d::Result<()> {
    /// let mut graph = Graph::new()?;
    /// let node1 = graph.create_node(HashMap::new())?;
    /// let node2 = graph.create_node(HashMap::new())?;
    /// let mut props = HashMap::new();
    /// props.insert("since".to_string(), json!(2020));
    /// props.insert("temp".to_string(), json!("to_remove"));
    /// let rel_id = graph.create_relationship(node1, node2, "KNOWS".to_string(), props)?;
    ///
    /// // Remove a property
    /// if let Some(rel) = graph.remove_relationship_properties(rel_id, &["temp"])? {
    ///     println!("Updated relationship: {:?}", rel);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn remove_relationship_properties(
        &mut self,
        id: Id,
        property_names: &[&str],
    ) -> Result<Option<Relationship>> {
        if let Some(mut rel) = self.storage.get_relationship(id)? {
            for name in property_names {
                rel.properties.remove(*name);
            }
            self.storage.store_relationship(rel.clone())?;
            Ok(Some(rel))
        } else {
            Ok(None)
        }
    }
}

impl Default for Graph {
    fn default() -> Self {
        Self::new().expect("Failed to create default graph")
    }
}

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

    #[test]
    fn test_create_node() {
        let mut graph = Graph::new().unwrap();
        let properties = [("name".to_string(), json!("Alice"))].into();
        let node_id = graph.create_node(properties).unwrap();
        assert_eq!(node_id, 1);
    }

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

        // Create two nodes
        let node1_id = graph.create_node(HashMap::new()).unwrap();
        let node2_id = graph.create_node(HashMap::new()).unwrap();

        // Create relationship
        let rel_id = graph
            .create_relationship(node1_id, node2_id, "KNOWS".to_string(), HashMap::new())
            .unwrap();

        assert_eq!(rel_id, 1);
    }

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

        // Create indexes
        graph.create_property_index("name".to_string());
        graph.create_range_index("age".to_string());

        // Create nodes with properties
        let mut props1 = HashMap::new();
        props1.insert("name".to_string(), json!("Alice"));
        props1.insert("age".to_string(), json!(25));
        let node1_id = graph.create_node(props1).unwrap();

        let mut props2 = HashMap::new();
        props2.insert("name".to_string(), json!("Bob"));
        props2.insert("age".to_string(), json!(30));
        let node2_id = graph.create_node(props2).unwrap();

        let mut props3 = HashMap::new();
        props3.insert("name".to_string(), json!("Alice"));
        props3.insert("age".to_string(), json!(35));
        let _node3_id = graph.create_node(props3).unwrap();

        // Test property lookup
        let alice_nodes = graph
            .find_nodes_by_property("name", &json!("Alice"))
            .unwrap();
        assert_eq!(alice_nodes.len(), 2);

        // Test range lookup
        let age_range_nodes = graph
            .find_nodes_in_range("age", &json!(28), &json!(32))
            .unwrap();
        assert_eq!(age_range_nodes.len(), 1);
        assert_eq!(age_range_nodes[0].id, node2_id);

        // Create relationship and test relationship indexing
        let rel_id = graph
            .create_relationship(node1_id, node2_id, "KNOWS".to_string(), HashMap::new())
            .unwrap();

        let knows_rels = graph.find_relationships_by_type("KNOWS").unwrap();
        assert_eq!(knows_rels.len(), 1);
        assert_eq!(knows_rels[0].id, rel_id);

        let outgoing_rels = graph
            .find_outgoing_relationships(node1_id, "KNOWS")
            .unwrap();
        assert_eq!(outgoing_rels.len(), 1);
        assert_eq!(outgoing_rels[0].id, rel_id);

        // Test index stats
        let stats = graph.get_index_stats();
        assert!(stats.property_index_count > 0);
        assert!(stats.range_index_count > 0);
    }
}