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
//! Comprehensive getting started guide for Graph_D.

use graph_d::query::{AggregateFunction, Pagination, QueryBuilder, SortCriteria};
use graph_d::transaction::{IsolationLevel, LockableResource, TransactionManager};
use graph_d::{Graph, Result};
use serde_json::json;
use std::collections::HashMap;

fn main() -> Result<()> {
    println!("🦀 Welcome to Graph_D - Getting Started Guide\n");

    // Part 1: Basic Graph Operations
    basic_operations()?;

    // Part 2: Working with Properties
    property_operations()?;

    // Part 3: Graph Traversal
    graph_traversal()?;

    // Part 4: Advanced Queries
    advanced_queries()?;

    // Part 5: Persistent Storage
    persistent_storage()?;

    // Part 6: Concurrent Transactions
    concurrent_transactions()?;

    println!("🎉 Congratulations! You've completed the Graph_D getting started guide.");
    println!("Check out more examples in the examples/ directory!");

    Ok(())
}

fn basic_operations() -> Result<()> {
    println!("=== Part 1: Basic Graph Operations ===");

    // Create a new in-memory graph database
    let mut graph = Graph::new()?;
    println!("✓ Created new graph database");

    // Create nodes with simple properties
    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(),
    )?;

    println!("✓ Created nodes: Alice (ID: {alice_id}), Bob (ID: {bob_id})");

    // Create a relationship
    let rel_id = graph.create_relationship(
        alice_id,
        bob_id,
        "KNOWS".to_string(),
        [("since".to_string(), json!("2020"))].into(),
    )?;

    println!("✓ Created relationship: Alice KNOWS Bob (ID: {rel_id})");

    // Read data back
    if let Some(alice) = graph.get_node(alice_id)? {
        println!("✓ Retrieved Alice: {:?}", alice.properties);
    }

    if let Some(relationship) = graph.get_relationship(rel_id)? {
        println!(
            "✓ Retrieved relationship: {} -> {} ({})",
            relationship.from_id, relationship.to_id, relationship.rel_type
        );
    }

    println!("✓ Part 1 completed successfully!\n");
    Ok(())
}

fn property_operations() -> Result<()> {
    println!("=== Part 2: Working with Properties ===");

    let mut graph = Graph::new()?;

    // Create a node with rich JSON properties
    let user_id = graph.create_node(
        [
            ("name".to_string(), json!("John Doe")),
            ("email".to_string(), json!("john@example.com")),
            (
                "profile".to_string(),
                json!({
                    "bio": "Software engineer with 5 years experience",
                    "skills": ["Rust", "Python", "JavaScript"],
                    "location": {
                        "city": "San Francisco",
                        "country": "USA",
                        "coordinates": [37.7749, -122.4194]
                    },
                    "preferences": {
                        "notifications": true,
                        "theme": "dark"
                    }
                }),
            ),
            (
                "metadata".to_string(),
                json!({
                    "created_at": "2024-01-15T10:30:00Z",
                    "last_login": "2024-01-19T14:22:33Z",
                    "login_count": 42
                }),
            ),
        ]
        .into(),
    )?;

    println!("✓ Created user with rich JSON properties");

    // Retrieve and examine properties
    if let Some(user) = graph.get_node(user_id)? {
        println!("✓ User name: {:?}", user.get_property("name"));

        if let Some(profile) = user.get_property("profile") {
            println!("✓ User profile: {profile}");
        }

        println!("✓ Property keys: {:?}", user.property_keys());
    }

    // Create relationships with properties
    let company_id = graph.create_node(
        [
            ("name".to_string(), json!("TechCorp Inc.")),
            ("industry".to_string(), json!("Software")),
            ("size".to_string(), json!("500-1000")),
        ]
        .into(),
    )?;

    let _employment_rel = graph.create_relationship(
        user_id,
        company_id,
        "WORKS_FOR".to_string(),
        [
            ("position".to_string(), json!("Senior Developer")),
            ("start_date".to_string(), json!("2023-03-01")),
            ("salary".to_string(), json!(95000)),
            (
                "benefits".to_string(),
                json!(["health", "dental", "401k", "stock_options"]),
            ),
        ]
        .into(),
    )?;

    println!("✓ Created employment relationship with detailed properties");
    println!("✓ Part 2 completed successfully!\n");
    Ok(())
}

fn graph_traversal() -> Result<()> {
    println!("=== Part 3: Graph Traversal ===");

    let mut graph = Graph::new()?;

    // Create a small social network
    let alice_id = graph.create_node([("name".to_string(), json!("Alice"))].into())?;
    let bob_id = graph.create_node([("name".to_string(), json!("Bob"))].into())?;
    let charlie_id = graph.create_node([("name".to_string(), json!("Charlie"))].into())?;
    let diana_id = graph.create_node([("name".to_string(), json!("Diana"))].into())?;

    // Create friendship relationships
    graph.create_relationship(alice_id, bob_id, "FRIENDS_WITH".to_string(), HashMap::new())?;
    graph.create_relationship(
        bob_id,
        charlie_id,
        "FRIENDS_WITH".to_string(),
        HashMap::new(),
    )?;
    graph.create_relationship(
        charlie_id,
        diana_id,
        "FRIENDS_WITH".to_string(),
        HashMap::new(),
    )?;
    graph.create_relationship(
        alice_id,
        diana_id,
        "FRIENDS_WITH".to_string(),
        HashMap::new(),
    )?;

    println!("✓ Created social network: Alice -> Bob -> Charlie -> Diana");

    // Basic traversal: Find Alice's friends
    let alice_friends = QueryBuilder::from_node(&graph, alice_id)
        .outgoing("FRIENDS_WITH")?
        .nodes()?;

    println!("✓ Alice's direct friends:");
    for friend in &alice_friends {
        let name = friend
            .get_property("name")
            .and_then(|v| v.as_str())
            .unwrap_or("Unknown");
        println!("  - {name}");
    }

    // Multi-hop traversal: Find friends of friends
    let friends_of_friends = QueryBuilder::from_node(&graph, alice_id)
        .outgoing("FRIENDS_WITH")?
        .outgoing("FRIENDS_WITH")?
        .nodes()?;

    println!("✓ Friends of Alice's friends:");
    for friend in &friends_of_friends {
        let name = friend
            .get_property("name")
            .and_then(|v| v.as_str())
            .unwrap_or("Unknown");
        println!("  - {name}");
    }

    // Path finding
    use graph_d::query::PathFinder;
    let path_finder = PathFinder::new(&graph);

    if let Some(path) = path_finder.shortest_path(alice_id, diana_id)? {
        println!("✓ Shortest path from Alice to Diana: {path:?}");
        println!("  Path length: {} hops", path.len() - 1);
    }

    println!("✓ Part 3 completed successfully!\n");
    Ok(())
}

fn advanced_queries() -> Result<()> {
    println!("=== Part 4: Advanced Queries ===");

    let mut graph = Graph::new()?;

    // Create sample data for analytics
    let departments = ["Engineering", "Sales", "Marketing", "HR"];
    let levels = ["Junior", "Senior", "Manager", "Director"];

    let mut employee_ids = Vec::new();

    for i in 0..20 {
        let employee_id = graph.create_node(
            [
                ("name".to_string(), json!(format!("Employee_{}", i))),
                (
                    "department".to_string(),
                    json!(departments[i % departments.len()]),
                ),
                ("level".to_string(), json!(levels[i % levels.len()])),
                ("salary".to_string(), json!(50000 + (i * 5000))),
                ("performance".to_string(), json!(3.0 + (i as f64 % 3.0))),
                ("years_experience".to_string(), json!(1 + (i % 10))),
            ]
            .into(),
        )?;

        employee_ids.push(employee_id);
    }

    println!(
        "✓ Created {} employees across {} departments",
        employee_ids.len(),
        departments.len()
    );

    // Aggregation queries
    let query = QueryBuilder::new(&graph, employee_ids.clone());

    // Count total employees
    let total_count = query.aggregate(AggregateFunction::Count)?;
    println!("✓ Total employees: {total_count:?}");

    // Average salary
    let avg_salary = query.aggregate(AggregateFunction::Avg("salary".to_string()))?;
    println!("✓ Average salary: {avg_salary:?}");

    // Group by department
    let dept_groups = query.aggregate(AggregateFunction::GroupBy("department".to_string()))?;
    if let graph_d::query::AggregateResult::Groups(groups) = dept_groups {
        println!("✓ Employees by department:");
        for (dept, employees) in groups {
            println!("  {}: {} employees", dept, employees.len());
        }
    }

    // Sorting and pagination
    let sorted_page = query.sorted_page(
        vec![SortCriteria::desc("salary"), SortCriteria::asc("name")],
        Pagination::new(0, 5),
    )?;

    println!("✓ Top 5 highest paid employees:");
    for (i, employee) in sorted_page.items.iter().enumerate() {
        let name = employee
            .get_property("name")
            .and_then(|v| v.as_str())
            .unwrap_or("Unknown");
        let salary = employee
            .get_property("salary")
            .and_then(|v| v.as_f64())
            .unwrap_or(0.0);
        println!("  {}. {}: ${:.0}", i + 1, name, salary);
    }

    // Statistical analysis
    let salary_stats = query.statistics("salary")?;
    println!("✓ Salary statistics:");
    println!("  Mean: ${:.2}", salary_stats.mean);
    println!("  Median: ${:.2}", salary_stats.median);
    println!("  Standard deviation: ${:.2}", salary_stats.std_dev);

    println!("✓ Part 4 completed successfully!\n");
    Ok(())
}

fn persistent_storage() -> Result<()> {
    println!("=== Part 5: Persistent Storage ===");

    let db_path = "getting_started_test.db";

    // Create persistent database
    {
        let mut graph = Graph::open(db_path)?;
        println!("✓ Created persistent database at: {db_path}");

        // Add some data
        let node_id = graph.create_node(
            [
                ("type".to_string(), json!("persistent_test")),
                ("created_at".to_string(), json!("2024-01-01")),
                ("data".to_string(), json!({"important": true, "value": 42})),
            ]
            .into(),
        )?;

        println!("✓ Added test data (Node ID: {node_id})");

        // Flush to disk
        graph.storage.flush()?;
        println!("✓ Data flushed to disk");
    }

    // Reopen database to verify persistence
    {
        let _graph = Graph::open(db_path)?;
        println!("✓ Reopened database from disk");

        // Note: Current implementation persists metadata only
        // Full data persistence would require complete record serialization
        println!("✓ Database reopened successfully (metadata persisted)");
    }

    // Cleanup
    std::fs::remove_file(db_path).ok();
    println!("✓ Cleaned up test database");

    println!("✓ Part 5 completed successfully!\n");
    Ok(())
}

fn concurrent_transactions() -> Result<()> {
    println!("=== Part 6: Concurrent Transactions ===");

    let tx_manager = TransactionManager::new(IsolationLevel::ReadCommitted);
    println!("✓ Created transaction manager with ReadCommitted isolation");

    // Basic transaction
    {
        let mut tx = tx_manager.begin_concurrent();
        println!("✓ Started transaction {}", tx.id());

        // Acquire locks
        tx.read_lock(LockableResource::Node(1))?;
        tx.write_lock(LockableResource::Node(2))?;
        println!("✓ Acquired read lock on Node 1 and write lock on Node 2");

        // In a real application, you would perform graph operations here
        // while holding the appropriate locks

        // Commit transaction (automatically releases locks)
        tx.commit()?;
        println!("✓ Transaction committed and locks released");
    }

    // Multiple concurrent readers
    {
        let mut tx1 = tx_manager.begin_concurrent();
        let mut tx2 = tx_manager.begin_concurrent();
        let mut tx3 = tx_manager.begin_concurrent();

        // All can acquire read locks on the same resource
        tx1.read_lock(LockableResource::Node(100))?;
        tx2.read_lock(LockableResource::Node(100))?;
        tx3.read_lock(LockableResource::Node(100))?;

        println!("✓ Three transactions successfully acquired shared read locks");

        // Commit all
        tx1.commit()?;
        tx2.commit()?;
        tx3.commit()?;

        println!("✓ All transactions committed successfully");
    }

    // Transaction statistics
    let stats = tx_manager.lock_statistics();
    println!("✓ Current lock statistics:");
    println!("  Active locks: {}", stats.total_active_locks);
    println!("  Waiting requests: {}", stats.waiting_requests);
    println!("  Locked resources: {}", stats.locked_resources);

    println!("✓ Part 6 completed successfully!\n");
    Ok(())
}

// Helper function to demonstrate error handling
#[allow(dead_code)]
fn error_handling_example() -> Result<()> {
    let mut graph = Graph::new()?;

    // Try to create a relationship between non-existent nodes
    match graph.create_relationship(999, 1000, "INVALID".to_string(), HashMap::new()) {
        Ok(_) => println!("This shouldn't happen"),
        Err(e) => println!("Expected error: {e}"),
    }

    // Try to get a non-existent node
    match graph.get_node(999)? {
        Some(_) => println!("This shouldn't happen"),
        None => println!("Node not found (expected)"),
    }

    Ok(())
}