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
// ═══════════════════════════════════════════════════════════════════════════════
// CLI Integration Tests for Graph_D
// ═══════════════════════════════════════════════════════════════════════════════
// Satisfies: T6 (CLI REPL) - Dedicated integration tests for CLI binary
// Satisfies: G2 gap from verification report
// ═══════════════════════════════════════════════════════════════════════════════

use std::fs;
use std::io::Write;
use std::process::Command;
use tempfile::TempDir;

/// Get the path to the CLI binary built with the 'cli' feature.
/// This assumes tests are run after `cargo build --features cli`.
fn get_cli_binary() -> std::path::PathBuf {
    // Use the target/debug binary path
    let mut path = std::env::current_exe()
        .expect("Failed to get current exe path")
        .parent()
        .expect("Failed to get parent dir")
        .parent()
        .expect("Failed to get target dir")
        .to_path_buf();
    path.push("graph_d");

    // On Windows, add .exe extension
    #[cfg(windows)]
    path.set_extension("exe");

    path
}

/// Check if CLI binary exists (may not if built without cli feature)
fn cli_binary_available() -> bool {
    get_cli_binary().exists()
}

// ═══════════════════════════════════════════════════════════════════════════════
// Version and Help Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_cli_version_flag() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let output = Command::new(get_cli_binary())
        .arg("--version")
        .output()
        .expect("Failed to execute CLI");

    assert!(output.status.success(), "Version flag should succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("graph_d") || stdout.contains("0.1.0"),
        "Version output should contain program name or version: {stdout}"
    );
}

#[test]
fn test_cli_help_flag() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let output = Command::new(get_cli_binary())
        .arg("--help")
        .output()
        .expect("Failed to execute CLI");

    assert!(output.status.success(), "Help flag should succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Verify key help content is present
    assert!(
        stdout.contains("DATABASE") || stdout.contains("database") || stdout.contains(":memory:"),
        "Help should mention database option: {stdout}"
    );
    assert!(
        stdout.contains("--cmd") || stdout.contains("-c"),
        "Help should mention command option: {stdout}"
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Single Command Mode Tests (using -c flag)
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_cli_single_command_mode() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    // Use :memory: as positional argument (it's the default, but explicit is clearer)
    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-c")
        .arg("MATCH (n) RETURN n")
        .output()
        .expect("Failed to execute CLI");

    // Should succeed even on empty database
    assert!(
        output.status.success(),
        "Single command mode should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_cli_match_query_on_empty_database() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-c")
        .arg("MATCH (n:Person) RETURN n.name")
        .output()
        .expect("Failed to execute CLI");

    // Should succeed - empty result on empty database is valid
    assert!(
        output.status.success(),
        "MATCH query on empty database should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_cli_invalid_query() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-c")
        .arg("INVALID SYNTAX")
        .output()
        .expect("Failed to execute CLI");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let combined = format!("{stdout}{stderr}").to_lowercase();

    // Invalid syntax should produce an error
    assert!(
        combined.contains("error")
            || combined.contains("invalid")
            || combined.contains("unexpected"),
        "Invalid query should produce error message. stdout: {stdout}, stderr: {stderr}"
    );
}

#[test]
fn test_cli_quiet_mode() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-q")
        .arg("-c")
        .arg("MATCH (n) RETURN n")
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "Quiet mode should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    // Just verify it doesn't crash
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.len() < 10000,
        "Quiet mode should not produce excessive output"
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Script File Mode Tests (using -f flag)
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_cli_script_file_mode() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let script_path = temp_dir.path().join("test_script.gql");

    // Create a script file with GQL commands
    let mut file = fs::File::create(&script_path).expect("Failed to create script file");
    writeln!(file, "-- This is a comment").unwrap();
    writeln!(file, "MATCH (n) RETURN n;").unwrap();

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-f")
        .arg(&script_path)
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "Script file mode should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_cli_script_with_comments() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let script_path = temp_dir.path().join("comments.gql");

    // Create a script file with various comment styles
    let mut file = fs::File::create(&script_path).expect("Failed to create script file");
    writeln!(file, "-- SQL-style comment").unwrap();
    writeln!(file, "// C-style comment").unwrap();
    writeln!(file, "MATCH (n) RETURN n;").unwrap();

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-f")
        .arg(&script_path)
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "Script with comments should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_cli_script_multiple_queries() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let script_path = temp_dir.path().join("multi.gql");

    // Create a script with multiple MATCH queries
    let mut file = fs::File::create(&script_path).expect("Failed to create script file");
    writeln!(file, "MATCH (n) RETURN n;").unwrap();
    writeln!(file, "MATCH (n:Person) RETURN n.name;").unwrap();
    writeln!(file, "MATCH (n) RETURN count(n);").unwrap();

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-f")
        .arg(&script_path)
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "Multiple MATCH queries in script should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// File-based Database Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_cli_file_database_creation() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let db_path = temp_dir.path().join("test.db");

    // Run a MATCH query which should create the database file
    let output = Command::new(get_cli_binary())
        .arg(&db_path)
        .arg("-c")
        .arg("MATCH (n) RETURN n")
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "File database creation should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Database file should exist
    assert!(
        db_path.exists(),
        "Database file should be created at {db_path:?}"
    );
}

#[test]
fn test_cli_file_database_reopening() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let db_path = temp_dir.path().join("persist.db");

    // First session: create database with a query
    let output1 = Command::new(get_cli_binary())
        .arg(&db_path)
        .arg("-c")
        .arg("MATCH (n) RETURN n")
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output1.status.success(),
        "First session should succeed. stderr: {}",
        String::from_utf8_lossy(&output1.stderr)
    );

    // Second session: reopen and query again
    let output2 = Command::new(get_cli_binary())
        .arg(&db_path)
        .arg("-c")
        .arg("MATCH (n) RETURN count(n)")
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output2.status.success(),
        "Second session should succeed (database reopening). stderr: {}",
        String::from_utf8_lossy(&output2.stderr)
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Output Format Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_cli_json_output_format() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-o")
        .arg("json")
        .arg("-c")
        .arg("MATCH (n) RETURN n")
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "JSON format should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_cli_csv_output_format() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-o")
        .arg("csv")
        .arg("-c")
        .arg("MATCH (n) RETURN n")
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "CSV format should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_cli_table_output_format() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-o")
        .arg("table")
        .arg("-c")
        .arg("MATCH (n) RETURN n")
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "Table format should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Path Traversal Security Tests (S2 Constraint)
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_cli_rejects_database_path_traversal() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    // Attempt to use path traversal in database path
    let output = Command::new(get_cli_binary())
        .arg("../../../etc/passwd")
        .arg("-c")
        .arg("MATCH (n) RETURN n")
        .output()
        .expect("Failed to execute CLI");

    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    let combined = format!("{stdout}{stderr}").to_lowercase();

    // Should reject path traversal or fail to open
    assert!(
        !output.status.success()
            || combined.contains("traversal")
            || combined.contains("error")
            || combined.contains("invalid"),
        "Path traversal should be rejected. status: {:?}, combined: {}",
        output.status,
        combined
    );
}

#[test]
fn test_cli_rejects_script_path_traversal() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    // Attempt to use path traversal in script path
    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-f")
        .arg("../../../etc/passwd")
        .output()
        .expect("Failed to execute CLI");

    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    let combined = format!("{stdout}{stderr}").to_lowercase();

    // Should reject path traversal
    assert!(
        !output.status.success()
            || combined.contains("traversal")
            || combined.contains("error")
            || combined.contains("invalid"),
        "Script path traversal should be rejected. status: {:?}, combined: {}",
        output.status,
        combined
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Error Handling Tests (S3 - No sensitive data in errors)
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_cli_error_no_sensitive_data() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    // Create a query that will fail - reference non-existent property
    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-c")
        .arg("MATCH (n) WHERE n.secret_password = 'hunter2' RETURN n")
        .output()
        .expect("Failed to execute CLI");

    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    let combined = format!("{stdout}{stderr}");

    // Error messages should not contain the value 'hunter2'
    assert!(
        !combined.contains("hunter2"),
        "Error messages should not leak property values. output: {combined}"
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Verbose Mode Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_cli_verbose_mode() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-v")
        .arg("-c")
        .arg("MATCH (n) RETURN n")
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "Verbose mode should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    // Verbose mode should produce status messages
    assert!(
        stderr.contains("Created") || stderr.contains("database") || !stderr.is_empty(),
        "Verbose mode should show status messages. stderr: {stderr}"
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Empty and Edge Case Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_cli_empty_script_file() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let script_path = temp_dir.path().join("empty.gql");

    // Create an empty script file
    fs::File::create(&script_path).expect("Failed to create script file");

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-f")
        .arg(&script_path)
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "Empty script file should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_cli_comment_only_script() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let script_path = temp_dir.path().join("comments_only.gql");

    // Create a script with only comments
    let mut file = fs::File::create(&script_path).expect("Failed to create script file");
    writeln!(file, "-- This is a comment").unwrap();
    writeln!(file, "// Another comment").unwrap();

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-f")
        .arg(&script_path)
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "Comment-only script should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Default In-Memory Mode Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_cli_default_memory_database() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    // No database argument - should use :memory: by default
    let output = Command::new(get_cli_binary())
        .arg("-c")
        .arg("MATCH (n) RETURN n")
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "Default memory database should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// GQL Parser Error Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_cli_create_node() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    // CREATE is now supported - should work correctly
    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-c")
        .arg("CREATE (n:Person {name: 'Alice'}) RETURN n")
        .output()
        .expect("Failed to execute CLI");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should succeed and return the created node
    assert!(
        output.status.success(),
        "CREATE should succeed. stdout: {stdout}, stderr: {stderr}"
    );

    // Should return 1 row
    assert!(
        stderr.contains("1 row returned"),
        "CREATE should return 1 row. stderr: {stderr}"
    );
}

#[test]
fn test_cli_match_with_where_clause() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-c")
        .arg("MATCH (n:Person) WHERE n.age > 21 RETURN n.name")
        .output()
        .expect("Failed to execute CLI");

    // WHERE clause should be supported
    assert!(
        output.status.success(),
        "MATCH with WHERE clause should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_cli_match_with_label() {
    if !cli_binary_available() {
        eprintln!("Skipping: CLI binary not found (build with --features cli)");
        return;
    }

    let output = Command::new(get_cli_binary())
        .arg(":memory:")
        .arg("-c")
        .arg("MATCH (p:Person) RETURN p")
        .output()
        .expect("Failed to execute CLI");

    assert!(
        output.status.success(),
        "MATCH with label should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}