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
// EMERGENCY M1 FIX: Allow clippy warnings
#![allow(clippy::all)]

use anyhow::Result;
use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;

/// Integration tests for the CQLite CLI
///
/// These tests validate all CLI functionality including:
/// - Command-line argument parsing
/// - Database operations
/// - Output formatting
/// - Error handling
/// - Interactive REPL mode
/// - SSTable reading capabilities

const CLI_BINARY: &str = "cqlite";

/// Test helper to create a temporary database
pub fn create_temp_database() -> Result<(TempDir, PathBuf)> {
    let temp_dir = TempDir::new()?;
    let db_path = temp_dir.path().join("test.db");
    Ok((temp_dir, db_path))
}

/// Test helper to run CLI commands
pub fn run_cli_command(args: &[&str]) -> Result<std::process::Output> {
    Command::new("cargo")
        .args(&["run", "--bin", CLI_BINARY, "--"])
        .args(args)
        .output()
        .map_err(|e| anyhow::anyhow!("Failed to run CLI command: {}", e))
}

#[cfg(all(test, feature = "integration-tests"))]
mod tests {
    use super::*;

    #[test]
    fn test_cli_help() -> Result<()> {
        let output = run_cli_command(&["--help"])?;
        assert!(output.status.success(), "CLI help should succeed");

        let stdout = String::from_utf8(output.stdout)?;
        assert!(stdout.contains("CQLite"), "Help should mention CQLite");
        assert!(
            stdout.contains("--database"),
            "Help should show database option"
        );
        assert!(
            stdout.contains("--format"),
            "Help should show format option"
        );

        Ok(())
    }

    #[test]
    fn test_cli_version() -> Result<()> {
        let output = run_cli_command(&["--version"])?;
        assert!(output.status.success(), "CLI version should succeed");

        let stdout = String::from_utf8(output.stdout)?;
        assert!(stdout.contains("cqlite"), "Version should mention cqlite");

        Ok(())
    }

    #[test]
    fn test_cli_invalid_argument() -> Result<()> {
        let output = run_cli_command(&["--invalid-argument"])?;
        assert!(!output.status.success(), "Invalid argument should fail");

        let stderr = String::from_utf8(output.stderr)?;
        assert!(
            stderr.contains("error") || stderr.contains("unrecognized"),
            "Should show error for invalid argument"
        );

        Ok(())
    }

    #[test]
    fn test_query_command_basic() -> Result<()> {
        let (_temp_dir, db_path) = create_temp_database()?;

        let output =
            run_cli_command(&["--database", db_path.to_str().unwrap(), "query", "SELECT 1"])?;

        // TODO: Once compilation is fixed, validate actual query execution
        // For now, just check the command structure
        println!("Query command output: {:?}", output);

        Ok(())
    }

    #[test]
    fn test_query_command_with_timing() -> Result<()> {
        let (_temp_dir, db_path) = create_temp_database()?;

        let output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "query",
            "--timing",
            "SELECT 1",
        ])?;

        println!("Query with timing output: {:?}", output);

        Ok(())
    }

    #[test]
    fn test_query_command_with_explain() -> Result<()> {
        let (_temp_dir, db_path) = create_temp_database()?;

        let output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "query",
            "--explain",
            "SELECT 1",
        ])?;

        println!("Query with explain output: {:?}", output);

        Ok(())
    }

    #[test]
    fn test_output_formats() -> Result<()> {
        let (_temp_dir, db_path) = create_temp_database()?;

        // Test table format (default)
        let table_output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "--format",
            "table",
            "query",
            "SELECT 1",
        ])?;

        // Test JSON format
        let json_output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "--format",
            "json",
            "query",
            "SELECT 1",
        ])?;

        // Test CSV format
        let csv_output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "--format",
            "csv",
            "query",
            "SELECT 1",
        ])?;

        println!("Table format: {:?}", table_output);
        println!("JSON format: {:?}", json_output);
        println!("CSV format: {:?}", csv_output);

        Ok(())
    }

    #[test]
    fn test_admin_commands() -> Result<()> {
        let (_temp_dir, db_path) = create_temp_database()?;

        // Test admin info
        let info_output =
            run_cli_command(&["--database", db_path.to_str().unwrap(), "admin", "info"])?;

        // Test admin compact
        let compact_output =
            run_cli_command(&["--database", db_path.to_str().unwrap(), "admin", "compact"])?;

        println!("Admin info: {:?}", info_output);
        println!("Admin compact: {:?}", compact_output);

        Ok(())
    }

    #[test]
    fn test_schema_commands() -> Result<()> {
        let (_temp_dir, db_path) = create_temp_database()?;

        // Test schema list
        let list_output =
            run_cli_command(&["--database", db_path.to_str().unwrap(), "schema", "list"])?;

        println!("Schema list: {:?}", list_output);

        Ok(())
    }

    #[test]
    fn test_bench_commands() -> Result<()> {
        let (_temp_dir, db_path) = create_temp_database()?;

        // Test read benchmark with minimal operations
        let read_output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "bench",
            "read",
            "--operations",
            "10",
            "--concurrency",
            "1",
        ])?;

        // Test write benchmark with minimal operations
        let write_output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "bench",
            "write",
            "--operations",
            "10",
            "--concurrency",
            "1",
        ])?;

        // Test mixed benchmark
        let mixed_output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "bench",
            "mixed",
            "--read-ratio",
            "70",
            "--operations",
            "10",
            "--concurrency",
            "1",
        ])?;

        println!("Read benchmark: {:?}", read_output);
        println!("Write benchmark: {:?}", write_output);
        println!("Mixed benchmark: {:?}", mixed_output);

        Ok(())
    }

    #[test]
    fn test_verbose_and_quiet_modes() -> Result<()> {
        let (_temp_dir, db_path) = create_temp_database()?;

        // Test verbose mode
        let verbose_output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "--verbose",
            "admin",
            "info",
        ])?;

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

        println!("Verbose mode: {:?}", verbose_output);
        println!("Quiet mode: {:?}", quiet_output);

        Ok(())
    }

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

        // Create a basic config file
        std::fs::write(
            &config_path,
            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 = 30000
memory_limit_mb = 512

[logging]
level = "info"
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 = "    -> "
"#,
        )?;

        let output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "--config",
            config_path.to_str().unwrap(),
            "admin",
            "info",
        ])?;

        println!("Config file loading: {:?}", output);

        Ok(())
    }

    #[test]
    fn test_sstable_auto_detect() -> Result<()> {
        // Test auto-detection feature
        let output = run_cli_command(&[
            "--auto-detect",
            "--cassandra-version",
            "5.0",
            "info",
            "/tmp/nonexistent/sstable/path",
        ])?;

        // Should fail gracefully for non-existent path
        println!("SSTable auto-detect: {:?}", output);

        Ok(())
    }

    #[test]
    fn test_cassandra_version_validation() -> Result<()> {
        // Test valid version
        let valid_output =
            run_cli_command(&["--cassandra-version", "5.0", "info", "/tmp/nonexistent"])?;

        // Test invalid version
        let invalid_output =
            run_cli_command(&["--cassandra-version", "99.0", "info", "/tmp/nonexistent"])?;

        println!("Valid version: {:?}", valid_output);
        println!("Invalid version: {:?}", invalid_output);

        Ok(())
    }

    #[test]
    fn test_error_handling() -> Result<()> {
        // Test with non-existent database file
        let output = run_cli_command(&["--database", "/tmp/nonexistent.db", "query", "SELECT 1"])?;

        // Should fail gracefully
        println!("Non-existent database: {:?}", output);

        Ok(())
    }

    #[test]
    fn test_import_export_commands() -> Result<()> {
        let (_temp_dir, db_path) = create_temp_database()?;
        let temp_file = _temp_dir.path().join("test.json");

        // Create a test file for import
        std::fs::write(&temp_file, r#"{"test": "data"}"#)?;

        // Test import command
        let import_output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "import",
            temp_file.to_str().unwrap(),
            "--format",
            "json",
            "--table",
            "test_table",
        ])?;

        // Test export command
        let export_file = _temp_dir.path().join("export.json");
        let export_output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "export",
            "test_table",
            export_file.to_str().unwrap(),
            "--format",
            "json",
        ])?;

        println!("Import: {:?}", import_output);
        println!("Export: {:?}", export_output);

        Ok(())
    }
}

/// Performance and stress tests
#[cfg(all(test, feature = "integration-tests"))]
mod performance_tests {
    use super::*;

    #[test]
    #[ignore] // Run with: cargo test --ignored
    fn test_large_query_performance() -> Result<()> {
        let (_temp_dir, db_path) = create_temp_database()?;

        let start = std::time::Instant::now();
        let output = run_cli_command(&[
            "--database",
            db_path.to_str().unwrap(),
            "--format",
            "json",
            "query",
            "SELECT 1",
        ])?;
        let duration = start.elapsed();

        println!("Query took: {:?}", duration);
        assert!(
            duration.as_millis() < 5000,
            "Query should complete within 5 seconds"
        );

        println!("Performance test output: {:?}", output);

        Ok(())
    }

    #[test]
    #[ignore] // Run with: cargo test --ignored
    fn test_concurrent_cli_operations() -> Result<()> {
        use super::{create_temp_database, run_cli_command};
        use std::path::PathBuf;
        use std::sync::Arc;
        use std::thread;

        let (_temp_dir, db_path) = create_temp_database()?;
        let db_path: Arc<PathBuf> = Arc::new(db_path);

        let mut handles = vec![];

        for _i in 0..5 {
            let db_path_clone = Arc::clone(&db_path);
            let handle = thread::spawn(move || {
                run_cli_command(&[
                    "--database",
                    db_path_clone.to_str().unwrap(),
                    "admin",
                    "info",
                ])
            });
            handles.push(handle);
        }

        for handle in handles {
            let result = handle.join().unwrap();
            println!("Concurrent operation result: {:?}", result);
        }

        Ok(())
    }
}