cqlite-cli 0.11.0

Command-line interface for CQLite — read Apache Cassandra 5.0 SSTables without a cluster
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
use anyhow::Result;
use std::io::Write;
use std::path::PathBuf;
// use std::process::{Command, Stdio}; // TODO: Add actual end-to-end tests
use std::time::Duration;
use tempfile::TempDir;

/// End-to-end integration tests for the CQLite CLI
///
/// These tests validate complete user workflows including:
/// - Interactive REPL mode functionality
/// - File I/O operations
/// - Complex query scenarios
/// - Error recovery and resilience
/// - Performance under realistic workloads
/// - Cross-platform compatibility
#[cfg(all(test, feature = "integration-tests"))]
mod e2e_tests {
    use super::*;
    use std::process::{Command, Stdio};
    use std::thread;
    use std::time::Instant;

    const CLI_BINARY: &str = "cqlite";
    const TEST_TIMEOUT: Duration = Duration::from_secs(30);

    /// Helper to run CLI with timeout
    fn run_cli_with_timeout(args: &[&str], timeout: Duration) -> Result<std::process::Output> {
        let mut cmd = Command::new("cargo");
        cmd.args(["run", "--bin", CLI_BINARY, "--"]).args(args);
        cmd.stdout(Stdio::piped()).stderr(Stdio::piped());

        println!("Running command: cargo run --bin {CLI_BINARY} -- {args:?}");

        let start = Instant::now();
        let mut child = cmd.spawn()?;

        loop {
            if child.try_wait()?.is_some() {
                // Process finished; collect output by re-running the command as output() loses the child
                // Instead, capture by spawning with output initially; but we spawned to allow polling.
                // Workaround: since we used spawn, we need to manually read from pipes.
                // Simpler approach: re-exec using output() when quick; here, we can just return a minimal Output.
                // To preserve logs, we re-run with output() if it was fast; else, provide empty.
                // For test stability, re-run to capture output:
                let output = Command::new("cargo")
                    .args(["run", "--bin", CLI_BINARY, "--"])
                    .args(args)
                    .output()?;
                println!(
                    "Command completed. stdout: {}, stderr: {}",
                    String::from_utf8_lossy(&output.stdout),
                    String::from_utf8_lossy(&output.stderr)
                );
                return Ok(output);
            }
            if start.elapsed() >= timeout {
                let _ = child.kill();
                anyhow::bail!("Timed out after {timeout:?} running CLI with args {args:?}");
            }
            thread::sleep(Duration::from_millis(50));
        }
    }

    /// Helper to create test SSTable structure for testing
    fn create_test_sstable_structure(temp_dir: &TempDir) -> Result<PathBuf> {
        let sstable_dir = temp_dir
            .path()
            .join("users-46436710673711f0b2cf19d64e7cbecb");
        std::fs::create_dir_all(&sstable_dir)?;

        // Create minimal SSTable files for testing
        let data_file = sstable_dir.join("nb-1-big-Data.db");
        let toc_file = sstable_dir.join("nb-1-big-TOC.txt");
        let statistics_file = sstable_dir.join("nb-1-big-Statistics.db");

        // Write minimal test data
        std::fs::write(&data_file, b"test data")?;
        std::fs::write(&toc_file, "Data.db\nStatistics.db\nTOC.txt")?;
        std::fs::write(&statistics_file, b"test stats")?;

        Ok(sstable_dir)
    }

    /// Create test schema files
    fn create_test_schema_files(temp_dir: &TempDir) -> Result<(PathBuf, PathBuf)> {
        let json_schema = temp_dir.path().join("schema.json");
        let cql_schema = temp_dir.path().join("schema.cql");

        let json_content = r#"{
  "keyspace": "test_keyspace",
  "table": "users",
  "partition_keys": [
    {
      "name": "id",
      "data_type": "uuid",
      "position": 0
    }
  ],
  "clustering_keys": [
    {
      "name": "created_at",
      "data_type": "timestamp",
      "position": 0,
      "order": "ASC"
    }
  ],
  "columns": [
    {
      "name": "id",
      "data_type": "uuid",
      "nullable": false,
      "default": null
    },
    {
      "name": "name",
      "data_type": "text",
      "nullable": true,
      "default": null
    },
    {
      "name": "email",
      "data_type": "text",
      "nullable": true,
      "default": null
    },
    {
      "name": "created_at",
      "data_type": "timestamp",
      "nullable": false,
      "default": null
    }
  ],
  "comments": {}
}"#;

        let cql_content = r#"CREATE TABLE test_keyspace.users (
  id uuid,
  name text,
  email text,
  created_at timestamp,
  PRIMARY KEY (id, created_at)
);"#;

        std::fs::write(&json_schema, json_content)?;
        std::fs::write(&cql_schema, cql_content)?;

        Ok((json_schema, cql_schema))
    }

    #[test]
    #[ignore = "Long e2e; run with --ignored or set E2E=1"]
    fn test_complete_database_workflow() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let db_path = temp_dir.path().join("workflow.db");
        let (json_schema, _cql_schema) = create_test_schema_files(&temp_dir)?;

        // Step 1: Create table from schema
        let create_output = run_cli_with_timeout(
            &[
                "--database",
                db_path.to_str().unwrap(),
                "schema",
                "create",
                json_schema.to_str().unwrap(),
            ],
            TEST_TIMEOUT,
        )?;

        println!("Create table output: {create_output:?}");

        // Step 2: List tables
        let list_output = run_cli_with_timeout(
            &["--database", db_path.to_str().unwrap(), "schema", "list"],
            TEST_TIMEOUT,
        )?;

        println!("List tables output: {list_output:?}");

        // Step 3: Insert data
        let insert_output = run_cli_with_timeout(
            &[
                "--database",
                db_path.to_str().unwrap(),
                "query",
                "INSERT INTO test_keyspace.users (id, name, email, created_at) VALUES (uuid(), 'John Doe', 'john@example.com', toTimestamp(now()))",
            ],
            TEST_TIMEOUT,
        )?;

        println!("Insert data output: {insert_output:?}");

        // Step 4: Query data with different formats
        for format in &["table", "json", "csv"] {
            let query_output = run_cli_with_timeout(
                &[
                    "--database",
                    db_path.to_str().unwrap(),
                    "--format",
                    format,
                    "query",
                    "SELECT * FROM test_keyspace.users",
                ],
                TEST_TIMEOUT,
            )?;

            println!("Query ({format}) output: {query_output:?}");
        }

        // Step 5: Get database info
        let info_output = run_cli_with_timeout(
            &["--database", db_path.to_str().unwrap(), "admin", "info"],
            TEST_TIMEOUT,
        )?;

        println!("Database info output: {info_output:?}");

        // Step 6: Run benchmark
        let bench_output = run_cli_with_timeout(
            &[
                "--database",
                db_path.to_str().unwrap(),
                "bench",
                "read",
                "--operations",
                "5",
                "--concurrency",
                "1",
            ],
            TEST_TIMEOUT,
        )?;

        println!("Benchmark output: {bench_output:?}");

        Ok(())
    }

    #[test]
    fn test_sstable_reading_workflow() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let sstable_dir = create_test_sstable_structure(&temp_dir)?;
        let (json_schema, _cql_schema) = create_test_schema_files(&temp_dir)?;

        // Test SSTable info command
        let info_output =
            run_cli_with_timeout(&["info", sstable_dir.to_str().unwrap()], TEST_TIMEOUT)?;

        println!("SSTable info output: {info_output:?}");

        // Test SSTable info with detailed flag
        let detailed_info_output = run_cli_with_timeout(
            &["info", sstable_dir.to_str().unwrap(), "--detailed"],
            TEST_TIMEOUT,
        )?;

        println!("Detailed SSTable info output: {detailed_info_output:?}");

        // Test SSTable reading
        let read_output = run_cli_with_timeout(
            &[
                "read",
                sstable_dir.to_str().unwrap(),
                "--schema",
                json_schema.to_str().unwrap(),
                "--limit",
                "10",
            ],
            TEST_TIMEOUT,
        )?;

        println!("SSTable read output: {read_output:?}");

        // Test with different output formats
        for format in &["json", "csv"] {
            let format_output = run_cli_with_timeout(
                &[
                    "--format",
                    format,
                    "read",
                    sstable_dir.to_str().unwrap(),
                    "--schema",
                    json_schema.to_str().unwrap(),
                    "--limit",
                    "5",
                ],
                TEST_TIMEOUT,
            )?;

            println!("SSTable read ({format}) output: {format_output:?}");
        }

        // Test auto-detection features
        let auto_detect_output = run_cli_with_timeout(
            &[
                "--auto-detect",
                "--cassandra-version",
                "5.0",
                "info",
                sstable_dir.to_str().unwrap(),
            ],
            TEST_TIMEOUT,
        )?;

        println!("Auto-detect output: {auto_detect_output:?}");

        Ok(())
    }

    #[test]
    fn test_schema_validation_workflow() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let (json_schema, cql_schema) = create_test_schema_files(&temp_dir)?;

        // Test JSON schema validation
        let json_validation = run_cli_with_timeout(
            &["schema", "validate", json_schema.to_str().unwrap()],
            TEST_TIMEOUT,
        )?;

        println!("JSON schema validation: {json_validation:?}");

        // Test CQL schema validation
        let cql_validation = run_cli_with_timeout(
            &["schema", "validate", cql_schema.to_str().unwrap()],
            TEST_TIMEOUT,
        )?;

        println!("CQL schema validation: {cql_validation:?}");

        // Test invalid schema
        let invalid_schema = temp_dir.path().join("invalid.json");
        std::fs::write(&invalid_schema, "{ invalid json syntax }")?;

        let invalid_validation = run_cli_with_timeout(
            &["schema", "validate", invalid_schema.to_str().unwrap()],
            TEST_TIMEOUT,
        )?;

        println!("Invalid schema validation: {invalid_validation:?}");
        // Should fail but not crash

        Ok(())
    }

    #[test]
    fn test_import_export_workflow() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let db_path = temp_dir.path().join("import_export.db");

        // Create test data files
        let json_data = temp_dir.path().join("test_data.json");
        let csv_data = temp_dir.path().join("test_data.csv");

        std::fs::write(
            &json_data,
            r#"[
  {"id": "123e4567-e89b-12d3-a456-426614174000", "name": "Alice", "email": "alice@example.com"},
  {"id": "123e4567-e89b-12d3-a456-426614174001", "name": "Bob", "email": "bob@example.com"}
]"#,
        )?;

        std::fs::write(
            &csv_data,
            "id,name,email\n123e4567-e89b-12d3-a456-426614174000,Alice,alice@example.com\n123e4567-e89b-12d3-a456-426614174001,Bob,bob@example.com",
        )?;

        // Test JSON import
        let json_import = run_cli_with_timeout(
            &[
                "--database",
                db_path.to_str().unwrap(),
                "import",
                json_data.to_str().unwrap(),
                "--format",
                "json",
                "--table",
                "users",
            ],
            TEST_TIMEOUT,
        )?;

        println!("JSON import: {json_import:?}");

        // Test CSV import
        let csv_import = run_cli_with_timeout(
            &[
                "--database",
                db_path.to_str().unwrap(),
                "import",
                csv_data.to_str().unwrap(),
                "--format",
                "csv",
                "--table",
                "users",
            ],
            TEST_TIMEOUT,
        )?;

        println!("CSV import: {csv_import:?}");

        // Test export
        let export_file = temp_dir.path().join("exported.json");
        let export_output = run_cli_with_timeout(
            &[
                "--database",
                db_path.to_str().unwrap(),
                "export",
                "users",
                export_file.to_str().unwrap(),
                "--format",
                "json",
            ],
            TEST_TIMEOUT,
        )?;

        println!("Export output: {export_output:?}");

        Ok(())
    }

    #[test]
    fn test_configuration_workflow() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let config_file = temp_dir.path().join("test_config.toml");
        let db_path = temp_dir.path().join("config_test.db");

        // Create configuration file
        std::fs::write(
            &config_file,
            r#"
[connection]
timeout_ms = 30000
retry_attempts = 3
pool_size = 10

[output]
max_rows = 1000
colors = true
timestamp_format = "%Y-%m-%d %H:%M:%S"

[performance]
cache_size_mb = 128
query_timeout_ms = 45000
memory_limit_mb = 512

[logging]
level = "debug"
format = "Pretty"

[repl]
enable_history = true
enable_completion = true
enable_colors = true
show_timing = false
page_size = 50
enable_paging = true
max_history_size = 1000
prompt = "cqlite> "
prompt_continuation = "    -> "

default_database = "default.db"
"#,
        )?;

        // Test CLI with configuration
        let config_output = run_cli_with_timeout(
            &[
                "--config",
                config_file.to_str().unwrap(),
                "--database",
                db_path.to_str().unwrap(),
                "--verbose",
                "admin",
                "info",
            ],
            TEST_TIMEOUT,
        )?;

        println!("Configuration test output: {config_output:?}");

        // Test quiet mode
        let quiet_output = run_cli_with_timeout(
            &[
                "--config",
                config_file.to_str().unwrap(),
                "--database",
                db_path.to_str().unwrap(),
                "--quiet",
                "admin",
                "info",
            ],
            TEST_TIMEOUT,
        )?;

        println!("Quiet mode output: {quiet_output:?}");

        Ok(())
    }

    #[test]
    fn test_error_recovery_workflow() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let non_existent_db = temp_dir.path().join("nonexistent.db");

        // Test graceful handling of non-existent database
        let no_db_output = run_cli_with_timeout(
            &[
                "--database",
                non_existent_db.to_str().unwrap(),
                "query",
                "SELECT 1",
            ],
            TEST_TIMEOUT,
        )?;

        println!("Non-existent database output: {no_db_output:?}");

        // Test invalid query
        let db_path = temp_dir.path().join("error_test.db");
        let invalid_query_output = run_cli_with_timeout(
            &[
                "--database",
                db_path.to_str().unwrap(),
                "query",
                "INVALID SQL SYNTAX HERE",
            ],
            TEST_TIMEOUT,
        )?;

        println!("Invalid query output: {invalid_query_output:?}");

        // Test non-existent SSTable
        let no_sstable_output =
            run_cli_with_timeout(&["info", "/tmp/nonexistent/sstable/path"], TEST_TIMEOUT)?;

        println!("Non-existent SSTable output: {no_sstable_output:?}");

        // Test invalid Cassandra version
        let invalid_version_output = run_cli_with_timeout(
            &["--cassandra-version", "99.0", "info", "/tmp/test"],
            TEST_TIMEOUT,
        )?;

        println!("Invalid version output: {invalid_version_output:?}");

        Ok(())
    }

    #[test]
    #[ignore = "Performance-heavy; run with --ignored or set E2E=1"]
    fn test_performance_under_load() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let db_path = temp_dir.path().join("performance.db");

        // Test with larger datasets
        let large_benchmark = run_cli_with_timeout(
            &[
                "--database",
                db_path.to_str().unwrap(),
                "bench",
                "mixed",
                "--operations",
                "100",
                "--concurrency",
                "2",
                "--read-pct",
                "80",
            ],
            Duration::from_secs(60),
        )?; // Longer timeout for performance test

        println!("Large benchmark output: {large_benchmark:?}");

        // Test query performance
        let query_performance = run_cli_with_timeout(
            &[
                "--database",
                db_path.to_str().unwrap(),
                "query",
                "--timing",
                "SELECT * FROM system.local",
            ],
            TEST_TIMEOUT,
        )?;

        println!("Query performance output: {query_performance:?}");

        Ok(())
    }

    #[test]
    #[ignore = "REPL mode requires interactive input - skipping in automated tests"]
    fn test_interactive_mode_simulation() -> Result<()> {
        // Note: This test simulates interactive mode by testing REPL entry
        // Full interactive testing would require expect/pexpect-style tools
        // Marking as ignored to prevent hanging during automated test runs

        let temp_dir = TempDir::new()?;
        let db_path = temp_dir.path().join("interactive.db");

        // Instead of trying to run REPL which will hang waiting for input,
        // we test that the database can be created and accessed
        let output = run_cli_with_timeout(
            &[
                "--database",
                db_path.to_str().unwrap(),
                "query",
                "SELECT 1 as column_0",
            ],
            TEST_TIMEOUT,
        )?;

        println!("Non-interactive test output: {output:?}");

        // Verify the command succeeded
        assert!(output.status.success(), "Command should succeed");

        Ok(())
    }

    #[test]
    fn test_cross_format_compatibility() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let (json_schema, cql_schema) = create_test_schema_files(&temp_dir)?;

        // Test that both schema formats work identically
        let json_validation = run_cli_with_timeout(
            &["schema", "validate", json_schema.to_str().unwrap()],
            TEST_TIMEOUT,
        )?;

        let cql_validation = run_cli_with_timeout(
            &["schema", "validate", cql_schema.to_str().unwrap()],
            TEST_TIMEOUT,
        )?;

        println!("JSON validation: {json_validation:?}");
        println!("CQL validation: {cql_validation:?}");

        // Both should succeed (when compilation is fixed)

        Ok(())
    }

    #[test]
    fn test_memory_usage_patterns() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let db_path = temp_dir.path().join("memory_test.db");

        // Test with memory constraints
        let memory_test = run_cli_with_timeout(
            &[
                "--database",
                db_path.to_str().unwrap(),
                "bench",
                "write",
                "--operations",
                "50",
                "--concurrency",
                "1",
            ],
            TEST_TIMEOUT,
        )?;

        println!("Memory usage test: {memory_test:?}");

        // Test database info after operations
        let post_info = run_cli_with_timeout(
            &["--database", db_path.to_str().unwrap(), "admin", "info"],
            TEST_TIMEOUT,
        )?;

        println!("Post-operation info: {post_info:?}");

        Ok(())
    }
}

/// Helper functions for end-to-end testing
#[cfg(test)]
mod e2e_helpers {
    use super::*;

    /// Validate that output contains expected patterns
    #[allow(dead_code)]
    pub fn validate_output_contains(output: &std::process::Output, patterns: &[&str]) -> bool {
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        let combined = format!("{stdout}{stderr}");

        patterns.iter().all(|pattern| combined.contains(pattern))
    }

    /// Validate that command executed successfully
    #[allow(dead_code)]
    pub fn validate_success(output: &std::process::Output) -> bool {
        output.status.success()
    }

    /// Validate that command failed as expected
    #[allow(dead_code)]
    pub fn validate_failure(output: &std::process::Output) -> bool {
        !output.status.success()
    }

    /// Extract timing information from output
    #[allow(dead_code)]
    pub fn extract_timing_info(output: &std::process::Output) -> Option<Duration> {
        let stdout = String::from_utf8_lossy(&output.stdout);

        // Look for timing patterns like "Query executed in 123.45ms"
        for line in stdout.lines() {
            if line.contains("executed in") && line.contains("ms") {
                if let Some(ms_part) = line.split("in ").nth(1) {
                    if let Some(ms_str) = ms_part.split("ms").next() {
                        if let Ok(ms) = ms_str.trim().parse::<f64>() {
                            return Some(Duration::from_millis(ms as u64));
                        }
                    }
                }
            }
        }

        None
    }

    /// Create comprehensive test dataset
    #[allow(dead_code)]
    pub fn create_large_test_dataset(temp_dir: &TempDir, size: usize) -> Result<PathBuf> {
        let data_file = temp_dir.path().join("large_dataset.csv");
        let mut file = std::fs::File::create(&data_file)?;

        writeln!(file, "id,name,email,age,city")?;
        for i in 0..size {
            writeln!(
                file,
                "{},User{},user{}@example.com,{},City{}",
                i,
                i,
                i,
                20 + (i % 50),
                i % 100
            )?;
        }

        Ok(data_file)
    }
}