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

use anyhow::Result;
use clap::Parser;
use rstest::rstest;
use std::path::PathBuf;
use tempfile::TempDir;

/// Unit tests for individual CLI components
///
/// These tests validate specific functionality in isolation:
/// - Configuration loading and validation
/// - Command parsing and validation
/// - Output formatting functions
/// - Error handling and user feedback
/// - Schema validation logic
/// - Utility functions

#[cfg(test)]
mod config_tests {
    use super::*;
    use cqlite_cli::config::Config;
    use cqlite_cli::Cli;

    #[test]
    fn test_default_config() -> Result<()> {
        let config = Config::default();

        assert_eq!(config.performance.cache_size_mb, 64);
        assert_eq!(config.performance.query_timeout_ms, 30000);
        assert!(config.performance.memory_limit_mb.is_none());
        assert_eq!(config.logging.level, "info");

        Ok(())
    }

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

        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 = 256
query_timeout_ms = 60000
memory_limit_mb = 1024

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

        // Create a minimal CLI for testing
        let cli = Cli::parse_from(&["cqlite"]);
        let config = Config::load(Some(config_path), &cli)?;

        assert_eq!(config.performance.cache_size_mb, 256);
        assert_eq!(config.performance.query_timeout_ms, 60000);
        assert_eq!(config.performance.memory_limit_mb, Some(1024));
        assert_eq!(config.logging.level, "debug");

        Ok(())
    }

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

        // Test invalid cache size
        std::fs::write(
            &config_path,
            r#"
[performance]
cache_size_mb = -10
"#,
        )?;

        // Create a minimal CLI for testing
        let cli = Cli::parse_from(&["cqlite"]);
        let result = Config::load(Some(config_path), &cli);
        assert!(result.is_err(), "Should reject negative cache size");

        Ok(())
    }

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

        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]
query_timeout_ms = 300000
cache_size_mb = 256

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

        // Create a minimal CLI for testing
        let cli = Cli::parse_from(&["cqlite"]);
        let config = Config::load(Some(config_path), &cli)?;

        // Should use explicit values from TOML
        assert_eq!(config.performance.cache_size_mb, 256);
        assert_eq!(config.logging.level, "trace");

        Ok(())
    }
}

#[cfg(test)]
mod cli_parsing_tests {
    use super::*;
    use cqlite_cli::{AdminCommands, BenchCommands, Cli, Commands, SchemaCommands};

    #[test]
    fn test_basic_command_parsing() -> Result<()> {
        // Test query command
        let args = vec!["cqlite", "query", "SELECT 1"];
        let cli = Cli::try_parse_from(args)?;

        match cli.command {
            Some(Commands::Query {
                query,
                explain,
                timing,
            }) => {
                assert_eq!(query, "SELECT 1");
                assert!(!explain);
                assert!(!timing);
            }
            _ => panic!("Expected Query command"),
        }

        Ok(())
    }

    #[test]
    fn test_query_with_flags() -> Result<()> {
        let args = vec!["cqlite", "query", "--explain", "--timing", "SELECT 1"];
        let cli = Cli::try_parse_from(args)?;

        match cli.command {
            Some(Commands::Query {
                query,
                explain,
                timing,
            }) => {
                assert_eq!(query, "SELECT 1");
                assert!(explain);
                assert!(timing);
            }
            _ => panic!("Expected Query command with flags"),
        }

        Ok(())
    }

    #[test]
    fn test_admin_commands() -> Result<()> {
        // Test admin info
        let args = vec!["cqlite", "admin", "info"];
        let cli = Cli::try_parse_from(args)?;

        match cli.command {
            Some(Commands::Admin { command }) => match command {
                AdminCommands::Info => {}
                _ => panic!("Expected Info admin command"),
            },
            _ => panic!("Expected Admin command"),
        }

        // Test admin backup
        let args = vec!["cqlite", "admin", "backup", "/tmp/backup.db"];
        let cli = Cli::try_parse_from(args)?;

        match cli.command {
            Some(Commands::Admin { command }) => match command {
                AdminCommands::Backup {
                    destination,
                    compression,
                } => {
                    assert_eq!(destination, PathBuf::from("/tmp/backup.db"));
                    assert_eq!(compression, 6);
                }
                _ => panic!("Expected Backup admin command"),
            },
            _ => panic!("Expected Admin command"),
        }

        Ok(())
    }

    #[test]
    fn test_schema_commands() -> Result<()> {
        // Test schema list
        let args = vec!["cqlite", "schema", "list"];
        let cli = Cli::try_parse_from(args)?;

        match cli.command {
            Some(Commands::Schema { command }) => match command {
                SchemaCommands::List => {}
                _ => panic!("Expected List schema command"),
            },
            _ => panic!("Expected Schema command"),
        }

        // Test schema describe
        let args = vec!["cqlite", "schema", "describe", "users"];
        let cli = Cli::try_parse_from(args)?;

        match cli.command {
            Some(Commands::Schema { command }) => match command {
                SchemaCommands::Describe { table } => {
                    assert_eq!(table, "users");
                }
                _ => panic!("Expected Describe schema command"),
            },
            _ => panic!("Expected Schema command"),
        }

        Ok(())
    }

    #[test]
    fn test_bench_commands() -> Result<()> {
        // Test read benchmark
        let args = vec![
            "cqlite",
            "bench",
            "read",
            "--operations",
            "1000",
            "--concurrency",
            "4",
        ];
        let cli = Cli::try_parse_from(args)?;

        match cli.command {
            Some(Commands::Bench { command }) => match command {
                BenchCommands::Read {
                    operations,
                    concurrency,
                    table,
                } => {
                    assert_eq!(operations, 1000);
                    assert_eq!(concurrency, 4);
                    assert_eq!(table, None);
                }
                _ => panic!("Expected Read bench command"),
            },
            _ => panic!("Expected Bench command"),
        }

        Ok(())
    }

    #[test]
    fn test_global_options() -> Result<()> {
        let args = vec![
            "cqlite",
            "--database",
            "/tmp/test.db",
            "--config",
            "/tmp/config.toml",
            "--format",
            "json",
            "--verbose",
            "--auto-detect",
            "--cassandra-version",
            "5.0",
            "query",
            "SELECT 1",
        ];
        let cli = Cli::try_parse_from(args)?;

        assert_eq!(cli.database, Some(PathBuf::from("/tmp/test.db")));
        assert_eq!(cli.config, Some(PathBuf::from("/tmp/config.toml")));
        assert_eq!(cli.verbose, 1);
        assert!(!cli.quiet);
        assert!(cli.auto_detect);
        assert_eq!(cli.cassandra_version, Some("5.0".to_string()));

        Ok(())
    }

    #[test]
    fn test_invalid_command_parsing() -> Result<()> {
        // Test invalid subcommand
        let args = vec!["cqlite", "invalid-command"];
        let result = Cli::try_parse_from(args);
        assert!(result.is_err(), "Should reject invalid command");

        // Test missing required argument
        let args = vec!["cqlite", "admin", "backup"];
        let result = Cli::try_parse_from(args);
        assert!(result.is_err(), "Should reject missing backup path");

        Ok(())
    }

    /// Parameterized test for invalid CLI arguments (Issue #20 - rstest adoption)
    #[rstest]
    #[case(&["cqlite", "invalid-command"], "invalid subcommand")]
    #[case(&["cqlite", "admin", "backup"], "missing backup path")]
    #[case(&["cqlite", "--format", "invalid-format", "query", "SELECT 1"], "invalid format")]
    #[case(&["cqlite", "--unknown-flag"], "unknown flag")]
    fn test_invalid_arguments_rejected(#[case] args: &[&str], #[case] description: &str) {
        let result = Cli::try_parse_from(args.to_vec());
        assert!(result.is_err(), "Should reject {}", description);
    }

    /// Parameterized test for valid Cassandra versions (Issue #20 - rstest adoption)
    #[rstest]
    #[case("3.11")]
    #[case("4.0")]
    #[case("5.0")]
    fn test_valid_cassandra_versions(#[case] version: &str) {
        let args = vec![
            "cqlite",
            "--cassandra-version",
            version,
            "query",
            "SELECT 1",
        ];
        let result = Cli::try_parse_from(args);
        assert!(
            result.is_ok(),
            "Should accept Cassandra version {}",
            version
        );

        let cli = result.unwrap();
        assert_eq!(cli.cassandra_version, Some(version.to_string()));
    }
}

#[cfg(test)]
mod output_format_tests {
    use super::*;
    use cqlite_cli::cli::OutputFormat;

    /// Parameterized test for output format parsing (Issue #20 - rstest adoption)
    #[rstest]
    #[case("table", OutputFormat::Table)]
    #[case("json", OutputFormat::Json)]
    #[case("csv", OutputFormat::Csv)]
    #[case("TABLE", OutputFormat::Table)] // Case insensitivity
    #[case("Json", OutputFormat::Json)] // Mixed case
    #[case("CSV", OutputFormat::Csv)] // All caps
    fn test_output_format_parsing_parameterized(
        #[case] input: &str,
        #[case] expected: OutputFormat,
    ) {
        let result = input.parse::<OutputFormat>();
        assert!(result.is_ok(), "Failed to parse format: {}", input);
        assert_eq!(result.unwrap(), expected);
    }

    /// Parameterized test for invalid format rejection
    #[rstest]
    #[case("invalid")]
    #[case("xml")]
    #[case("")]
    #[case("jsonl")]
    fn test_invalid_format_rejected(#[case] input: &str) {
        let result = input.parse::<OutputFormat>();
        assert!(result.is_err(), "Should reject invalid format: '{}'", input);
    }

    /// Parameterized test for output format display (Issue #20 - rstest adoption)
    #[rstest]
    #[case(OutputFormat::Table, "table")]
    #[case(OutputFormat::Json, "json")]
    #[case(OutputFormat::Csv, "csv")]
    fn test_output_format_display_parameterized(
        #[case] format: OutputFormat,
        #[case] expected: &str,
    ) {
        assert_eq!(format!("{}", format), expected);
    }

    // Keep original tests for backwards compatibility
    #[test]
    fn test_output_format_parsing() -> Result<()> {
        // Test valid formats
        assert_eq!(
            "table".parse::<OutputFormat>().unwrap(),
            OutputFormat::Table
        );
        assert_eq!("json".parse::<OutputFormat>().unwrap(), OutputFormat::Json);
        assert_eq!("csv".parse::<OutputFormat>().unwrap(), OutputFormat::Csv);

        // Test case insensitivity
        assert_eq!(
            "TABLE".parse::<OutputFormat>().unwrap(),
            OutputFormat::Table
        );
        assert_eq!("Json".parse::<OutputFormat>().unwrap(), OutputFormat::Json);

        // Test invalid format
        let result = "invalid".parse::<OutputFormat>();
        assert!(result.is_err(), "Should reject invalid format");

        Ok(())
    }

    #[test]
    fn test_output_format_display() -> Result<()> {
        assert_eq!(format!("{}", OutputFormat::Table), "table");
        assert_eq!(format!("{}", OutputFormat::Json), "json");
        assert_eq!(format!("{}", OutputFormat::Csv), "csv");

        Ok(())
    }
}

#[cfg(test)]
mod error_handling_tests {
    use super::*;

    #[test]
    fn test_database_initialization_errors() -> Result<()> {
        // Test with invalid database path
        let _invalid_path = PathBuf::from("/root/readonly/invalid.db");
        let _config = cqlite_cli::config::Config::default();

        // This should be tested when compilation is fixed
        // let result = cqlite_cli::initialize_database(&invalid_path, &config).await;
        // assert!(result.is_err(), "Should fail with invalid path");

        Ok(())
    }

    #[test]
    fn test_schema_validation_errors() -> Result<()> {
        let temp_dir = TempDir::new()?;

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

        // This should be tested when compilation is fixed
        // let result = cqlite_cli::commands::schema::validate_schema(&invalid_json_path).await;
        // assert!(result.is_err(), "Should reject invalid JSON");

        // Test invalid CQL schema
        let invalid_cql_path = temp_dir.path().join("invalid.cql");
        std::fs::write(&invalid_cql_path, "INVALID SQL SYNTAX")?;

        // This should be tested when compilation is fixed
        // let result = cqlite_cli::commands::schema::validate_schema(&invalid_cql_path).await;
        // assert!(result.is_err(), "Should reject invalid CQL");

        Ok(())
    }
}

#[cfg(test)]
mod utility_tests {
    use super::*;

    #[test]
    fn test_version_detection() -> Result<()> {
        // Test auto-detection with various SSTable formats
        // This will be implemented once compilation is fixed

        Ok(())
    }

    #[test]
    fn test_cassandra_version_validation() -> Result<()> {
        // Test valid versions
        let valid_versions = vec!["3.11", "4.0", "5.0"];
        for _version in valid_versions {
            // This should be tested when compilation is fixed
            // let result = cqlite_cli::cli::validate_cassandra_version(version);
            // assert!(result.is_ok(), "Should accept version {}", version);
        }

        // Test invalid versions
        let invalid_versions = vec!["2.0", "99.0", "invalid"];
        for _version in invalid_versions {
            // This should be tested when compilation is fixed
            // let result = cqlite_cli::cli::validate_cassandra_version(version);
            // assert!(result.is_err(), "Should reject version {}", version);
        }

        Ok(())
    }

    #[test]
    fn test_path_validation() -> Result<()> {
        use std::path::Path;

        // Test existing path
        let temp_dir = TempDir::new()?;
        assert!(temp_dir.path().exists());

        // Test non-existing path
        let non_existing = Path::new("/this/path/does/not/exist");
        assert!(!non_existing.exists());

        Ok(())
    }
}

/// Test data structures and helpers
#[cfg(test)]
mod test_helpers {

    /// Create a sample schema for testing
    #[allow(dead_code)]
    pub fn create_test_schema() -> cqlite_core::schema::TableSchema {
        use cqlite_core::schema::{
            ClusteringColumn, ClusteringOrder, Column, KeyColumn, TableSchema,
        };
        use std::collections::HashMap;

        TableSchema {
            keyspace: "test_keyspace".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "uuid".to_string(),
                position: 0,
            }],
            clustering_keys: vec![ClusteringColumn {
                name: "created_at".to_string(),
                data_type: "timestamp".to_string(),
                position: 0,
                order: ClusteringOrder::Asc,
            }],
            columns: vec![
                Column {
                    name: "id".to_string(),
                    data_type: "uuid".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "name".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "created_at".to_string(),
                    data_type: "timestamp".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
        }
    }

    /// Create test data for benchmarking
    #[allow(dead_code)]
    pub fn create_test_data(size: usize) -> Vec<(String, String)> {
        (0..size)
            .map(|i| (format!("key_{}", i), format!("value_{}", i)))
            .collect()
    }

    /// Validate test output format
    #[allow(dead_code)]
    pub fn validate_output_format(output: &str, format: &str) -> bool {
        match format {
            "json" => output.trim_start().starts_with('{') || output.trim_start().starts_with('['),
            "csv" => output.lines().any(|line| line.contains(',')),
            "table" => output.contains('|') || output.contains('+'),
            _ => false,
        }
    }
}

/// Regression tests for previously fixed bugs
#[cfg(test)]
mod regression_tests {
    use super::*;

    #[test]
    fn test_memory_leak_in_large_queries() -> Result<()> {
        // This would test for memory leaks during large query processing
        // Implementation depends on compilation being fixed
        Ok(())
    }

    #[test]
    fn test_concurrent_database_access() -> Result<()> {
        // This would test for race conditions in concurrent access
        // Implementation depends on compilation being fixed
        Ok(())
    }

    #[test]
    fn test_sstable_corruption_handling() -> Result<()> {
        // This would test graceful handling of corrupted SSTable files
        // Implementation depends on compilation being fixed
        Ok(())
    }
}